branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>#include <LiquidCrystal.h> #include <Servo.h> #include <CapacitiveSensor.h> /* * Arduino Knock Lock Box with Piezo/Capacitive Touch Alarm System and Servo Lock * Built Using Projects 11, 12, 13 from the Arduino Projects Book and * <NAME>'s "Secret Knock Detecting Door Lock" from: https://www.instructables.com/id/Secret-Knock-Detecting-Door-Lock/ * * LCD uses pins 2 - 7 * button uses pin 8 * capacitive touch sensor uses pins 9 - 10 * servo uses pin 11 * LEDs use pins 12 - 13 * piezo uses analog pin A0 * * Tinkercad circuit link: https://www.tinkercad.com/things/7rCGxMmiFTF-knock-lock-box-/editel * NOTE: The DC Motor in the circuit is to represent tinfoil Project Notes: - COULD PROBABLY MAKE A KNOCK/TOUCH DETECTOR BASED ON TIMINGS AND VALUES OF CAPACITIVE SENSOR, HENCE NO KNOCK HEARING BY PEOPLE NEARBY - capacitive sensor with tinfoil behind cardboard does not work too well - surface used for knocking affects whether or not a knock is registered - piezo speaker being half covered by cardboard in my box design may affect if a knock is registered */ //note: order of Arduino Pins that connect to LCD //is order of connection pins in direction of RS to D7 LiquidCrystal lcd(6,7,2,3,4,5);// create lCD instance Servo myServo; // create servo instance CapacitiveSensor capSensor = CapacitiveSensor(10,9); // Pin definitions int greenLED = 12; // Status LED int redLED = 13; // Status LED int piezo = A0; // Piezo sensor for both input and output int buttonPin = 8; // Button for knock input // Constants (adjust as needed) const int capacitanceSensingThreshold = 700; const int knockThreshold = 2; const int rejectValue = 25; const int averageRejectValue = 15; const int knockFadeTime = 150; const int lockTurnTime = 650; const int maximumKnocks = 20; const int nonZeroArrayVal = 6; const int knockComplete = 1500; const int deBounceTime = 20; // Variables. int secretCode[maximumKnocks] = {50, 25, 25, 50, 100, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int knockReadings[maximumKnocks]; // When someone knocks this array fills with delays between knocks. int secretCodeNonZeroValues[nonZeroArrayVal]; int knockReadingsNonZeroValues[nonZeroArrayVal]; int knockSensorValue; boolean buttonPressed = false; boolean locked = true; int toggleState; int buttonState; int lastButtonState; long unsigned lastPress; void setup() { pinMode(redLED, OUTPUT); pinMode(greenLED, OUTPUT); Serial.begin(9600); lcd.begin(16,2); lcd.print("Knock Lock Box"); lcd.setCursor(0,1); lcd.print("LOCKED"); myServo.attach(11); myServo.write(0); digitalWrite(greenLED, LOW); digitalWrite(redLED, LOW); } void loop() { buttonState = digitalRead(buttonPin); if (locked == true) { alarm(); if (buttonState == 1) { buttonPressed = true; pinMode(piezo, INPUT); Serial.println("Button Pressed"); } else { Serial.println("Nothing Pressed"); lcd.setCursor(0,1); lcd.print("LOCKED "); buttonPressed = false; } } if (locked == false) { if (buttonState == 0) { digitalWrite(greenLED, LOW); digitalWrite(redLED, HIGH); } if (buttonState == 1) { locked = true; buttonPressed = false; digitalWrite(greenLED, LOW); digitalWrite(redLED,LOW); lcd.setCursor(0,1); lcd.print("LOCKED "); myServo.write(0); delay(500); } } knockSensorValue = analogRead(piezo); if (buttonPressed == true) { pinMode(piezo, INPUT); listenToSecretKnock(); } } void alarm() { long sensorValue = capSensor.capacitiveSensor(30); if(sensorValue > capacitanceSensingThreshold) { Serial.println(sensorValue); digitalWrite(redLED, HIGH); pinMode(piezo, OUTPUT); tone(piezo, 330); delay(500); digitalWrite(redLED,LOW); noTone(piezo); delay(100); } } boolean validateKnock() { int currentKnockCount = 0; int secretKnockCount = 0; int maxKnockInterval = 0; for (int i=0;i<maximumKnocks;i++) { if (knockReadings[i] > 0) { currentKnockCount++; } if (secretCode[i] > 0) { secretKnockCount++; } if (knockReadings[i] > maxKnockInterval) { maxKnockInterval = knockReadings[i]; } } int j = 0; for (int i=maximumKnocks-1;i>=0;i--) { if (knockReadings[i] > 0) { knockReadingsNonZeroValues[j] = map(knockReadings[i],0, maxKnockInterval, 0, 100);; Serial.print("Knock"); Serial.println(knockReadingsNonZeroValues[j]); j += 1; } } int k = 0; for (int i=maximumKnocks-1;i>=0;i--) { if (secretCode[i] > 0) { secretCodeNonZeroValues[k] = secretCode[i]; Serial.print("Code"); Serial.println(secretCodeNonZeroValues[k]); k += 1; } } // Mid Code Check // Unsure why there are 12 values in each array Serial.println(sizeof(secretCodeNonZeroValues)); for (int i=sizeof(secretCodeNonZeroValues);i>=0;i--) { Serial.print(secretCodeNonZeroValues[i]); Serial.print("-"); } Serial.println(); Serial.println(sizeof(knockReadingsNonZeroValues)); for (int i=sizeof(knockReadingsNonZeroValues);i>=0;i--) { Serial.print(knockReadingsNonZeroValues[i]); Serial.print("-"); } Serial.println(); int totaltimeDifferences=0; int timeDiff=0; // if statement due to during first run, 0 knocks would lead to servo rotation "unlock" if (knockReadingsNonZeroValues[0] != 0) { // was receveing extra values in knockReadings // for loop below only compares the last values in the array to // the secretCode values based on the length of secretCode // We count backwards since extra readings at beginning of the knockReadings for (int a = 0; a < nonZeroArrayVal; a++) { timeDiff = abs(knockReadingsNonZeroValues[a] - secretCodeNonZeroValues[a]); Serial.println("Compare:"); Serial.println(knockReadingsNonZeroValues[a]); Serial.println(secretCodeNonZeroValues[a]); // if (timeDiff > rejectValue){ // Individual value too far out of whack // return false; // } totaltimeDifferences += timeDiff; } // It can also fail if the whole thing is too inaccurate. if (totaltimeDifferences/secretKnockCount>averageRejectValue){ return false; } return true; } else { return false; } } void listenToSecretKnock() { alarm(); digitalWrite(greenLED, HIGH); if (locked = true) { lcd.setCursor(0,1); lcd.print("Listening"); } // reset listening array for (int i = 0; i < maximumKnocks; i++) { knockReadings[i]=0; knockReadingsNonZeroValues[i]=0; secretCodeNonZeroValues[i]=0; } int currentKnock = 0; int now = millis(); int startTime = millis(); delay(knockFadeTime); do{ // listen for knock or timeout knockSensorValue = analogRead(piezo); if (knockSensorValue >= knockThreshold) { now = millis(); knockReadings[currentKnock] = now-startTime; currentKnock++; startTime=now; // reset for next knock delay(knockFadeTime); } now = millis(); // loop as long as each knock before timeout time (knockComplete) and in max num of knocks } while((now-startTime < knockComplete) && (currentKnock < maximumKnocks)); // knock now recorded if (validateKnock() == true) { myServo.write(90); tone(piezo,392,200); delay(150); tone(piezo,440,200); delay(150); tone(piezo,494,200); lcd.setCursor(0,1); lcd.print("UNLOCKED "); locked = false; buttonPressed = false; } else { pinMode(piezo, OUTPUT); for (int i = 0; i < 4; i++) { delay(100); tone(piezo,450,200); digitalWrite(redLED, HIGH); delay(100); digitalWrite(redLED,LOW); } } } <file_sep>Arduino Knock Lock Box with Piezo/Capacitive Touch Alarm System and Servo Lock Built Using Projecs 11, 12, and 13 from the Arduino Projects Book and Steve Hoefer's "Secret Knock Detecting Door Lock" from: https://www.instructables.com/id/Secret-Knock-Detecting-Door-Lock/ Circuit Available at https://www.tinkercad.com/things/7rCGxMmiFTF-knock-lock-box- Working demonstration available at https://www.youtube.com/watch?v=2g22b2d7lAA
74be7bb106598068f7c20d53b1159495639d9ee4
[ "Markdown", "C++" ]
2
C++
Nivram3/Arduino
5dca5b9414c51f1877eada1737fe75ed208cfe58
53d51c505d9dddc8942298afdff6ef5dd60a2939
refs/heads/master
<repo_name>li-fengjie/flask-blog<file_sep>/app/views/user.py import os from flask import Blueprint, render_template, url_for, request, flash, get_flashed_messages, redirect, current_app from app.forms import RegisterForm, LoginForm, UploadForm, FindPwdForm, passwordForm, emailForm from app.models import User from app.exts import db, photos from app.email import send_mail from flask_login import login_required, login_user, logout_user, current_user from PIL import Image users = Blueprint('users', __name__) # 注册 @users.route('/register/', methods=['GET', 'POST']) def register(): form = RegisterForm() if form.validate_on_submit(): u = User(username=form.username.data, password=<PASSWORD>, email=form.email.data) db.session.add(u) db.session.commit() # 生成token 用u对象调用模型中的方法 token = u.generate_active_token() send_mail(u.email, '账户激活', 'email/activate', username=u.username, token=token) flash("恭喜注册成功,请点击邮件中的链接完成激活") return redirect(url_for('users.login')) return render_template('user/register.html', form=form) # 这个方法用来验证token 给用户邮箱发送过去一个完整的url @users.route('/active/<token>', methods=['GET', 'POST']) def active(token): if User.check_active_token(token): flash("账户激活成功") return redirect(url_for('users.login')) else: flash("账户激活失败") return redirect(url_for('main.index')) # 登录 @users.route('/login/', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): u = User.query.filter_by(username=form.username.data).first() if not u: flash("该用户名不存在") elif not u.confirmed: flash("该账户没有激活,请激活后登录") elif u.verify_password(form.password.data): login_user(u, remember=form.remember.data) flash("登录成功") return redirect(request.args.get('next') or url_for("main.index")) else: flash("密码不正确") return render_template('user/login.html', form=form) # 退出登录 @users.route('/logout/', methods=['GET', 'POST']) def logout(): logout_user() flash("退出登录成功") return redirect(url_for('main.index')) @users.route('/test/', methods=['GET', 'POST']) @login_required def test(): return 'this is test' # 找回密码 @users.route('/find_pwd/', methods=['GET', 'POST']) def find_pwd(): form = FindPwdForm() if form.validate_on_submit(): u = User.query.filter_by(username=form.username.data).first() if not u: flash("该用户名不存在") elif not u.email == form.email.data: flash("邮箱不正确!!") else: # 生成token 用u对象调用模型中的方法 token = u.generate_active_token() send_mail(u.email, '密码找回', 'email/findpwd', username=u.username, token=token) flash("请点击邮件中的链接找回密码") return redirect(url_for('users.find_pwd')) return render_template('user/find_pwd.html', form=form) # 这个方法用来验证token 给用户邮箱发送过去一个完整的url 生成新密码 @users.route('/acfpwd/<username>/<token>', methods=['GET', 'POST']) def acfpwd(username, token): if User.check_active_token(token): new_pwd = random_string() u = User.query.filter_by(username=username).first() u.password = <PASSWORD> db.session.commit() flash("新密码为:" + new_pwd) return redirect(url_for('users.login')) else: flash("密码找回失败") return redirect(url_for('main.index')) # 修改密码 @users.route('/change_pwd/', methods=['GET', 'POST']) @login_required def change_pwd(): form = passwordForm() if form.validate_on_submit(): if current_user.verify_password(form.oldPassword.data): current_user.password = form.newPassword1.data # db.session.add(current_user) db.session.commit() flash('密码修改成功') logout_user() flash('请重新登录') return redirect(url_for("users.login")) else: flash('密码修改失败') return render_template('user/change_pwd.html', form=form) # 修改邮箱 @users.route('/change_email/', methods=['GET', 'POST']) @login_required def change_email(): form = emailForm() if form.validate_on_submit(): if current_user.email == form.oldEmail.data: current_user.email = form.newEmail1.data # db.session.add(current_user) db.session.commit() current_user.confirmed = False token = current_user.generate_active_token() send_mail(current_user.email, '账户激活', 'email/activate', username=current_user.username, token=token) flash("请点击邮件中的链接完成激活") return redirect(url_for('users.login')) return render_template('user/change_email.html', form=form) # 修改头像 @users.route('/change_icon/', methods=['GET', 'POST']) @login_required def change_icon(): img_url = '' form = UploadForm() if form.validate_on_submit(): # 获取文件后缀 suffix = os.path.splitext(form.icon.data.filename)[1] # 随机文件名 拼接 filename = random_string() + suffix photos.save(form.icon.data, name=filename) pathname = os.path.join(current_app.config['UPLOADED_PHOTOS_DEST'], filename) img = Image.open(pathname) img.thumbnail((128, 128)) img.save(pathname) if current_user.icon != 'default.jpg': os.remove(current_app.config['UPLOADED_PHOTOS_DEST'], current_user.icon) current_user.icon = filename # 将新上传的文件名 赋值给 用户的头像 db.session.add(current_user) # 保存在数据库中 flash("头像上传成功") return redirect(url_for("users.change_icon")) img_url = photos.url(current_user.icon) return render_template('user/change_icon.html', form=form, img_url=img_url) # 生成随机字符串 def random_string(length=16): import random base_str = '1234567890abcdefhijklmnopqrstuvwxyz' return ''.join(random.choice(base_str) for i in range(length)) <file_sep>/项目第6-天.md # 项目第六天 * flask-sqlalchemy * flask-migrate * 项目架构搭建 及基础代码 ## sqlalchemy 回顾 > innodb 引擎支持外键 ``` 一对多 父表 user 从表 article 外键写在 从表 ``` ## flask-sqlalchemy > pip install flask-sqlalchemy ``` from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_script import Manager app = Flask(__name__) # 数据库的配置变量 HOSTNAME = '127.0.0.1' PORT = '3306' DATABASE = 'ligongdaxue' USERNAME = 'root' PASSWORD = '<PASSWORD>' DB_URI = 'mysql+pymysql://{username}:{password}@{host}:{port}/{db}'.format(username=USERNAME,password=<PASSWORD>,host=HOSTNAME,port=PORT,db=DATABASE) app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False manager = Manager(app) db = SQLAlchemy(app) class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer,primary_key=True,autoincrement=True) username = db.Column(db.String(50),nullable=False) def __repr__(self): return "User(username:%s)" % self.username class Article(db.Model): __tablename__ = 'article' id = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False) title = db.Column(db.String(50), nullable=False) content = db.Column(db.Text, nullable=False) uid = db.Column(db.Integer, db.ForeignKey("user.id")) author = db.relationship("User",backref="articles") def __repr__(self): return "Article(title:%s,content:%s)" % (self.title, self.content) # db.drop_all() db.create_all() user = User(username="qfedu666") article = Article(title="如果你觉得大海是最干净透彻,那是你没有看过我的眼睛",content="我的眼睛更透彻,因为眼里只有你") article.author = user db.session.add(article) db.session.commit() # users = User.query.order_by(User.id.desc()).all() # print(users) users = User.query.filter(User.username=="qfedu666").first() users.username = 'ligong666' db.session.commit() users = User.query.filter(User.username=="qfedu666").first() db.session.delete(users) db.session.commit() @app.route('/') def index(): return 'hello world' if __name__ == "__main__": manager.run() ``` ## flask-migrate > 在开发过程中 经常需要修改数据库 尽量不要手动去修改数据库 而是通过修改 orm模型 来修改数据库 再把它映射到数据库中 最好有一个工具 专门来做这件事情 这个工具就是 flask-migrate 能够跟踪模型的变化并且映射到数据库中 > pip install flask-migrate ``` config.py # 数据库的配置变量 HOSTNAME = '127.0.0.1' PORT = '3306' DATABASE = 'ligongdaxue' USERNAME = 'root' PASSWORD = '<PASSWORD>' DB_URI = 'mysql+pymysql://{username}:{password}@{host}:{port}/{db}'.format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE) SQLALCHEMY_DATABASE_URI = DB_URI SQLALCHEMY_TRACK_MODIFICATIONS = False exts.py #encoding:utf-8 from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() models.py from exts import db class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer,primary_key=True,autoincrement=True) username = db.Column(db.String(50),nullable=False) def __repr__(self): return "User(username:%s)" % self.username class Article(db.Model): __tablename__ = 'article' id = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False) title = db.Column(db.String(50), nullable=False) content = db.Column(db.Text, nullable=False) uid = db.Column(db.Integer, db.ForeignKey("user.id")) author = db.relationship("User",backref="articles") def __repr__(self): return "Article(title:%s,content:%s)" % (self.title, self.content) gongda.py #控制层 中间人 代码在这个文件下 from flask import Flask import config from exts import db #创建实例 gongda = Flask(__name__) #加载配置文件 gongda.config.from_object(config) db.init_app(gongda) @gongda.route('/') def index(): return 'kangbazi666' @gongda.route('/profile/') def profile(): pass if __name__ == "__main__": gongda.run() manager.py 项目的入口文件 只是用来做管理用 from flask_script import Manager from ligong import gongda from exts import db from models import User,Article from flask_migrate import Migrate,MigrateCommand manager = Manager(gongda) #python manage.py runserver -d -r #python manage.py db init #初始化迁移目录 会在 项目中生成一个文件夹 #python manage.py db migrate #生成迁移脚本 #python manager.py db upgrade #将模型映射到数据库中 #python manage.py db --help Migrate(gongda,db) manager.add_command("db",MigrateCommand) if __name__ == "__main__": manager.run() ``` ### 初始化迁移目录 ``` python manage.py db init ``` ### 生成迁移脚本 ``` python manage.py db migrate ``` ### 映射到数据库中 ``` python manage.py db upgrade ``` ### 查看帮助文件 ``` python manage.py db --help ``` <file_sep>/项目第5天.md # 项目第5天 ## flask-mail ``` pip install flask-mail from flask_mail import Mail,Message ligong.config['MAIL_SERVER'] = os.environ.get('MAIL_SERVER','smtp.126.com') ligong.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME','<EMAIL>') ligong.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD','<PASSWORD>') #要在mail对象之前完成 邮箱服务器 用户名 密码等的配置 mail = Mail(ligong) @ligong.route('/') def index(): #创建邮件发送对象 msg = Message(subject='账户激活',recipients=['<EMAIL>','<EMAIL>'],sender=ligong.config['MAIL_USERNAME']) #浏览器查看邮件内容 msg.html = '<h1>请点击以下链接完成激活</h1>' #用客户端查看邮件内容 msg.body = '请点击以下链接完成激活' mail.send(message=msg) return '邮件已经发送' if __name__ == "__main__": manager.run() ``` ## 封装 发送邮件 函数 ``` #封装发送邮件函数 #subject 你要发送给谁 列表 你让用户查看什么样的 模板名称 #由谁发出去 def send_mail(subject,to,template,**kwargs): #创建邮件发送对象 msg=Message(subject=subject,recipients=to,sender=ligong.config['MAIL_USERNAME']) msg.html = render_template(template+'.html',**kwargs) msg.body = render_template(template+'.txt',**kwargs) mail.send(message=msg) @ligong.route('/') def index(): send_mail('墙壁 眼睛 膝盖 wall eye knee',['<EMAIL>','<EMAIL>'],'activate',username='kangbazi') return '邮件已经发送' ``` ## 异步发送邮件 ``` def async_send_mail(app,msg): with app.app_context(): #新创建的线程是没有上下文的 需要手动去创建程序上下文 mail.send(message=msg) def send_to_mail(subject,to,template,**kwargs): #根据current_app 获取到 当前 应用实例 app = current_app._get_current_object() #创建邮件对象 msg = Message(subject=subject,recipients=to,sender=app.config['MAIL_USERNAME']) #网页显示邮件内容 msg.html = render_template(template+'.html',**kwargs) #终端显示邮件内容 msg.body = render_template(template + '.txt', **kwargs) #创建线程 第一个参数 你要让线程 干什么 第二个参数 将参数传递给 第一个参数的方法 thr = Thread(target=async_send_mail,args=[app,msg]) #启动线程 thr.start() return thr send_to_mail('墙壁 眼睛 膝盖 wall eye knee',['<EMAIL>','<EMAIL>'],'activate',username='kangbazi') return '邮件发送成功' ``` ## orm 对象关系映射模型 将类映射到数据库中 ``` class Person(): name = 'kangbazi' age = 18 contry = 'china' p = Person('xx','ss') 类 数据表 属性 字段 对象 数据行 create table person(id int(11),name varchar(32),age int,contry varchar(32))engine=innodb default charset = utf-8 insert into person values(1,'kangbazi',18,'china') from sqlalchemy.ext.declarative import declarative_base # 创建数据库引擎 engine = create_engine(DB_URI) Base = declarative_base(engine) class Person(Base): __tablename__ = 'person' id = Column(Integer,primary_key=True,autoincrement=True) name = Column(String(20)) age = Column(Integer) country =Column(String(20)) def __str__(self): return "Person(id:%d,name:%s,age:%d,country:%s)" % (self.id,self.name,self.age,self.country) #以上用来 更加直观的显示自定的内容 用declarative_base根据 engine 创建一个 基类 Base.metadata.create_all() #将类映射到数据库中 ``` ### 增删改查 > sqlalchemy 数据库增删改查操作需要 一个session的会话对象 来实现 ``` from sqlalchemy.orm import sessionmaker #创建session对象 # Session = sessionmaker(engine) #这是类 # session = Session() session = sessionmaker(engine)() #这才是 session对象 在类中写一个 魔术方法 def __str__(self): return "Person(id:%d,name:%s,age:%d,country:%s)" % (self.id,self.name,self.age,self.country) def add_data(): # p = Person(name='yingjun',age=18,country='China') # session.add(p) p1 = Person(name='xiaojun',age=19,country='Lizhidunshideng') p2 = Person(name='junjun',age=20,country='新加坡') session.add_all([p1,p2]) session.commit() def show_data(): #select * from person all_person = session.query(Person).all() for p in all_person: print(p) # all_person = session.query(Person).filter_by(name="junjun").all() # for p in all_person: # print(p) # all_person = session.query(Person).filter(Person.name=="junjun").all() # for p in all_person: # print(p) oneperson = session.query(Person).first() print(oneperson) def update_data(): p = session.query(Person).first() p.name = 'kangbazijunjun' session.commit() def delete_data(): p = session.query(Person).first() session.delete(p) session.commit() if __name__ == "__main__": #add_data() #show_data() #update_data() delete_data() ``` ## 一对多关系 ```python from sqlalchemy import create_engine,Column,Integer,String,Text,ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker,relationship # 数据库的配置变量 HOSTNAME = '127.0.0.1' PORT = '3306' DATABASE = 'ligongda' USERNAME = 'root' PASSWORD = '<PASSWORD>' DB_URI = 'mysql+pymysql://{username}:{password}@{host}:{port}/{db}'.format(username=USERNAME,password=<PASSWORD>,host=HOSTNAME,port=PORT,db=DATABASE) # 创建数据库引擎 engine = create_engine(DB_URI) Base = declarative_base(engine) session = sessionmaker(engine)() #父表 user 从表 article class User(Base): __tablename__= 'user' id = Column(Integer,primary_key=True,autoincrement=True,nullable=False) username = Column(String(20),nullable=False) def __repr__(self): return "User(username:%s)" % self.username class Article(Base): __tablename__ = 'article' id = Column(Integer, primary_key=True, autoincrement=True, nullable=False) title = Column(String(50), nullable=False) content = Column(Text,nullable=False) uid = Column(Integer,ForeignKey("user.id")) author = relationship("User",backref="users") def __repr__(self): return "Article(title:%s,content:%s)" % (self.title,self.content) # Base.metadata.drop_all() # Base.metadata.create_all() # user = User(username='junjun') # session.add(user) # session.commit() # article = Article(title="java从入门到放弃",content="我不会撩妹,你可不可以撩我一下",uid=1) # session.add(article) # session.commit() # user = session.query(User).first() # session.delete(user) # session.commit() article = session.query(Article).first() uid = article.uid print(uid) user = session.query(User).get(uid) print(user) ``` <file_sep>/app/models/users.py from werkzeug.security import generate_password_hash, check_password_hash from app.exts import db from flask import current_app, flash from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from flask_login import UserMixin from app.exts import login_manager class User(UserMixin, db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False) username = db.Column(db.String(50), nullable=False, unique=True) password_hash = db.Column(db.String(128)) email = db.Column(db.String(128), nullable=False, unique=True) confirmed = db.Column(db.Boolean, default=False) icon = db.Column(db.String(64), default='default.jpg') # lazy 在这里是懒加载 dynamic表示不加载数据但是提供查询 # 如果一对一的关系 需要加上 uselist=Flase posts = db.relationship("Posts", backref="user", lazy="dynamic") # 当前用户通过 user 访问 posts 表中的字段 # 密码不能读 而且永不返回 @property def password(self): raise AttributeError("密码不可读的帅哥") # 设置密码的时候 保存的是加密后的hash值 @password.setter def password(self, password): self.password_hash = generate_password_hash(password) # 校验密码是否正确 正确 true 错误 false # 先加密 再跟数据库比较 def verify_password(self, password): return check_password_hash(self.password_hash, password) # 生成token 通过邮箱发送给用户 def generate_active_token(self, expires_in=3600): s = Serializer(current_app.config['SECRET_KEY'], expires_in=expires_in) return s.dumps({'id': self.id}) # 验证token 方法 @staticmethod def check_active_token(token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return False # 这个id是从 token中解析出来的 然后根据id 到数据库中查找 对应的数据进行更新 u = User.query.get(data.get('id')) if not u: flash("该用户不存在") return False if not u.confirmed: u.confirmed = True db.session.add(u) return True # 登录成功以后 执行以下方法 回调函数 获取登录用户的相关信息 @login_manager.user_loader def load_user(uid): return User.query.get(int(uid)) <file_sep>/项目第1天.md # 项目第一天 下午 ## web 工作原理 * 用户在浏览器中输入域名 * 先到 c:/windows/system32/drivers/etc/ hosts /etc/hosts 查看是否有 用户输入的域名 如果有直接返回对应的ip地址 交给 浏览器 如果没有 就交给 dns服务器 加速 到 顶级域名服务器 对域名进行解析 返回对应的ip地址 交给浏览器 * web服务器 用户提交请求 到指定的服务器 服务器需要立即响应 这个角色就是 nginx 、Apache、iis * web服务器除了响应请求以外还可以响应 静态请求 静态页面 图片 音频等 * 应用服务器 我们的业务逻辑需要 python 、php、j2ee、.net 这些来处理 但是nginx 和 Apache不能直接将动态请求交给 后台语言 需要通过中间人 这个中间人就是 应用服务器 tomcat 、uwsgi * url * http://www.baidu.com:8080/python?page=1&query_string=你的搜索内容#anchor ``` http https: 协议 www.baidu.com :域名 或者 ip地址 8080 端口号 python 你要查看内容的路径 page 参数 query_string 搜索内容 #anchor 锚点 比如 最右下角 回到顶部 ``` * web框架 * flask django * 面向对象 * 面向对象注重的是结果 面向过程注重的是 过程 * 设计模式 * MVC M model 组装车间 一个数据表就是一个model v view 包装车间 c controller 项目经理 * MTV m model 组装车间 t template 包装车间 v view 视图 相当于 项目经理 * 将处理好的结果返回给用户 ## 虚拟环境 virtualenvwrapper ``` 一台服务器上 同时存在 python2 和 python3 A项目 python2 b项目 python3 python2和3之间差别还是有的 同时运行两个项目 要么 A报错 要么B报错 如果让两个项目同时运行 还不报错 这个时候需要虚拟环境 ``` #### 安装 virtualenvwrapper ``` pip install virtualenvwrapper-win windows 安装 pip install virtualenv linux 安装方法 我的电脑 属性 高级系统设置 环境变量 系统变量 新建 变量名 WORKON_HOME 变量值:c:\jiangxiligong ``` #### 创建虚拟环境 ``` mkvirtualenv 环境名字 前面会出现 () 说明当前位于改虚拟环境 C:\jiangxiligong\test13\Scripts\python.exe 记好这个路径 pycharm用到 ``` #### 退出虚拟环境 ``` deactivate ``` #### 切换到指定的虚拟环境 ``` workon 虚拟环境名字 ``` #### 列出所有的虚拟环境 ``` lsvirtualenv ``` #### 删除虚拟环境 ``` rmvirtualenv 虚拟环境名字 ``` #### 切换到指定的虚拟环境 ``` workon 虚拟环境名称 cdvirtualenv ``` ## 安装 flask * 切换到指定的虚拟环境 * pip install flask <file_sep>/README.md ![首页界面](img_01.png) # 项目部署: 用户提交请求 ->nginx ->uwsgi ->python ->数据库 这里用的是非常干净的`ubuntu 16.04`系统环境 ## 在开发机上的准备工作: 1. 确认项目没有bug。 2. 用`pip freeze > requirements.txt`将当前环境的包导出到`requirements.txt`文件中,方便部署的时候安装。 3. 将项目上传到服务器上的`/srv`目录下。这里以`git`为例。使用`git`比其他上传方式(比如使用pycharm)更加的安全,因为`git`有版本管理的功能,以后如果想要回退到之前的版本,`git`轻而易举就可以做到。 4. 在`https://git-scm.com/downloads`下载`Windows`版本的客户端。然后双击一顿点击下一步安装即可。 5. 然后使用码云,在码云上创建一个项目。码云地址:<https://gitee.com/> 6. 然后进入到项目中,使用以下命令做代码提交: ```shell # 初始化一个仓库 * git init # 添加远程的仓库地址 * git remote add origin xxx.git # 添加所有的代码到缓存区 * git add . # 将代码提交到本地仓库 * git commit -m 'first commit' # 从码云仓库上拉数据下来 * git pull origin master --allow-unrelated-histories # 将本地仓库中的代码提交到远程服务器的master分支上 * git push origin master ``` ------ ## 在服务器上的准备工作: 1. ubuntu开启root用户: ``` > sudo passwd root > 然后输入root用户的密码 ``` 2. 为了方便`xshell`或者`CRT`连接服务器,建议安装`OpenSSH`(一般云服务器上都已经安装了): ```shell sudo apt install openssh-server openssh-client service ssh restart ``` 3. 安装`vim`: ```shell sudo apt install vim ``` 4. 修改一下`ubuntu`的`apt`源(云服务器一般都有自己的源,可以不用修改),`apt`源是用来安装软件的链接: 先拷贝`/etc/apt/sources.list`为`/etc/apt/sources.list.bak`,然后用`vi`编辑`/etc/apt/sources.list`,删除`sources.list`中的其他内容,将下面代码粘贴到文件中。然后保存: ```shell deb http://mirrors.ustc.edu.cn/ubuntu/ xenial main restricted universe multiverse deb http://mirrors.ustc.edu.cn/ubuntu/ xenial-security main restricted universe multiverse deb http://mirrors.ustc.edu.cn/ubuntu/ xenial-updates main restricted universe multiverse deb http://mirrors.ustc.edu.cn/ubuntu/ xenial-proposed main restricted universe multiverse deb http://mirrors.ustc.edu.cn/ubuntu/ xenial-backports main restricted universe multiverse deb-src http://mirrors.ustc.edu.cn/ubuntu/ xenial main restricted universe multiverse deb-src http://mirrors.ustc.edu.cn/ubuntu/ xenial-security main restricted universe multiverse deb-src http://mirrors.ustc.edu.cn/ubuntu/ xenial-updates main restricted universe multiverse deb-src http://mirrors.ustc.edu.cn/ubuntu/ xenial-proposed main restricted universe multiverse deb-src http://mirrors.ustc.edu.cn/ubuntu/ xenial-backports main restricted universe multiverse ``` 然后更新源: ```shell sudo apt update ``` 5. 安装`MySQL`服务器和客户端: ```shell sudo apt install mysql-server mysql-client ``` 6. 如果是sqlite ``` apt-get install sqlite sqlite3 检查数据库安装结果: sqlite3 .database .exit 安装Sqlite3编译需要的工具包: apt-get install libsqlite3-dev ``` 7. 安装`memcached`: 通过命令`apt install memcached`即可安装。更多的`memcached`的知识点请参考`memcached`那一章节。 8. 安装好项目要用到的`Python`: ``` * sudo apt install python3 * sudo apt install python3-pip * pip install --upgrade pip ``` 如果系统上已经有`Python3`了,就无需再安装了。因为`supervisor`不支持`Python3`,所以还需要安装`Python2`,如果没有,就安装一下: ``` * sudo apt install python2.7 * sudo apt install python-pip ``` 然后输入`python2.7`即可使用了。 如果在输入`pip`的时候提示以下错误: ```shell Traceback (most recent call last): File "/usr/bin/pip", line 9, in from pip import main ImportError: cannot import name main ``` 这是因为`pip 10`的一个`bug`,可以零时使用以下解决方案: 将`/usr/bin/pip`中的: ```python from pip import main if __name__ == '__main__': sys.exit(main()) ``` 改成: ``` from pip import __main__ if __name__ == '__main__': sys.exit(__main__._main()) ``` 9. 安装`virtualenvwrapper`,并创建好项目要用到的虚拟环境: ``` * pip install virtualenvwrapper ``` 安装完`virtualenvwrapper`后,还需要配置`virtualenvwrapper`的环境变量。 - 首先通过`which virtualenvwrapper.sh`命令查看`virtualenvwrapper.sh`文件所在的路径。 - 在当前用户目录下创建`.virtualenv`文件夹,用来存放所有的虚拟环境目录。 - 在当前用户目录下编辑`.bashrc`文件,添加以下代码: ```shell #if [ -f ~/.bash_aliases ]; then 这里可以给它注释掉 # . ~/.bash_aliases #fi # enable programmable completion features (you don't need to enable # this, if it's already enabled in /etc/bash.bashrc and /etc/profile # sources /etc/bash.bashrc). #if [ -f /etc/bash_completion ] && ! shopt -oq posix; then # . /etc/bash_completion #fi if [ -f /usr/local/bin/virtualenvwrapper.sh ]; then export WORKON_HOME=$HOME/.virtualenvs export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3.5 export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv source /usr/local/bin/virtualenvwrapper.sh fi ``` 然后退出`bashrc`文件,输入命令`source ~/.bashrc`。 注意:因为我们是把`virtualenvwrapper`安装在了`python2`的环境中,所以在创建虚拟环境的时候需要使用`--python`参数指定使用哪个`Python`文件。比如我的`python3`的路径是在`/usr/bin/python3`。那么示例代码如下: ```shell mkvirtualenv --python=/usr/bin/python3 xfz-env ``` 10. 安装`git`: ```shell sudo apt install git ``` 11. 使用`git`下载项目代码: ```shell * git init * git remote add origin https://gitee.com/**/** * git pull origin master ``` 12. 进入虚拟环境中,然后进入到项目所在的目录,执行命令:`pip install -r requirements.txt`,安装项目依赖的包。如果提示`OSError: mysql_config not found`,那么再安装`sudo apt install libmysqld-dev`即可。 13. 进入`mysql`数据库中,创建好项目的数据库。 14. 执行`python manage.py migrate/upgrade`将模型映射到数据库中。 15. 执行`python kangbazi.py`,然后在自己电脑上访问这个网站,确保没有BUG。 16. 设置`DEBUG=False`,避免如果你的网站产生错误,而将错误信息暴漏给用户。 ------ ## 安装uwsgi: uwsgi是一个应用服务器,非静态文件的网络请求就必须通过他完成,他也可以充当静态文件服务器,但不是他的强项。uwsgi是使用python编写的,因此通过`pip3 install uwsgi`就可以了。(uwsgi必须安装在系统级别的Python环境中,不要安装到虚拟环境中)。然后创建一个叫做`uwsgi.ini`的配置文件: ```shell [uwsgi] # 必须全部为绝对路径 # 项目的路径 chdir = /blog/ # flask 入口文件 wsgi-file = /blog/manage.py # 回调的app对象 callable = app # Python虚拟环境的路径 home = /root/.virtualenvs/ligong-env # 进程相关的设置 # 主进程 master = true # 最大数量的工作进程 processes = 10 http = :8000 在没有安装nginx 的情况下 选择这个 socket = /blog/blog.sock 安装上了 nginx 选择这个 跟nginx配置文件中的kangbazi 下面的是一样的 # 设置socket的权限 chmod-socket = 666 # 退出的时候是否清理环境 vacuum = true ``` 然后通过命令`uwsgi --ini uwsgi.ini`运行,确保没有错误。然后在浏览器中访问`http://ip地址:8000`,如果能够访问到页面(可能没有静态文件)说明`uwsgi`配置没有问题。 ## 安装和配置nginx: 虽然`uwsgi`可以正常的部署我们的项目了。但我们还是依然要采用`nginx`来作为**web服务器**。使用`nginx`来作为web服务器有以下好处: 1. uwsgi对静态文件资源处理并不好,包括响应速度,缓存等。 2. nginx作为专业的web服务器,暴露在公网上会比uwsgi更加安全一点。 3. 运维起来更加方便。比如要将某些IP写入黑名单,nginx可以非常方便的写进去。而uwsgi可能还要写一大段代码才能实现。 ### 安装: 通过`apt install nginx`即可安装。 ### nginx简单操作命令: - 启动:service nginx start - 关闭:service nginx stop - 重启:service nginx restart - 测试配置文件:service nginx configtest ### 添加配置文件: 在`/etc/nginx/conf.d`目录下,新建一个文件,叫做`blog.conf`,然后将以下代码粘贴进去: ```conf upstream kangbazi{ server unix:///blog/blog.sock; } # 配置服务器 server { # 监听的端口号 listen 80; # 域名 你的服务器的 server_name 192.168.0.101; charset utf-8; # 最大的文件上传尺寸 client_max_body_size 75M; # 静态文件访问的url location /static { # 静态文件地址 alias /blog/app/static; } # 最后,发送所有非静态文件请求到django服务器 location / { uwsgi_pass <PASSWORD>; # uwsgi_params文件地址 include /etc/nginx/uwsgi_params; } } ``` 写完配置文件后,为了测试配置文件是否设置成功,运行命令:`service nginx configtest`,如果不报错,说明成功。 每次修改完了配置文件,都要记得运行`service nginx restart`。 ------ ## 使用supervisor管理`uwsgi`进程: 让supervisor管理uwsgi,可以在uwsgi发生意外的情况下,会自动的重启。 ### 安装supervisor: 因为`supervisor`是用`python`写成的,所以通过`pip`即可安装。 并且因为`supervisor`不支持`python3`,因此需要把`supervisor`安装在`python2`的环境中。 `pip2 install supervisor`。 ### 启动: 在项目的根目录下创建一个文件叫做`supervisor.conf`,然后将以下代码填入到配置文件中: ```conf # supervisor的程序名字 [program:blog] # supervisor执行的命令 command=uwsgi --ini uwsgi.ini # 项目的目录 directory = /blog # 开始的时候等待多少秒 startsecs=0 # 停止的时候等待多少秒 stopwaitsecs=0 # 自动开始 autostart=true # 程序挂了后自动重启 autorestart=true # 输出的log文件 stdout_logfile=/var/log/supervisord.log # 输出的错误文件 stderr_logfile=/var/log/supervisord.err [supervisord] # log的级别 loglevel=debug [inet_http_server] # supervisor的服务器 port = 127.0.0.1:9001 # 用户名和密码 username = admin password = 123 # 使用supervisorctl的配置 [supervisorctl] # 使用supervisorctl登录的地址和端口号 serverurl = http://127.0.0.1:9001 # 登录supervisorctl的用户名和密码 username = admin password = 123 [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface ``` 然后使用命令`supervisord -c supervisor.conf`运行就可以了。 以后如果想要启动`uwsgi`,就可以通过命令`supervisorctl -c supervisor.conf`进入到管理控制台,然后可以执行相关的命令进行管理: - status # 查看状态 - start program_name #启动程序 - restart program_name #重新启动程序 - stop program_name # 关闭程序 - reload # 重新加载配置文件 - quit # 退出控制台 <file_sep>/app/forms/__init__.py from .users import RegisterForm,LoginForm,UploadForm,FindPwdForm,passwordForm,emailForm from .posts import PostForm<file_sep>/app/exts.py from flask_bootstrap import Bootstrap from flask_sqlalchemy import SQLAlchemy from flask_mail import Mail, Message from flask_moment import Moment from flask_uploads import UploadSet, IMAGES, configure_uploads, patch_request_class from flask_migrate import Migrate, MigrateCommand from flask_login import LoginManager # 创建对象 bootstrap = Bootstrap() db = SQLAlchemy() mail = Mail() migrate = Migrate(db=db) moment = Moment() photos = UploadSet('photos', IMAGES) login_manager = LoginManager() # 完成对象 跟 实例的绑定 def config_extensions(app): bootstrap.init_app(app) db.init_app(app) mail.init_app(app) migrate.init_app(app) moment.init_app(app) configure_uploads(app, photos) patch_request_class(app, size=None) # -----------------登录相关设置--------------------- login_manager.init_app(app) # 设置登录提示消息 login_manager.login_message = "需要登录才可以访问" # 设置登录的站点 login_manager.login_view = 'users.login' # session 保护级别 none 不保护 basic 基本保护 strong 强保护 login_manager.session_protection = 'strong' <file_sep>/用户的管理.md # 用户的管理 # 重点 * 注册 * 模板 * 表单验证 * 用户模型 * token生成与验证 * 登录 * 登录逻辑 * flask-login * 用户的信息管理 ## 用户注册激活 1.在base.html中 ``` {% import 'bootstrap/wtf.html' as wtf %} <li><a href="{{url_for('user.register')}}">注册</a></li> ``` 2.在 蓝本 user.py中写明视图函数 ```python @users.route('/register/',methods = ['GET','POST']) def register(): return render_template('user/register.html') ``` 3.register.html ``` {% extends 'common/base.html'%} {% block title%} 用户注册 {% endblock %} {% block content%} {{wtf.quick_form(form)}} {% endblock %} ``` 浏览器分为两大阵营: ​ 1.ie浏览器 ​ 2.w3c浏览器 ​ 谷歌 ​ 苹果 ​ 火狐 ​ opera 4.在app目录下 新建一个目录 forms 用来存放所有的表单 创建两个文件 __init__.py 个 user.py ```python __init__.py from .user import RegisterForm user.py from flask_wtf import FlaskForm from wtforms import StringField,SubmitField,PasswordField from wtforms.validators import DataRequired,Length,EqualTo,Email class RegisterForm(FlaskForm): user = StringField('用户名',validators=[DataRequired(),Length(6,15,message="用户名必须在6到15之间")]) password = PasswordField('密码',validators=[DataRequired(),Length(6,20,message="密码必须在6到20之间")]) confirm = PasswordField('密码',validators=[EqualTo('password',message="两次密码不一致")]) email = StringField("邮箱",validators=[Email(message="邮箱格式错误")]) submit = SubmitField("立即注册") ``` 5.在视图函数中创建一个表单对象 并渲染到模板中 ```python @users.route('/register/',methods = ['GET','POST']) def register(): form = RegisterForm() if form.validate_on_submit(): #如果用户提交正常 根据表单数据 创建用户对象 #然后将数据保存到数据库 #发送用户账户激活的邮件 #弹出消息 提示用户 flash("恭喜注册成功,请点击邮件中的链接完成激活") return redirect(url_for("main.index")) return render_template('user/register.html',form=form) ``` 6.创建用户模型 并迁移脚本 在app下面 创建一个 models 用来存放所有的模型 __init__.py user.py ```python __init__.py from .user import User 这里一定要包含一次 user.py from app.extensions import db from werkzeug.security import generate_password_hash,check_password_hash 加密 检测 class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer,primary_key=True,autoincrement=True) username = db.Column(db.String(50),nullable=False,unique=True) password_hash = db.Column(db.String(64)) email = db.Column(db.String(50),unique=True) confirmed = db.Column(db.Boolean,default=False) #保护密码 不被查看 @property def password(self): #防止任何形式的查看密码 #修改密码 首先输入旧密码 在输入新密码 raise AttributeError("用户密码不可读属性") #更新密码 必须加密以后再存入数据库 @password.setter def password(self,rr): self.password_hash = d(password) ``` 7.完成ORM 映射到数据表 manage.py ``` import os from flask_script import Manager from flask_migrate import MigrateCommand #因为已经在 扩展文件中 from app import create_app app = create_app(os.environ.get('FLASK_CONFIG') or 'default') manager = Manager(app) manager.add_command("db",MigrateCommand) if __name__ == '__main__': manager.run() python manage.py db init #初始化迁移目录 python manage.py db migrate #生成迁移脚本 python manage.py db upgrade #映射到数据库 ``` 8.账户激活是的token生成 与验证 ``` # @mains.route('/token/') # def token(): # s = Serializer(current_app.config['SECRET_KEY'],expires_in=3600) # return s.dumps({'id':666}) # @mains.route('/check/') # def check(): # t = '<KEY>' # s = Serializer(current_app.config['SECRET_KEY']) # data = s.loads(t) # return str(data['id']) from app.extensions import db from flask import current_app from werkzeug.security import generate_password_hash,check_password_hash from itsdangerous import TimedJSONWebSignatureSerializer as Serializer class User(db.Model): .... #生成账户激活的token def generate_active_token(self,expires_in=3600): s = Serializer(current_app.config['SECRET_KEY'],expires_in=expires_in) return s.dumps({'id':self.id}) #检测账户激活的token def check_active_token(token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return False #data.get('id') 这是从token中获取id 知道是谁点击了激活 u = User.query.get(data.get('id')) #根据这个id 从数据库里查询 if not u: return False if not u.confirmed: #如果该用户没有激活 那么激活 u.confirmed =True db.session.add(u) return Tru' ``` ## 完整的注册 蓝本 user.py ``` from app.email import send_mail @users.route('/register/',methods = ['GET','POST']) def register(): form = RegisterForm() if form.validate_on_submit(): #如果用户提交正常 根据表单数据 创建用户对象 这个password 是加密了密码的 装饰器 u= User(username=form.username.data,password=<PASSWORD>.data,email=form.email.data) #然后将数据保存到数据库 db.session.add(u) db.session.commit() #因为下面token 用到了id 我们这里需要手动提交一下 token = u.generate_active_token() #发送用户账户激活的邮件 send_mail(u.email,'激活您的账户','email/activate',username=u.username,token=token) #弹出消息 提示用户 flash("恭喜注册成功,请点击邮件中的链接完成激活") return redirect(url_for("main.index")) return render_template('user/register.html',form=form) ``` ## 添加激活的路由 蓝本 user.py ``` @users.route('/activate/<token>') def activate(token): #验证token 提取id if User.check_active_token(token): flash("账户已经激活") return redirect(url_for("user.login")) else: flash("激活失败") return redirect(url_for("main.index")) ``` ## 添加激活的模板 email/activate.html activate.txt ``` <h1>hello {{username}}:</h1> <p>请点击该链接用来激活您的账户:<a href="{{ url_for('user.activate',token=token,_external=True) }}">激活</a></p> hello {{username}} 请点击该链接用来激活您的账户:{{ url_for('user.activate',token=token,_external=True) }} ``` # 用户登录 1. 添加登录的跳转链接 ``` <li><a href="{{url_for('user.login')}}">登录</a></li> ``` 2. 登录的视图函数 ``` @users.route('/login/',methods=['GET','POST']) def login(): form = LoginForm() if form.validate_on_submit(): u = User.query.filter_by(username=form.username.data).first() if not u: flash("无效的用户名") elif not u.confirmed: flash("用户尚未激活,请激活以后再登录") elif u.verify_password(form.password.data): flash("登录成功") return redirect(url_for("main.index")) else: flash("无效密码") return render_template('user/login.html',form=form) ``` 3. 登录的模板文件 ``` {% extends 'common/base.html'%} {% block title%}用户登录{% endblock %} {% block content%} {{ wtf.quick_form(form)}} {% endblock %} ``` 4. 登录的表单 ``` class LoginForm(FlaskForm): username = StringField('用户名',validators=[DataRequired()]) password = PasswordField('密码',validators=[DataRequired()]) remember = BooleanField('记住我') submit = SubmitField("立即登录") ``` 5. 表单渲染到模板上 ``` {{ wtf.quick_form(form)}} ``` ## flask-login 扩展 ``` pip install flask-login extension.py from flask_login import LoginManager login_manager = LoginManager() #登录管理初始化 login_manager.init_app(app) #登录站点设置 login_manager.login_view = 'user.login' #指定登录的提示信息 login_manager.login_message = 'you must login before ' #设置session保护级别 none 不保护 basic基本的 strong强保护 login_manager.session_protection = 'strong' 用户模型 models user.py from flask_login import UserMixin #UserMixin 方便判断用户是否是登录 或者匿名用户 class User(UserMixin,db.Model): # 登录成功以后 要有一个回调函数 返回登录 @login_manager.user_loader def load_user(uid): return User.query.get(int(uid)) ``` ## 到 用户蓝本 重新修改 视图函数 ```python from flask_login import login_user,logout_user,login_required,current_user @users.route('/login/',methods=['GET','POST']) def login(): form = LoginForm() if form.validate_on_submit(): u = User.query.filter_by(username=form.username.data).first() if not u: flash("无效的用户名") elif not u.confirmed: flash("用户尚未激活,请激活以后再登录") elif u.verify_password(form.password.data): #正常的 登录 是将userid 写入session 这里使用了扩展 直接 login_user 即可 重点 login_user(u,remember=form.remember.data) flash("登录成功") #用户本意想查看 /user/test 但是 需要登录 登录成功应该跳转到 test页面 #如果没有 next 那么跳转到 首页 重点 return redirect(request.args.get('next') or url_for("main.index")) else: flash("无效密码") return render_template('user/login.html',form=form) # 路由保护 必须登录 @users.route('/test/') @login_required 重点 def test(): return '登录以后才可以查看' ## 退出登录 @users.route('/logout/') def logout(): logout_user() #重点 flash("您已退出登录") return redirect(url_for("main.index")) ``` ## 页面定制 ```html <ul class="nav navbar-nav navbar-right"> {% if current_user.is_authenticated %} <li><a href="{{url_for('user.logout')}}">退出</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{{current_user.username}} <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">个人中心</a></li> <li><a href="#">修改密码</a></li> <li><a href="#">修改邮箱</a></li> <li><a href="#">修改头像</a></li> </ul> </li> {% else %} <li><a href="{{url_for('user.register')}}">注册</a></li> <li><a href="{{url_for('user.login')}}">登录</a></li> {% endif %} </ul> ``` <file_sep>/app/email.py from app.exts import mail from flask_mail import Message from flask import current_app, render_template from threading import Thread # 异步发送邮件 def send_mail(to, subject, template, **kwargs): # 获取当前的app实例 跨页面获取 需要 current_app app = current_app._get_current_object() msg = Message(subject=subject, recipients=[to], sender=app.config['MAIL_USERNAME']) # 浏览器查看邮件内容 msg.html = render_template(template + '.html', **kwargs) # 终端查看邮件内容 msg.body = render_template(template + '.txt', **kwargs) # 创建线程 thr = Thread(target=async_send_mail, args=[app, msg]) thr.start() return thr def async_send_mail(app, msg): with app.app_context(): mail.send(message=msg) <file_sep>/app/forms/users.py from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField, BooleanField from wtforms.validators import DataRequired, Length, EqualTo, Email from wtforms.validators import ValidationError from flask_wtf.file import FileField, FileRequired, FileAllowed from app.models import User # 自定义验证函数 用户提交检测数据中是否存在 from app.exts import photos # 只能上传图片 # 用户注册表单 class RegisterForm(FlaskForm): username = StringField('用户名', validators=[DataRequired(), Length(6, 20, message="用户名必须在6到20位之间")]) email = StringField('Email', validators=[Email(message="邮箱格式不正确")]) password = PasswordField('密码', validators=[DataRequired(), Length(6, 20, message="密码长度必须在6到20位之间")]) confirm = PasswordField('确认密码', validators=[EqualTo('password', message="两次密码不一致")]) submit = SubmitField('立即注册') def validate_username(self, filed): if User.query.filter_by(username=filed.data).first(): raise ValidationError("该用户已经注册请选择其它用户") def validate_email(self, filed): if User.query.filter_by(email=filed.data).first(): raise ValidationError("该邮箱已经被占用请用其它邮箱") # 用户登录表单 class LoginForm(FlaskForm): username = StringField('用户名', validators=[DataRequired(), Length(6, 20, message="用户名必须在6到20位之间")]) password = PasswordField('密码', validators=[DataRequired(), Length(6, 20, message="密码长度必须在6到20位之间")]) remember = BooleanField('记住我') submit = SubmitField('立即登录') # 用户上传表单 class UploadForm(FlaskForm): icon = FileField("头像", validators=[FileRequired(), FileAllowed(photos, message="只能上传图片类型")]) submit = SubmitField('立即上传') # 找回密码表单 class FindPwdForm(FlaskForm): username = StringField('用户名', validators=[DataRequired(), Length(6, 20, message="用户名必须在6到20位之间")]) email = StringField('Email', validators=[Email(message="邮箱格式不正确")]) submit = SubmitField('立即提交') # 修改密码表单 class passwordForm(FlaskForm): oldPassword = PasswordField('旧密码', validators=[DataRequired(), Length(6, 20, message="密码长度必须在6到20位之间")]) newPassword1 = PasswordField('新密码', validators=[DataRequired(), Length(6, 20, message="密码长度必须在6到20位之间")]) newPassword2 = PasswordField('确认密码', validators=[DataRequired(), Length(6, 20, message="密码长度必须在6到20位之间"), EqualTo('newPassword1', message="新密码两次输入不一致")]) submit = SubmitField('提交') # 修改邮箱表单 class emailForm(FlaskForm): oldEmail = StringField('旧邮箱', validators=[Email(message="邮箱格式不正确")]) newEmail1 = StringField('新邮箱', validators=[Email(message="邮箱格式不正确")]) newEmail2 = StringField('确认邮箱', validators=[Email(message="邮箱格式不正确"), EqualTo('newEmail1', message="两次邮箱不一致")]) submit = SubmitField('提交') def validate_email(self, filed): if User.query.filter_by(newEmail1=filed.data).first(): raise ValidationError("该邮箱已经被占用请用其它邮箱") <file_sep>/manage.py import os from flask_script import Manager from flask_migrate import MigrateCommand from app import create_app #创建实例 app = create_app(os.environ.get('FLASK_CONFIG') or 'default') manage = Manager(app) manage.add_command('db', MigrateCommand) if __name__ == '__main__': manage.run()<file_sep>/SQLAlchemy介绍和基本使用.md # SQLAlchemy介绍和基本使用 数据库是一个网站的基础。`Flask`可以使用很多种数据库。比如`MySQL`,`MongoDB`,`SQLite`,`PostgreSQL`等。这里我们以`MySQL`为例进行讲解。而在`Flask`中,如果想要操作数据库,我们可以使用`ORM`来操作数据库,使用`ORM`操作数据库将变得非常简单。 在讲解`Flask`中的数据库操作之前,先确保你已经安装了以下软件: - `mysql`:如果是在`windows`上,到[官网](http://dev.mysql.com/downloads/windows/)下载。如果是`ubuntu`,通过命令`sudo apt-get install mysql-server libmysqlclient-dev -yq`进行下载安装。 - `MySQLdb`:`MySQLdb`是用`Python`来操作`mysql`的包,因此通过`pip`来安装,命令如下:`pip install mysql-python`。 - `pymysql`:`pymysql`是用`Python`来操作`mysql`的包,因此通过`pip`来安装,命令如下:`pip3 install pymysql`。如果您用的是`Python 3`,请安装`pymysql`。 - `SQLAlchemy`:`SQLAlchemy`是一个数据库的`ORM`框架,我们在后面会用到。安装命令为:`pip3 install SQLAlchemy`。 ### 通过`SQLAlchemy`连接数据库: 首先来看一段代码: ```python pip install SQLAlchemy pip install pymysql from sqlalchemy import create_engine # 数据库的配置变量 HOSTNAME = '127.0.0.1' PORT = '3306' DATABASE = 'jiangxiligong' USERNAME = 'root' PASSWORD = '<PASSWORD>' DB_URI = 'mysql+pymysql://{username}:{password}@{host}:{port}/{db}'.format(username=USERNAME,password=<PASSWORD>,host=HOSTNAME,port=PORT,db=DATABASE) # 创建数据库引擎 engine = create_engine(DB_URI) #创建连接 with engine.connect() as con: rs = con.execute('SELECT version()') print (rs.fetchone()) ``` 首先从`sqlalchemy`中导入`create_engine`,用这个函数来创建引擎,然后用`engine.connect()`来连接数据库。其中一个比较重要的一点是,通过`create_engine`函数的时候,需要传递一个满足某种格式的字符串,对这个字符串的格式来进行解释: ``` dialect+driver://username:password@host:port/database?charset=utf8 ``` `dialect`是数据库的实现,比如`MySQL`、`PostgreSQL`、`SQLite`,并且转换成小写。`driver`是`Python`对应的驱动,如果不指定,会选择默认的驱动,比如MySQL的默认驱动是`MySQLdb`。`username`是连接数据库的用户名,`password`是连接数据库的密码,`host`是连接数据库的域名,`port`是数据库监听的端口号,`database`是连接哪个数据库的名字。 如果以上输出了`1`,说明`SQLAlchemy`能成功连接到数据库。 ### 用SQLAlchemy执行原生SQL: 我们将上一个例子中的数据库配置选项单独放在一个`constants.py`的文件中,看以下例子: ```python from sqlalchemy import create_engine from constants import DB_URI #连接数据库 engine = create_engine(DB_URI,echo=True) # 使用with语句连接数据库,如果发生异常会被捕获 with engine.connect() as con: # 先删除users表 con.execute('drop table if exists authors') # 创建一个users表,有自增长的id和name con.execute('create table authors(id int primary key auto_increment,'name varchar(25))') # 插入两条数据到表中 con.execute('insert into persons(name) values("abc")') con.execute('insert into persons(name) values("xiaotuo")') # 执行查询操作 results = con.execute('select * from persons') # 从查找的结果中遍历 for result in results: print(result) ```<file_sep>/app/forms/posts.py from flask_wtf import FlaskForm from wtforms import TextAreaField, SubmitField, StringField from wtforms.validators import DataRequired, Length class PostForm(FlaskForm): # 如果要设置指定的属性 可以写 render_kw content = TextAreaField('', render_kw={'placeholder': '这一刻你想说什么'}, validators=[DataRequired(), Length(10, 140, message="说话注意分寸在10~140之间")]) submit = SubmitField("发表") <file_sep>/项目第8天.md # 项目第八天 ## 登录验证 * 添加登录的跳转链接 * 添加登录的视图函数 * 准备模板文件 * 登录表单 * 渲染表单 ``` pip install flask-login exts.py from flask_login import LoginManager login_manager = LoginManager() -----------------登录相关设置--------------------- login_manager.init_app(app) #设置登录提示消息 login_manager.login_message = "需要登录才可以访问" #设置登录的站点 login_manager.login_view = 'users.login' #session 保护级别 none 不保护 basic 基本保护 strong 强保护 login_manager.session_protection = 'strong' from flask_login import login_required,login_user,logout_user,current_user @users.route('/login/',methods=['GET','POST']) def login(): form = LoginForm() if form.validate_on_submit(): u = User.query.filter_by(username=form.username.data).first() if not u: flash("该用户名不存在") elif not u.confirmed: flash("该账户没有激活,请激活后登录") elif u.verify_password(form.password.data): login_user(u,remember=form.remember.data) flash("登录成功") #如果一个方法 受登录保护 url后面会跟一个next参数 登录成功以后跳到next参数的 页面 return redirect( request.args.get('next') or url_for("main.index")) else: flash("密码不正确") return render_template('user/login.html',form=form) @users.route('/logout/',methods=['GET','POST']) def logout(): logout_user() flash("退出登录成功") return redirect(url_for('main.index')) @users.route('/test/',methods=['GET','POST']) @login_required #如果一个方法需要登录保护 直接 加 @login_required 装饰器即可 def test(): return 'this is test' <ul class="nav navbar-nav navbar-right"> {% if current_user.is_authenticated %} <li><a href="{{ url_for('users.logout') }}">退出</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">你好,{{ current_user.username }} <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">个人中心</a></li> <li><a href="#">修改密码</a></li> <li><a href="#">修改邮箱</a></li> <li role="separator" class="divider"></li> <li><a href="#">修改头像</a></li> </ul> </li> {% else %} <li><a href="{{ url_for("users.login") }}">登录</a></li> <li><a href="{{ url_for("users.register") }}">注册</a></li> {% endif %} </ul> ``` ## 修改密码 ``` 1.添加跳转链接 2.准备表单类 原密码 新密码 确认密码 3.添加视图函数 并将其渲染到模板文件 校验成功以后 更新密码即可 4.准备模板文件 ``` ## 找回密码 ``` 1.登录页面添加一个跳转链接 2.渲染指定的模板 需要用户写 邮箱或者用户名 3.校验成功以后 发送邮件 邮件中 url 要带着该用户的id 知道谁要修改密码 4.添加重置密码的视图函数 处理用户点击邮箱中url后的相关操作 5.更新密码 ``` ## 修改邮箱 ``` 1.添加跳转链接 2.准备表单类 3.添加视图函数 并将其渲染到模板文件 校验成功以后 更新邮箱即可 4.准备模板文件 ``` ## 上传头像 ``` 1.添加跳转的链接 2.添加视图函数 渲染到指定的模板 3.准备模板文件 4.flask-uploads 随机文件名 缩略图 5.将图片的名字保存 数据库里的 icon字段 ``` ## 分页原理 ``` http://127.0.0.1:5055/users/lists?page=1 select * from user where name=‘扛把子’ limit (page-1)*5 ,5 每页显示多少个 5 1 0-5 (page-1)*5 2 5-10 3 10-15 7 ``` ## 分页对象 paginate > 返回的是一个Pagination对象 包含相关的参数 ``` pagination = Posts.query.filter_by(rid=0).order_by(Posts.timestamp.desc()).paginate(page,per_page=5,error_out=False) 参数: 1.page 当前页码 2.per_page 每页显示多少条记录 默认20 3.error_out 当分页查询出错是否报404 错误 默认为True 对象的属性 : 1.items 当前页面所有的数据 2.page 当前页码 3.total 总记录数 4.pages:总页码数 5.per_num : 每页多少条 6.prev_num :上一页 7.next_num :下一页 8.has_prev:是否还有上一页 9.has_next:是否还有下一页 对象的方法: 1.prev 上一页的分页对象 2.next 下一页的分页对象 3.iter_pages < 1 2 3 ... 10 11> 如果显示不全 返回True 宏 {#第一个参数 pagination对象 第二个 跳转到哪里去#} {% macro pagination_show(pagination,endpoint) %} <nav aria-label="Page navigation"> <ul class="pagination"> {# 上一页#} <li {% if not pagination.has_prev %} class="disabled" {% else %} {% endif %}> <a href="{% if pagination.has_prev %}{{ url_for(endpoint,page=pagination.prev_num,**kwargs) }}{% else %}#{% endif %}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> {# 中间页码#} {% for p in pagination.iter_pages() %} {% if p %} {# www.baidu.com?page=#} <li {% if pagination.page == p %} class="active" {% endif %}><a href="{{ url_for(endpoint,page=p,**kwargs) }}">{{ p }}</a></li> {% else %} <li><a href="#">&hellip;</a></li> {% endif %} {% endfor %} {# 下一页#} <li {% if not pagination.has_next %} class="disabled" {% else %}{% endif %}> <a href="{% if pagination.has_next %}{{ url_for(endpoint,page=pagination.next_num,**kwargs) }}{% else %}#{% endif %}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> </ul> </nav> {% endmacro %} index.html {{ pagination_show(pagination,'main.index') }} 视图函数 @main.route('/',methods=['GET','POST']) def index(): form = PostForm() if form.validate_on_submit(): if current_user.is_authenticated:#如果登录 #获取当前用户 u = current_user._get_current_object() p = Posts(content=form.content.data,user=u) db.session.add(p) return redirect(url_for('main.index')) else: flash("请先登录") return redirect(url_for('users.login')) #调取所有发表的博客 # posts = Posts.query.filter_by(rid=0).all() #www.baidu.com?page=1 #接收用户 url传递过来的 page参数 page = request.args.get('page',1,type=int) pagination = Posts.query.filter_by(rid=0).order_by(Posts.timestamp.desc()).paginate(page,per_page=5,error_out=False) posts = pagination.items return render_template('main/index.html',form=form,posts=posts,pagination=pagination) ``` <file_sep>/app/views/posts.py from flask import render_template, request, flash, get_flashed_messages, Blueprint, redirect, url_for, jsonify posts = Blueprint('posts', __name__) @posts.route('/collect/<pid>') def collect(pid): return jsonify({'result': 'ok'}) <file_sep>/app/views/__init__.py from .main import main from .user import users from .posts import posts DEFAULT_BLUEPRINT = ( (main, ''), (users, '/users'), (posts, '/posts') ) def config_blueprint(app): for blueprint, url_prefix in DEFAULT_BLUEPRINT: app.register_blueprint(blueprint, url_prefix=url_prefix) <file_sep>/项目第9天.md ## 项目第九天 ## flask-paginate ``` pip install flask-paginate 在蓝本中 from flask_paginate import Pagination,get_page_parameter #这个方法直接获取当前页面 main.route('/',methods=['GET','POST']) def index(): form = PostForm() if form.validate_on_submit(): if current_user.is_authenticated:#如果登录 #获取当前用户 u = current_user._get_current_object() p = Posts(content=form.content.data,user=u) db.session.add(p) return redirect(url_for('main.index')) else: flash("请先登录") return redirect(url_for('users.login')) render_template('main/index.html',form=form,posts=posts,pagination=pagination) page = request.args.get(get_page_parameter(),default=1,type=int) start = (page-1)* current_app.config['PAGE_NUM'] end = start+current_app.config['PAGE_NUM'] posts = Posts.query.slice(start,end) pagination=Pagination(page=page,total=Posts.query.count(),inner_window=2,outer_window=3,bs_version=3) # 0 3 # 3 6 context = { 'form':form, 'posts':posts, 'pagination':pagination } return render_template('main/index.html',**context) 页面上: {{ pagination.links }} 批量添加测试数据 manager = Manager(app) manager.add_command('db', MigrateCommand) @manager.command def posts_test_data(): for x in range(1,250): content = '内容 %s' % x post = Posts(content=content) post.uid = 1 db.session.add(post) db.session.commit() return '恭喜插入成功' python manager.py posts_test_data ``` ## 博客收藏 ``` models/user.py from .posts import Posts favorites = db.relationship('Posts',secondary='collections',backref=db.backref('users',lazy='dynamic'),lazy='dynamic') #判断是否收藏 def is_favorite(self,pid): #获取所有收藏的博客 favorites = self.favorites.all() posts = list(filter(lambda p:p.id == pid ,favorites)) if len(posts)>0: return True return False #添加收藏 def add_favorite(self,pid): p = Posts.query.get(pid) self.favorites.append(p) #取消收藏 def del_favorite(self,pid): p = Posts.query.get(pid) self.favorites.remove(p) models.__init_.py from app.exts import db collections = db.Table('collections', db.Column('users_id',db.Integer,db.ForeignKey('user.id')), db.Column('posts_id',db.Integer,db.ForeignKey('posts.id')), ) {% if current_user.is_authenticated %} <div url="{{ url_for("posts.collect",pid=post.id) }}" class="collect">{% if current_user.is_favorite(post.id)%}取消收藏{% else %}收藏{% endif %}</div> {% endif %} <script type="text/javascript"> $(function () { $('.collect').click(function () { _this = this $.get($(this).attr('url'),function () { if($(_this).text() == "收藏"){ $(_this).text('取消收藏') }else{ $(_this).text('收藏') } }) }) }) </script> ``` <file_sep>/项目第6天.md # 项目第6天 ## flask-sqlalchemy ```python pip install flask-sqlalchemy from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_script import Manager ligong = Flask(__name__) # 数据库的配置变量 HOSTNAME = '1172.16.31.10' PORT = '3306' DATABASE = 'jiangxiligongdaxue' USERNAME = 'root' PASSWORD = '<PASSWORD>' DB_URI = 'mysql+pymysql://{username}:{password}@{host}:{port}/{db}'.format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE) ligong.config['SQLALCHEMY_DATABASE_URI']=DB_URI db = SQLAlchemy(ligong) manager = Manager(ligong) class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer,primary_key=True,autoincrement=True,nullable=False) username = db.Column(db.String(20),nullable=False) def __repr__(self): return "User:(username:%s)" % (self.username) class Article(db.Model): __tablename__ = 'article' id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(50), nullable=False) content = db.Column(db.Text,nullable=False) uid = db.Column(db.Integer,db.ForeignKey("user.id")) author = db.relationship("User",backref="articles") def __repr__(self): return "Article:(title:%s,content:%s)" % (self.title,self.content) db.drop_all() db.create_all() user = User(username="qianfeng") article = Article(title="php是世界上最好的语言",content="开发语言市场行情不错关键看个人") article.author = user db.session.add(article) db.session.commit() # users = User.query.order_by(User.id.desc()).all() # print(users) # users = User.query.filter(User.username == "qianfeng").first() # print(users) # users = User.query.filter(User.username == "qianfeng").first() # users.username = "maowang" # db.session.commit() users = User.query.filter(User.username == "qianfeng").first() db.session.delete(users) db.session.commit() @ligong.route('/') def index(): return '如果我是猫,九条命都跟你过' if __name__ == "__main__": manager.run() ``` ## flask-migrate 使用命令 将模型映射到数据库中 > 这一个迁移工具 跟踪模型的变化 将 模型映射到数据库中 ``` pip install falsk-migrate config.py # 数据库的配置变量 DB_USERNAME = 'root' DB_PASSWORD = '<PASSWORD>' DB_HOST = '127.0.0.1' DB_PORT = '3306' DB_NAME = 'jiangxiligong_demo' DB_URI = 'mysql+pymysql://%s:%s@%s:%s/%s?charset=utf8' % (DB_USERNAME,DB_PASSWORD,DB_HOST,DB_PORT,DB_NAME) SQLALCHEMY_DATABASE_URI = DB_URI SQLALCHEMY_TRACK_MODIFICATIONS = False exts.py from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() models.py from exts import db class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer,primary_key=True,autoincrement=True) username = db.Column(db.String(20),nullable=False) age = db.Column(db.Integer) ligong.py from flask import Flask import config from exts import db ligong = Flask(__name__) ligong.config.from_object(config) #导入配置文件 需要from_object方法 db.init_app(ligong) #将db 跟 ligong进行绑定 @ligong.route('/') def index(): return '迁移脚本测试' if __name__ == "__main__": ligong.run() manage.py #coding:utf-8 from flask_script import Manager from ligong import ligong from exts import db from models import User from flask_migrate import Migrate,MigrateCommand manager = Manager(ligong) Migrate(ligong,db) manager.add_command("db",MigrateCommand) #python manage.py db migrate if __name__ == "__main__": manager.run() #python manage.py runserver -d -r ``` ### 初始化一个迁移目录 ``` python manage.py db init 下一次 就不需要执行这个命令了 除非删了重新初始化 ``` ### 自动检测模型 生成迁移脚本 ``` python manage.py db migrate ``` ### 将迁移脚本映射到数据库中 ``` python manage.py db upgrade ``` ### 查看 帮助文件 ``` python manage.py db --help ``` ## 项目模块分解 * 用户模块 * 注册登录 * 个人中心 * 邮箱激活 * 博客模块 * 发帖回帖 * 分页展示 * restful接口 备选 * 收藏点赞 * 搜索 排序 统计 * 上传到七牛云 ## 环境 * 开发环境 * 测试环境 * 生产环境 ## 项目架构 ``` -jiangxiligong --app ---__init__.py 跟其它目录之前交流的桥梁 每个文件夹 也就是python包都有 static 和templates 除外 ---home ---admin ---config.py ---exts.py ---email.py ---forms.py ---models.py ---static ----js ----css ----images ---templates ----home ----admin --manage.py --requirments.txt #从开发环境 上传到 测试环境服务器需要安装的依赖包 --迁移脚本文件夹 ``` ### 依赖包管理 ``` pip freeze > requirments.txt 将我们虚拟环境下 依赖包全部导出到 文件中 到测试环境服务器 pip install -r requirments.txt #自动从文件中安装 依赖包 ``` ### 编写项目配置文件 ```python import os base_dir = os.path.abspath(os.path.dirname(__file__)) class Config: #密钥 SECRET_KEY = os.environ.get('SECRET_KEY') or 'jiangxiligong' #数据库配置 SQLALCHEMY_COMMIT_ON_TEARDOWN = True SQLALCHEMY_TRACK_MODIFICATIONS = False #邮件发送 MAIL_SERVER = os.environ.get('MAIL_SERVER','smtp.126.com') MAIL_USERNAME = os.environ.get('MAIL_SERVER','<EMAIL>') MAIL_SERVER = os.environ.get('MAIL_SERVER','zxasqw12') #BOOTSTRAP 使用本地的静态文件 BOOTSTRAP_SERVE_LOCAL = True #上传文件 MAX_CONTENT_LENGTH = 1024*1024*8 UPLOADED_PHOTOS_DEST = os.path.join(base_dir,'static/upload') #完成特定环境的初始化 @staticmethod def init_app(): pass ## 开发环境配置 class DevelopmentConfig(Config): SQLALCHEMY_DATABASE_URI = 'sqlite:///'+ os.path.join(base_dir,'static/db/blog-dev.sqlite') #测试环境配置 class TestingConfig(Config): SQLALCHEMY_DATABASE_URI = 'sqlite:///'+ os.path.join(base_dir,'static/db/blog-test.sqlite') #生产环境配置 class ProductionConfig(Config): SQLALCHEMY_DATABASE_URI = 'sqlite:///'+ os.path.join(base_dir,'static/db/blog.sqlite') config = { 'development':DevelopmentConfig, 'testing':TestingConfig, 'production':ProductionConfig, #默认环境 'default':DevelopmentConfig } ``` ## app/__init__.py ``` from flask import Flask,render_template from app.config import config from app.exts import configure_uploads #封装一个函数 专门用来创建 实例app def create_app(config_name): #创建实例 app = Flask(__name__) #配置各种扩展 configure_uploads(app) #初始化 应用配置文件 app.config.from_object(config[config_name]) return app def config_errorhandler(app): @app.errorhandler(404) def page_not_found(e): return render_template('errors/404.html') return render_template('errors/404.html') ``` ### app/exts.py ```python #导入类库 from flask_bootstrap import Bootstrap from flask_sqlalchemy import SQLAlchemy from flask_mail import Mail,Message from flask_moment import Moment from flask_migrate import Migrate,MigrateCommand from flask_uploads import UploadSet,IMAGES,configure_uploads,patch_request_class #创建对象 bootstrap = Bootstrap() db = SQLAlchemy mail = Mail() migrate = Migrate(db=db) moment = Moment() photos = UploadSet('photos',IMAGES) #将扩展库对象跟 我们app进行绑定 def config_extensions(app): bootstrap.init_app(app) db.init_app(app) mail.init_app(app) migrate.init_app(app) moment.init_app(app) configure_uploads(app,photos) patch_request_class(app,size=None) ```
b0b82991f1dca96e4a1f9ff63b810b2ac3b51d92
[ "Markdown", "Python" ]
19
Python
li-fengjie/flask-blog
a67b5ec298e62521622e38992e6a6a7682aa260f
1be79d1c71c914948febbd6f5a05e63b9c746314
refs/heads/main
<repo_name>todd-trowbridge/greeter-app<file_sep>/src/components/Greeter.js import React from "react"; // function based component // function Greeter(props) { // return ( // <div className="greeter"> // <span className="first-word">Hello </span> {props.name || "world"} // </div> // ); // } // class based component class Greeter extends React.Component { // pass in the props constructor(props) { // pass in the props to react via super() super(props); // state this.state = { count: 0, }; } // function to handle onClick handleClick = () => { if (this.state.count >= 10) { this.setState({ count: 0 }) } else { this.setState({ count: this.state.count + 1 }) } } render() { return ( <div className="greeter"> <span className="first-word">Hello </span> {this.props.name || "world"} {/* control + command + space brings up emoji picker */} <button onClick={this.handleClick}>👋</button> <span>{this.state.count}</span> </div> ); } } export default Greeter; <file_sep>/src/components/App.js import "../css/App.css"; import Greeter from "./Greeter"; import Count from "./Count"; function App() { // create a list of users const users = ["Todd", "Lachlan"]; // return html and jsx return ( // return multiple divs by starting with a blank tag <> <div id="hello-world" className="App"> {/* manually assign the name prop */} <Greeter name="<NAME>" /> <Greeter name="<NAME>" /> {/* manually pick which user is passed via id */} <Greeter name={users[0]} /> <Greeter name={users[1]} /> {/* defaults to world (from Greeter.js using ||) */} <Greeter /> {/* map the users list via index for key*/} {users.map((person, index) => { return <Greeter key={index} name={person} />; })} {/* or use the person as the unique key */} {users.map((person) => { return <Greeter key={person} name={person} />; })} </div> <br></br> <div id="count" className="App"> <Count /> </div> {/* close the blank tag */} </> ); } export default App;
dc502ec2ce819ab2aa9b5ce750aabe464f28dde4
[ "JavaScript" ]
2
JavaScript
todd-trowbridge/greeter-app
c31f2159594205ad150d1d3e61820b7452f7bcf4
9eaef05699e32f66390b9940a5bac8ef38e71f7a
refs/heads/master
<file_sep> package com.fpmislata.banco.presentacion.controllers; import com.fpmislata.banco.persistencia.database.DatabaseMigration; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class flywayController { @Autowired DatabaseMigration databaseMigration; @RequestMapping(value = "/migrate", method = RequestMethod.GET) public void migrar(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){ databaseMigration.migrate(); } } <file_sep>package com.fpmislata.banco.presentacion.controllers; import com.fpmislata.banco.negocio.dominio.EntidadBancaria; import com.fpmislata.banco.negocio.servicio.EntidadBancariaService; import com.fpmislata.banco.presentacion.json.JsonTransformer; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller//decimos que es un controlador REST public class EntidadBancariaController { //con autowired buscamos en los aplicationContext.xml la ruta de las dependencias mediante spring @Autowired//lo que necesita está en otro proyecto, tenemos que especificar los nombres de los otros applicationContext en el web.xml EntidadBancariaService entidadBancariaService; @Autowired//lo que necesita esta en el applicationContext.api.xml, en este proyecto JsonTransformer jsonTransformer; //en el web.xml se define los nombres de los applicationContext necesarios, //y también el controlador(dispatcher) que contendrá la url que pondremos para acceder a la api //en el dispatcher-servlet.xml se le dice donde debe buscar el controlador @RequestMapping(value = "/entidadBancaria/{idEntidad}", method = RequestMethod.GET, produces = "application/json") public void entidadBancariaGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @PathVariable("idEntidad") int idEntidad) throws IOException { EntidadBancaria entidadBancaria = entidadBancariaService.get(idEntidad); String jsonSalida = jsonTransformer.toJson(entidadBancaria); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(jsonSalida); } @RequestMapping(value = {"/entidadBancaria"}, method = RequestMethod.POST, consumes = "application/json", produces = "application/json") public void entidadBancariaInsert(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @RequestBody String json) throws IOException { try { EntidadBancaria entidadaBancaria = jsonTransformer.fromJson(json, EntidadBancaria.class); entidadBancariaService.insert(entidadaBancaria); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(json); } catch (Exception ex) { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } @RequestMapping(value = {"/entidadBancaria/{identidadBancaria}"}, method = RequestMethod.PUT, consumes = "application/json", produces = "application/json") public void entidadBancariaUpdate(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @RequestBody String jsonEntrada, @PathVariable("identidadBancaria") int identidadBancaria) throws IOException { try { EntidadBancaria entidadBancaria = (EntidadBancaria) jsonTransformer.fromJson(jsonEntrada, EntidadBancaria.class); entidadBancariaService.update(entidadBancaria); String jsonSalida = jsonTransformer.toJson(entidadBancaria); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(jsonSalida); } catch (Exception ex) { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } @RequestMapping(value = "/entidadBancaria/{idEntidad}", method = RequestMethod.DELETE, produces = "application/json") public void entidadBancariaDelete(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @PathVariable("idEntidad") int idEntidad) throws IOException { if (entidadBancariaService.delete(idEntidad)) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } else { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } @RequestMapping(value = "/entidadBancaria", method = RequestMethod.GET, produces = "application/json") public void entidadBancariaFind(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException { List<EntidadBancaria> entidades = null; try { if (httpServletRequest.getParameter("nombre") == null) { entidades = entidadBancariaService.findAll(); } else { entidades = entidadBancariaService.findByNombre(httpServletRequest.getParameter("nombre")); } String json = jsonTransformer.toJson(entidades); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().println(json); } catch (Exception ex) { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } }
64118d7e1b24c2adf41e8df8a1122ece6fc2428a
[ "Java" ]
2
Java
ralliv/bancoVillar.api
07c21ad6b155bc75aa4d2c4e5f15c1ae48faa694
e43749040ae29fd88ade0bf6f28fbc5dd2a4bfe5
refs/heads/master
<repo_name>BuzweMfaca/IthalaLemfundo<file_sep>/settings.gradle rootProject.name = 'ithala-lemfundo' <file_sep>/src/main/java/za/co/ithalalemfundo/service/dto/package-info.java /** * Data Transfer Objects. */ package za.co.ithalalemfundo.service.dto; <file_sep>/src/main/java/za/co/ithalalemfundo/service/package-info.java /** * Service layer beans. */ package za.co.ithalalemfundo.service;
c4bfc773cf4bc0189932f8434739f926b1b486fb
[ "Java", "Gradle" ]
3
Gradle
BuzweMfaca/IthalaLemfundo
895ca5bcb0d7af7acec93985e456fb6b33c2adac
b88a1f175e27c109b85a2a294eb30c65118167e8
refs/heads/master
<file_sep>import React from "react"; import classes from "./kombucha.module.css"; import Komingredient from "./ingredients/ingredients"; const kombucha = props => { let transformedIngredients = Object.keys(props.ingredients) .map(igkey => { return [...Array(props.ingredients[igkey])].map((_, i) => { //have to use [igkey] instead of .igkey as igkey is string i.e., something.'string' doesnt work return <Komingredient key={igkey + i} type={igkey} />; }); }) .reduce((arr, el) => arr.concat(el)); if (transformedIngredients.length === 0) { transformedIngredients = <p>Please start adding ingredient</p>; } return ( <div className={classes.kombucha}> <Komingredient type="bread-top" /> {transformedIngredients} <Komingredient type="bread-bottom" /> </div> ); }; export default kombucha;
1c5f07ba36eb96e9555fd6f1cedd208e1463c0bf
[ "JavaScript" ]
1
JavaScript
wang0805/komb3
96542db4338b4b3984b5cf50151fc3951cbd4a5b
ea9a78b995bfd197f594ff2275da2e7406b89a88
refs/heads/master
<file_sep># docker-siwapp-sf1 Docker container for siwapp sf1 # Introduction Dockerfile to build a [siwapp](http://www.siwapp.org/) container image. **Warning!** It uses non-official siwapp branch (fork) [darneta/siwapp-sf1](http://github.com/darneta/siwapp-sf1) due to easy setup support and various modifications. ## Version Current Version: **0.5.2** # Installation Pull the image from the docker index. ```bash docker pull darneta/siwapp-sf1:latest ``` # Quick Start Step 1. Start containers ```bash wget https://raw.githubusercontent.com/darneta/docker-siwapp-sf1/master/docker-compose.yml ``` ```bash docker-compose up ``` Step 2. Get siwapp container ip address ``` docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' dockersiwappsf1_siwapp_1 ``` Step 3. Install siwapp (if not already installed) Point your browser to `http://ip-from-previous-step` and complete the installation. Database prameters will be set from mysql container so just click next. # Configuration ## Available environment variables - **DB_HOST**: The database server hostname. - **DB_PORT**: The database server port. - **DB_NAME**: The database name. - **DB_USER**: The database user. - **DB_PASS**: The database password. - **SMTP_USER**: The SMTP user. - **SMTP_PASS**: The SMTP pass. - **SMTP_HOST**: The SMTP host. - **SMTP_PORT**: The SMTP port. <file_sep>#!/bin/bash set -e rm /app/config/databases.yml cp /app/container/databases.yml /app/config/databases.yml rm /app/apps/siwapp/config/factories.yml cp /app/container/factories.yml /app/apps/siwapp/config/factories.yml DB_HOST=${DB_HOST:-} DB_PORT=${DB_PORT:-} DB_NAME=${DB_NAME:-} DB_USER=${DB_USER:-} DB_PASS=${DB_PASS:-} SMTP_HOST=${SMTP_HOST:-} SMTP_PORT=${SMTP_PORT:-} SMTP_USER=${SMTP_USER:-} SMTP_PASS=${SMTP_PASS:-} if [ -n "${MYSQL_PORT_3306_TCP_ADDR}" ]; then DB_HOST=${DB_HOST:-${MYSQL_PORT_3306_TCP_ADDR}} DB_PORT=${DB_PORT:-${MYSQL_PORT_3306_TCP_PORT}} # support for linked sameersbn/mysql image DB_USER=${DB_USER:-${MYSQL_ENV_DB_USER}} DB_PASS=${DB_PASS:-${MYSQL_ENV_DB_PASS}} DB_NAME=${DB_NAME:-${MYSQL_ENV_DB_NAME}} fi sudo sed 's/{{DB_HOST}}/'"${DB_HOST}"'/' -i /app/config/databases.yml sudo sed 's/{{DB_PORT}}/'"${DB_PORT}"'/' -i /app/config/databases.yml sudo sed 's/{{DB_NAME}}/'"${DB_NAME}"'/' -i /app/config/databases.yml sudo sed 's/{{DB_USER}}/'"${DB_USER}"'/' -i /app/config/databases.yml sudo sed 's/{{DB_PASS}}/'"${DB_PASS}"'/' -i /app/config/databases.yml sudo sed 's/{{SMTP_HOST}}/'"${SMTP_HOST}"'/' -i /app/apps/siwapp/config/factories.yml sudo sed 's/{{SMTP_PORT}}/'"${SMTP_PORT}"'/' -i /app/apps/siwapp/config/factories.yml sudo sed 's/{{SMTP_USER}}/'"${SMTP_USER}"'/' -i /app/apps/siwapp/config/factories.yml sudo sed 's/{{SMTP_PASS}}/'"${SMTP_PASS}"'/' -i /app/apps/siwapp/config/factories.yml echo "Waiting for mysql" while ! mysqladmin ping -h"${DB_HOST}" -u "${DB_USER}" -p"${DB_PASS}" --silent; do echo "."; sleep 1 done count="select count(*) from information_schema.tables where table_type = 'BASE TABLE' and table_schema = '${DB_NAME}'" mysql -h ${DB_HOST} --port=${DB_PORT} -u ${DB_USER} -p${DB_PASS} ${DB_NAME} -e "$count" > /tmp/status.txt stat=`cat /tmp/status.txt | tail -1` rm -rf /tmp/status.txt if [ "$stat" != "0" ]; then rm /app/web/config.php cp /app/container/config.php /app/web/config.php fi mkdir -p /app/cache chown www-data:www-data /app -R chmod -R 0766 /app/cache chmod 0766 /app/web/config.php sed -i "s/AllowOverride None/AllowOverride All/g" /etc/apache2/apache2.conf a2enmod rewrite rm -rf /app/cache/* restart cron if [ -f "/run/apache2/apache2.pid" ]; then rm /run/apache2/apache2.pid; fi source /etc/apache2/envvars tail -F /var/log/apache2/* & exec apache2 -D FOREGROUND <file_sep>version: '2' services: db: image: sameersbn/mysql:latest restart: unless-stopped environment: DB_NAME: siwapp DB_USER: siwapp DB_PASS: <PASSWORD> volumes: - /var/lib/mysql postfix: image: catatnight/postfix restart: unless-stopped environment: maildomain: your_domain.com smtp_user: siwapp:siwapp siwapp: image: darneta/siwapp-sf1 restart: unless-stopped links: - db:db - postfix:postfix environment: DB_HOST: db DB_NAME: siwapp DB_USER: siwapp DB_PASS: <PASSWORD> SMTP_USER: siwapp SMTP_PASS: <PASSWORD> SMTP_HOST: postfix SMTP_PORT: 25 expose: - 80 ports: - 80
9d2e5e53f581d8ad7d7a10c28688cdd236bf6042
[ "Markdown", "YAML", "Shell" ]
3
Markdown
darneta/docker-siwapp-sf1
f3985e0aab20c6e97874b13dbd90e966cfa42525
1706480f820c95e1e107e7a033606f8e5e000355
refs/heads/master
<file_sep>var app = angular.module('elementApp', []); app.controller('elementController', function($scope) { var uniqueCount = [1, 2, 6, 8, 2, 3, 6, 7, 1, 4, 5, 3, 8, 1, 2]; var map = {}; for(var i = 0; i < uniqueCount.length; i++) { if(map[uniqueCount[i]] != null) { map[uniqueCount[i]] = map[uniqueCount[i]]+ 1; } else { map[uniqueCount[i]] = 1; } console.log(map) } $scope.output = map; console.log(map) });
9298f09edb0e3263ae053107802d37810cfdcaab
[ "JavaScript" ]
1
JavaScript
samyareddy/AEC
d8fc789d2777e64f1f27bd5a108874a02acef26b
6395d2c2d6c6444ead856f9a08e8b1571eb62128
refs/heads/master
<file_sep>package com.dubbo.demo.provider; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author <NAME> */ public class ProviderMain { public static void main(String[] args) throws Exception { ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("application-context-provider.xml"); classPathXmlApplicationContext.start(); Thread.sleep(1000 * 1000); } }
433115592f1150a0cfc1a9dc2139daea5474fb34
[ "Java" ]
1
Java
sunyang1989/dubbo-ws-demo-master
e3641b8e3b0be4fc77b112a466d612e77116af59
53f45a26114db142dccd9734239b0f880d8a0036
refs/heads/master
<repo_name>httpPrincess/store-updater<file_sep>/methods.py import logging from time import time def dispatcher(message, instance_store, type_store): msg_subject = get_message_subject(message) if msg_subject is None: logging.error('Invalid message format') return if msg_subject == 'instance_type' and 'type' in message: register_type(message['type'], type_store) elif msg_subject == 'instance_info' and 'instance' in message: update_instance(message['instance'], instance_store) else: logging.error('Invalid message ignored: %s', message) def update_instance(instance, instance_store): if not is_proper_instance(instance): logging.error('Invalid instance description %s' % instance) return logging.debug('Updating instance %s ', instance['id']) instance['last_info'] = time() instance_store.update(instance['id'], instance) def register_type(instance_type, type_store): if not is_proper_instance_type(instance_type): logging.error('Invalid instance type: %s', instance_type) return name = instance_type['name'] instance_type['ts'] = time() logging.debug('Registering type: %s', name) type_store.update(name, instance_type) def is_proper_instance_type(instance_type): return 'name' in instance_type def is_proper_instance(instance): return 'id' in instance def get_message_subject(message): if 'subject' not in message: return None return message.pop('subject')<file_sep>/queue_managers/__init__.py import os from queue_managers.rabbit import BlockingPikaManager host = os.getenv('MESSAGING_PORT_5672_TCP_ADDR', 'localhost') port = int(os.getenv('MESSAGING_PORT_5672_TCP_PORT', 5672)) user = os.getenv('MESSAGING_USER', 'guest') password = os.getenv('MESSAGING_PASS', '<PASSWORD>') manager = BlockingPikaManager(host=host, port=port, user=user, password=<PASSWORD>, queue='info') def subscribe(routing_key, callback): manager.subscribe(routing_key, callback) <file_sep>/stores/__init__.py import os from stores.mongo_store import MongoStore config = dict() host = os.getenv('DB_PORT_27017_TCP_ADDR', 'localhost') port = os.getenv('DB_PORT_27017_TCP_PORT', '27017') config['url'] = 'mongodb://%s:%s' % (host, port) config['database'] = os.getenv('DATABASE_NAME', 'metahosting') config['collection'] = os.getenv('TYPE_COLLECTION', 'types') type_store = MongoStore(config=config) config['collection'] = os.getenv('INSTANCE_COLLECTION', 'instances') instance_store = MongoStore(config=config) <file_sep>/run.py #!/usr/bin/env python from queue_managers import subscribe from methods import dispatcher import logging import threading from time import sleep from stores import instance_store, type_store def my_method(): while True: logging.info('heartbeat') sleep(15) if __name__ == "__main__": logger = logging.getLogger() logger.setLevel(logging.DEBUG) logging.debug('Starting store updater...') thread = threading.Thread(target=my_method) thread.start() sleep(5) def my_dispatcher(message): dispatcher(message, instance_store, type_store) subscribe('info', my_dispatcher) <file_sep>/print_usage.sh #/bin/bash echo 'Follwing env variables will be used to configure this service' echo -e "'variable'\t,'default'" grep -h 'os.getenv' * -r | grep -o "'[A-Z_0-9 ]*', '[A-Za-z_0-9 ]*'" <file_sep>/README.md # store-updater meta hosting store-updater [![Build Status](https://travis-ci.org/httpPrincess/store-updater.svg?branch=master)](https://travis-ci.org/httpPrincess/store-updater) Start with links to messaging and store: Preparation: ``` docker run -d --name messaging rabbitmq:3 docker run -d --name db mongo:latest ``` Start: ``` docker run -d --link messaging:messaging --link db:db httpprincess/store-updater ``` <file_sep>/tests/test_methods.py from unittest import TestCase from methods import is_proper_instance_type, dispatcher, is_proper_instance, \ register_type, update_instance from mock import Mock class MethodsTest(TestCase): def setUp(self): self.types = dict() self.types[u'mysql'] = \ {u'description': u'mysql: world leading relational database', u'name': u'mysql', u'ts': 1416402816.064837, u'available': True} self.types[u'virtual1'] = \ {u'description': u'virtual worker for testing purposes', u'name': u'virtual1', u'ts': 1424338658.027424, u'available': True} self.instance = { 'id': '666', 'additional': 'info', 'foo': 'bar' } def tearDown(self): pass def test_is_proper_type(self): for type_name in self.types: res = is_proper_instance_type(self.types[type_name]) self.assertTrue(res) cpy = self.types['mysql'].copy() fields = ['description', 'ts', 'available'] for field in fields: cpy.pop(field) self.assertTrue(is_proper_instance_type(cpy)) cpy = self.types['mysql'].copy() # each type has to have a name! cpy.pop('name') self.assertFalse(is_proper_instance_type(cpy)) def test_is_proper_instance(self): res = is_proper_instance(self.instance) self.assertTrue(res) res = is_proper_instance({'some': 'test'}) self.assertFalse(res) def test_dispatching_types(self): instance_store = Mock() type_store = Mock() type_store.update = Mock(return_value=True) msg = {'subject': 'instance_type', 'type': self.types['mysql']} dispatcher(msg, instance_store, type_store) self.assertEqual(type_store.update.call_count, 1) args, kwargs = type_store.update.call_args self.assertEqual('mysql', args[0]) self.assertTrue('available' in args[1]) self.assertTrue('description' in args[1]) self.assertTrue('ts' in args[1]) def test_register_type(self): type_store = Mock() type_store.update = Mock(return_value=True) register_type({'useless': 'type'}, type_store) self.assertFalse(type_store.update.called) for type_name in self.types: type_store.update = Mock(return_value=True) register_type(self.types[type_name], type_store) args, kwargs = type_store.update.call_args self.assertEqual(type_name, args[0]) self.assertTrue('available' in args[1]) self.assertTrue('description' in args[1]) self.assertTrue('ts' in args[1]) def test_update_instance(self): instance_store = Mock() instance_store.update = Mock(return_value=True) instance = self.instance.copy() instance.pop('id') update_instance(instance, instance_store) self.assertEqual(instance_store.update.call_count, 0) update_instance(self.instance, instance_store) self.assertEqual(instance_store.update.call_count, 1) args, kwargs = instance_store.update.call_args self.assertEqual(self.instance['id'], args[0]) self.assertTrue('last_info' in args[1]) def test_dispatching_instances(self): type_store = Mock() instance_store = Mock() instance_store.update = Mock(return_value=True) msg = {'subject': 'instance_info', 'instance': self.instance} dispatcher(msg, instance_store, type_store) self.assertTrue(instance_store.update.call_count, 1) def test_fooling_dispatcher(self): type_store = Mock() instance_store = Mock() # not possible to register inappropriate instance type msg = {'subject': 'instance_type', 'type': {'useless': 'type'}} dispatcher(msg, instance_store, type_store) self.assertEqual(type_store.call_count, 0) # not possible to register inappropriate instance type msg = {'subject': 'instance_type', 'x-type': {'useless': 'type'}} dispatcher(msg, instance_store, type_store) self.assertEqual(type_store.call_count, 0) # not possible to register inappropriate instance msg = {'subject': 'instance_info', 'x-type': {'useless': 'foobar'}} dispatcher(msg, instance_store, type_store) self.assertEqual(instance_store.call_count, 0) msg = {'subject': 'instance_info', 'instance': {'no-id': 'foobar'}} dispatcher(msg, instance_store, type_store) self.assertEqual(instance_store.call_count, 0) msg = {'ever': 'wonder', 'why': {'we': 'go'}} dispatcher(msg, instance_store, type_store) self.assertEqual(instance_store.call_count, 0) <file_sep>/dockerfile/Dockerfile FROM debian:wheezy MAINTAINER jj RUN useradd updater RUN DEBIAN_FRONTEND=noninteractive apt-get update && apt-get install wget python python-pip -y && \ apt-get clean autoclean && apt-get autoremove && \ rm -rf /var/lib/{apt,dpkg,cache,log} RUN wget -O - --no-check-certificate https://github.com/httpPrincess/store-updater/archive/master.tar.gz | tar zxf - && \ ln -s store-updater-master/ /app WORKDIR /app/ RUN pip install -r /app/requirements.txt && chown -R updater /app/ USER updater CMD /app/print_usage.sh && /app/run.py <file_sep>/requirements.txt pymongo==2.7.2 pika==0.9.14 retrying==1.3.3 <file_sep>/queue_managers/rabbit.py # get yourself a running rabbitmq server with: # docker run -d -p 5672:5672 -p 15672:15672 dockerfile/rabbitmq import pika import logging import json from retrying import retry import threading class BlockingPikaManager(object): def __init__(self, host, port, user='guest', password='<PASSWORD>', queue=None): logging.debug('Messaging initialization') credentials = pika.PlainCredentials(user, password) self.parameters = pika.ConnectionParameters( host=host, port=port, virtual_host='', credentials=credentials) self.connection = self._get_connection(parameters=self.parameters) self.channel = self.connection.channel() if queue is not None: self.channel.queue_declare(queue=queue, durable=True) logging.debug('Connected to messaging') self.thread = threading.Thread(target=self.channel.start_consuming) self.thread.setDaemon(True) @retry(wait_exponential_multiplier=1000, wait_exponential_max=10000) def _get_connection(self, parameters): return pika.BlockingConnection(parameters) def subscribe(self, routing_key, listener): def callback_wrapper(channel, method, properties, body): if properties.content_type != 'application/json': logging.error('Invalid content_type: %s', properties.content_type) channel.basic_reject(delivery_tag=method.delivery_tag, requeue=False) logging.debug('Discarding message: %r', body) return listener(json.loads(body)) channel.basic_ack(delivery_tag=method.delivery_tag) logging.debug('Subscribe request for: %s', routing_key) self.channel.basic_consume(callback_wrapper, queue=routing_key) if not self.thread.is_alive(): self.thread.start()
8959ba0b6c33b5a0ea3215465b513d7850905e10
[ "Markdown", "Python", "Text", "Dockerfile", "Shell" ]
10
Python
httpPrincess/store-updater
0f8bcdd124c74e14f70c312d821e4585c495a29b
a09fc7a9b99e0f8884cf784e61019c04c082b153
refs/heads/master
<file_sep>import { FirstLevel } from "./levels/first_leve"; import { PlaygroundLevel } from "./levels/playground_level"; function main(param: g.GameMainParameterObject): void { const level = new FirstLevel(g.game); // const level = new PlaygrounLevel(g.game); console.log("Game Start!!"); g.game.pushScene(level.scene); } export = main; <file_sep>import { Actor } from "../bases/actor"; import { Level } from "../bases/level"; import { ControllerComponent } from "../components/controller_component"; import { PlayerActor } from "./player_actor"; export class ControllerActor extends Actor { private target: PlayerActor; width = 0; height = 0; constructor(level: Level, width: number, height: number) { super(level); this.width = width; this.height = height; const targets = level.filterActors((actor): actor is PlayerActor => actor instanceof PlayerActor); this.target = targets[0]; this.addComponent(new ControllerComponent(this, this.target)); } updateActor(): void { } setPosition(x: number, y: number) { this._entity.x = x; this._entity.y = y; } } <file_sep>import { Actor } from "./actor"; export abstract class Level { /** * 1タイルの横幅(pixel) */ tileWidth: number = 32; /** * 1タイルの縦幅(pixel) */ tileHeight: number = 32; /** * このレベルのルートエンティティ * シーンのロードが終わったときに初めに初期化されるので、 * null になることはない */ protected _entity!: g.E; /** * このレベルのシーン * シーンとレベルは1対1の関係 */ protected _scene: g.Scene; get scene() { return this._scene; } /** * このレベルで使うアセットIDを持つ */ protected assetIds: string[]; /** * このゲームの横幅 */ private _width: number; get width() { return this._width; } /** * このゲームの縦幅 */ private _height: number; get height() { return this._height; } /** * このシーンに登場するアクター * 継承先のレベルで追加する */ protected actors: Actor[]; /** * ゲームオーバーを表すフラグ * ゲームオーバーは onGameoverメソッドで更新する */ private _gameover = false; get gameover() { return this._gameover; } /** * そのレベルをクリアしたことを表すフラグ */ goal = false; /** * レベルは、ゲーム内の1ステージを表す。 * レベルが描画内容を持つため、使い方はステージに限らない。 * 例えば、移動画面や戦闘画面などの画面としても表現できる。 * @param game このゲームのインスタンス * @param assetIds このレベルで使用するアセットIDの配列 */ constructor(game: g.Game, assetIds: string[]) { this._width = game.width; this._height = game.height; this.assetIds = assetIds; this.actors = []; this._scene = new g.Scene({ game: game, assetIds: this.assetIds }); this._scene.loaded.add(() => { this._entity = new g.E({scene: this.scene}); this.initialize(); }); this.scene.update.add(() => this.update()); } /** * レベルの初期化処理 * シーンのロードが完了したときに実行する初期化処理 * 最初に必要なアクターの配置はここで行う */ abstract initialize(): void; /** * レベルの更新処理 * 毎フレームレベルで行いたい処理はここで行う */ abstract update(): void; /** * レベルに追加したいエンティティを指定する * @param entity 追加したいエンティティ */ append(entity: g.E): void { this._entity.append(entity); } /** * 取得したいアクターを指定するとそのアクターの配列が返ってくる * @param isType 型ガードの関数を渡す */ filterActors<T extends Actor>(isType: (a: Actor) => a is T): T[] { return this.actors.filter(isType); } /** * ゲームオーバーになったときに呼ぶ */ onGameover(): void { this._gameover = true; } } <file_sep>import { Actor } from "../bases/actor"; import { Level } from "../bases/level"; import { BlockComponent } from "../components/block_component"; import { TransformComponent } from "../components/transform_component"; import { Vector2 } from "../utils/vector2"; export class BlockActor extends Actor { protected block: BlockComponent; get activated() { return this.block.activated; } private transform: TransformComponent; get x() { return this.transform.position.x; } get y() { return this.transform.position.y; } constructor(level: Level, x: number, y: number) { super(level); this.block = new BlockComponent(this); this.addComponent(this.block); this.transform = new TransformComponent(this); this.addComponent(this.transform); this.transform.move(new Vector2(x, y)); this._entity.x = this.transform.position.x * this.block.width; this._entity.y = this.transform.position.y * this.block.height; } updateActor(): void { // 何もしない } } <file_sep>import { Actor } from "../bases/actor"; import { Level } from "../bases/level"; export class GroupActor extends Actor { private actors: Array<Actor>; constructor(level: Level, actors: Array<Actor>) { super(level); this.actors = actors; // アクターに別アクターのエンティティをつけれない? // this.actors.forEach(actor => this._entity.append(actor.)); } updateActor(): void { // 何もしない } } <file_sep>import { MetaBlock } from "../enities/meta_block"; import { MetaDataRepositoryInterface } from "../interfaces/meta_data_repository_interface"; import { Vector2 } from "../utils/vector2"; export class JsonRepository implements MetaDataRepositoryInterface { metaBlocks: MetaBlock[] = []; constructor(private readonly scene: g.Scene) { } private load(stage: string): void { this.metaBlocks = this.createBlocks(this.scene.assets[stage] as g.TextAsset); } fetchMetaBlocks(stageName: string): MetaBlock[] { this.load(stageName); return this.metaBlocks; } createBlocks(asset: g.TextAsset): MetaBlock[] { const metas = this.parse(asset).Blocks as any[]; return metas.map(meta => <MetaBlock>{position: new Vector2(meta.x, meta.y)}); } parse(asset: g.TextAsset): any { return JSON.parse(asset.data); } } <file_sep>import { RendererComponent } from "./renderer_component"; export class PlayerComponent extends RendererComponent{ update(): void { // 何もしない } generate(): g.E { return new g.FilledRect({ scene: this.level.scene, cssColor: "#ff0000", width: 32, height: 32 }); } } <file_sep>import { Actor } from "../bases/actor"; import { Level } from "../bases/level"; import { PlayerComponent } from "../components/player_component"; import { TransformComponent } from "../components/transform_component"; import { NeverAgainLevel } from "../levels/never_again_level"; import { Vector2 } from "../utils/vector2"; import { BlockActor } from "./block_actor"; export class PlayerActor extends Actor { // このプレイヤーの移動を担当する private transform: TransformComponent; private get position() { return this.transform.position; } public get x() { return this.position.x; } public get y() { return this.position.y; } // 描画を担当する private player: PlayerComponent; // プレイヤーのフレーム内の移動量(毎フレーム初期化する) private vector = new Vector2(); // シーン内のブロック(ブロックの数は、シーン内で固定) private blocks: BlockActor[] = []; // プレイヤーが歩いたところ private _stepedOns: Vector2[] = []; get stepedOns() { return this._stepedOns; } moved = false; constructor(level: Level) { super(level); this._entity.width = 32; this._entity.height = 32; this.transform = new TransformComponent(this); this.addComponent(this.transform); this.player = new PlayerComponent(this); this.addComponent(this.player); this.blocks = this.level.filterActors<BlockActor>((a): a is BlockActor => a instanceof BlockActor); } updateActor(): void { this.transform.move(this.vector); const length = (this.vector.x * this.vector.x) + (this.vector.y * this.vector.y); if (length > 0) { this.moved = true; } // 衝突判定 this.blocks.filter(block => block.activated).forEach(block => { // ぶつかっていたら元の場所に戻る if (this.isInto(block)) { this.transform.move(this.vector.inverse()); this.moved = false; } }); // 歩いたところを記録する this.addStepedOn(this.x, this.y); this.moved = false; this.vector.initialize(); this.positionUpdate(); } /** * 壁とぶつかっているならtrueを返す * @param block 確認する対象 */ isInto(block: BlockActor): boolean { return (this.position.x === block.x) && (this.position.y === block.y); } move(value: Vector2) { this.vector = value; } /** * プレイヤーの描画位置を更新する */ private positionUpdate() { this._entity.x = this.x * this._entity.width; this._entity.y = this.y * this._entity.height; } private addStepedOn(x: number, y: number): void { // すでに同じ場所を通っている場合は、追加しない for (const index in this._stepedOns) { if (this._stepedOns[index].x === x && this._stepedOns[index].y === y) { if (this.moved) { this.level.onGameover(); } return; } } const position = new Vector2(x, y); this._stepedOns.push(position); (this.level as NeverAgainLevel).stepOn(position); } } <file_sep>import { Vector2 } from '../src/utils/vector2'; describe('Vector2', () => { it('引数なしで生成すると、初期値はx, yともに0であるべき', () => { const vector = new Vector2(); expect(vector.x).toBe(0); expect(vector.y).toBe(0); }); it('引数を指定すると、その値を持ったベクトルが作られるべき', () => { const vector = new Vector2(10, -9); expect(vector.x).toBe(10); expect(vector.y).toBe(-9); }); });<file_sep> /** * 2Dのベクトル(長さや大きさ)を表すクラス */ export class Vector2 { get x() { return this._x; } get y() { return this._y; } constructor( private _x = 0, private _y = 0 ) { } /** * ベクトル値を初期化する */ initialize() { this._x = 0; this._y = 0; } plus(vector: Vector2) { this._x += vector._x; this._y += vector._y; } /** * 逆ベクトルを返す */ inverse(): Vector2 { return new Vector2(-this._x, -this._y); } } <file_sep>import { TileActor } from "../actors/tile_actor"; import { Layer } from "../bases/layer"; import { range } from "../utils/utils"; import { NeverAgainLevel } from "./never_again_level"; export class PlaygroundLevel extends NeverAgainLevel { constructor(game: g.Game) { super(game, []); } initialize(): void { // 各層を作成する // 床の層 this.floorLayer = new Layer(this.scene); this.floorLayer.appends(range(15*14).map(index => { const x = index % 15; const y = Math.floor(index / 15); const tile = new TileActor(this, x, y); return tile; })); this.appendLayer(this.floorLayer, "Floor"); // イベントの層 // キャラクターの層 // UI層 this.scene.append(this._entity); } update(): void { } } <file_sep>import { BackgroundActor } from "../actors/background_actor"; import { BlockActor } from "../actors/block_actor"; import { ControllerActor } from "../actors/controller_actor"; import { GoalBlockActor } from "../actors/goal_block_actor"; import { GoalEventActor } from "../actors/goal_event_actor"; import { PlayerActor } from "../actors/player_actor"; import { StartEventActor } from "../actors/start_event_actor"; import { TileActor } from "../actors/tile_actor"; import { MetaDataRepositoryInterface } from "../interfaces/meta_data_repository_interface"; import { JsonRepository } from "../repositories/json_repository"; import { Vector2 } from "../utils/vector2"; import { NeverAgainLevel } from "./never_again_level"; import { Layer } from "../bases/layer"; import { range } from "../utils/utils"; export class FirstLevel extends NeverAgainLevel { private sounded = false; constructor(game: g.Game) { super(game, [ "stage1", "bgm", "start", "walk", "gameover", "goal", "open", "walk", "gameover_bgm", "goal_bgm" ]); } initialize(): void { this.tiles = []; this.stepedOns = []; this.layers = []; // メタデータの取得 const repository: MetaDataRepositoryInterface = new JsonRepository(this.scene); // 背景の作成 this.actors.push(new BackgroundActor(this)); // 床の層 this.floorLayer = new Layer(this.scene); this.floorLayer.appends(range(15*14).map(index => { const x = index % 15; const y = Math.floor(index / 15); const tile = new TileActor(this, x, y); this.tiles.push(tile); return tile; })); this.appendLayer(this.floorLayer, "Floor"); // 障害物の作成 const metas = repository.fetchMetaBlocks("stage1"); const blocks: BlockActor[] = []; metas.forEach(meta => blocks.push(new BlockActor(this, meta.position.x, meta.position.y))); this.actors.push(...blocks); // スタートとゴールの位置を作成 // スタートとゴールは常に真ん中の下と上にする。 const startPosition: Vector2 = new Vector2(7, 13); const goalPosition: Vector2 = new Vector2(7, 0); // エリアの外側をブロックで囲む const walls: BlockActor[] = this.generateWalls(15, 14, startPosition, goalPosition); walls.forEach(wall => this.actors.push(wall)); // ゴール手前のブロック const goalBlock = new GoalBlockActor(this, goalPosition.x, goalPosition.y + 1); this.actors.push(goalBlock); walls.push(goalBlock); // プレイヤーの作成 this._player = new PlayerActor(this); this.player.move(startPosition); this.actors.push(this.player); // UIの作成 const controller = new ControllerActor(this, g.game.width, g.game.height * 0.3); controller.setPosition(0, g.game.height * 0.7); this.actors.push(controller); // 開始イベント const startEvent = new StartEventActor(this, startPosition.x, startPosition.y); this.actors.push(startEvent); // 終了イベント const goalEvent = new GoalEventActor(this, goalPosition.x, goalPosition.y); this.actors.push(goalEvent); // 通らなくて良い場所 const notSteps: Vector2[] = [ ...blocks.map(block => new Vector2(block.x, block.y)), ...walls.map(wall => new Vector2(wall.x, wall.y)), startPosition, goalPosition ]; // 全ての道を出す for (let y = 0; y < 14; y++) { for (let x = 0; x < 15; x++) { this.stepedOns.push(new Vector2(x, y)); } } // ブロックやスタートとゴールがあるところは除く this.stepedOns = this.stepedOns.filter(el => { const found = notSteps.some(step => step.x === el.x && step.y === el.y); return !found; // notSteps にない場所は、通過すべき場所 }); this.scene.append(this._entity); // ゲームの開始を告げる音と音楽を鳴らす (this.scene.assets.bgm as g.AudioAsset).play(); } update(): void { if (this.gameover && !this.sounded) { (this.scene.assets.bgm as g.AudioAsset).stop(); (this.scene.assets.gameover as g.AudioAsset).play(); (this.scene.assets.gameover_bgm as g.AudioAsset).play(); this.sounded = true; } if (this.goal && !this.sounded) { (this.scene.assets.bgm as g.AudioAsset).stop(); (this.scene.assets.goal_bgm as g.AudioAsset).play(); this.sounded = true; } } generateTiles(tileX: number, tileY: number) { let ary = []; for (let y = 0; y < tileY; y++) { for (let x = 0; x < tileX; x++) { const tileActor = new TileActor(this, x, y); ary.push(tileActor); } } return ary; } } <file_sep># Never Again **never-again** はTypeScriptとAkashicで作られたゲームです。このプロジェクトを改造してゲームを作ったり、Akashicのゲームを作るときの参考にするのも自由です。 利用者は、Akashic の環境構築や実行ができることを前提にしています。 このプロジェクトは、 `typescript-minimal` を元に作られています。 ## 準備 `never-again` を利用するには、素材を自分で用意する必要があります。現在、以下の素材が必要です。 列挙された名前の素材を用意する必要があります。拡張子は、各素材の種類に合わせて用意してください。例えば、音源の場合は ogg, m4a(acc) が必要です。つまり、Akashic の仕様に合わせて用意してください。 ### 絵 なし ### 音源 - bgm - gameover_bgm - gameover - goal_bgm - open - goal - start - walk ## 利用方法 初回のみ、以下のコマンドを実行して、ビルドに必要なパッケージをインストールしてください。 ```sh npm install ``` ### ビルド方法 ```sh npm run build ``` ### 動作確認方法 以下のどちらかを実行後、ブラウザで `http://localhost:3000/game/` にアクセスすることでゲームを実行できます。 * `npm start` * `npm install -g @akashic/akashic-sandbox` 後、 `akashic-sandbox .` ### アセットの更新方法 各種アセットを追加したい場合は、それぞれのアセットファイルを以下のディレクトリに格納します。 * 画像アセット: `image` * スクリプトアセット: `script` * テキストアセット: `text` * オーディオアセット: `audio` これらのアセットを追加・変更したあとに `npm run update` をすると、アセットの変更内容をもとに `game.json` を書き換えることができます。 <file_sep>import { Actor } from "./actor"; export type LayerTag = "Floor" | "Event"; export class Layer { private _entity: g.E; get entity() { return this._entity; } private actors: Array<Actor>; constructor(scene: g.Scene) { this.actors = []; this._entity = new g.E({scene: scene}); } appends(actors: Array<Actor>) { this.actors.push(...actors); actors.forEach(actor => actor.appendTo(this._entity)); } } <file_sep>import { Actor } from "../bases/actor"; import { RendererComponent } from "./renderer_component"; export class LabelComponent extends RendererComponent { private font!: g.DynamicFont; private label!: g.Label; private visible: boolean = false; constructor(actor: Actor, str: string) { super(actor); this.label.text = str; this.label.invalidate(); } show(): void { this.visible = true; } hide(): void { this.visible = false; } update(): void { if (this.visible) { this.label.show(); } else { this.label.hide(); } } generate(): g.E { this.font = new g.DynamicFont({ game: g.game, fontFamily: g.FontFamily.Serif, size: 32 }); this.label = new g.Label({ scene: this.level.scene, font: this.font, text: "SSSS", fontSize: 32, textColor: "White" }); return this.label; } } <file_sep>export function range(length: number): Array<number> { const ary = []; for (let i = 0; i < length; i++) { ary.push(i); } return ary; } <file_sep>import { Actor } from "../bases/actor"; import { RendererComponent } from "./renderer_component"; export class FloorComponent extends RendererComponent { private entity!: g.E; private frame!: g.FilledRect; private filled!: g.FilledRect; get x() { return this.entity.x / 32; } get y() { return this.entity.y / 32; } constructor(actor: Actor) { super(actor); } setPosition(x: number, y: number) { if (this.entity != null) { this.entity.x = x; this.entity.y = y; } } update(): void { // 何もしない } generate(): g.E { this.entity = new g.E({scene: this.level.scene}); const width = 32; const height = 32; this.frame = new g.FilledRect({ scene: this.level.scene, cssColor: "#000000", width: width, height: height, x: 0, y: 0 }); this.entity.append(this.frame); this.filled = new g.FilledRect({ scene: this.level.scene, cssColor: "#C71585", width: width - 2, height: height - 2, x: 1, y: 1 }); this.entity.append(this.filled); return this.entity; } steped() { this.filled.cssColor = "#800000"; } } <file_sep>import { Vector2 } from "../utils/vector2"; /** * ブロックを作るためのメタデータ */ export interface MetaBlock { position: Vector2; // エリアの座標 } <file_sep>import { Actor } from "../bases/actor"; import { Level } from "../bases/level"; import { BackgroundComponent } from "../components/backgound_component"; export class BackgroundActor extends Actor { private background: BackgroundComponent; constructor(level: Level) { super(level); this.background = new BackgroundComponent(this); this.addComponent(this.background); } updateActor(): void { // 何もしない } } <file_sep>import { MetaBlock } from "../enities/meta_block"; export interface MetaDataRepositoryInterface { fetchMetaBlocks(stageName: string): MetaBlock[]; } <file_sep>import { RendererComponent } from "./renderer_component"; export class BlockComponent extends RendererComponent { // trueならぶつかる private _activated = true; get activated() { return this._activated; } private _width = 32; get width() { return this._width; } private _height = 32; get height() { return this._height; } update(): void { // 何もしない } generate(): g.E { return new g.FilledRect({ scene: this.level.scene, cssColor: "#000000", width: 32, height: 32 }); } activate() { this._activated = true; this._entity.show(); } deactivate() { this._activated = false; this._entity.hide(); } } <file_sep>import { Actor } from "../bases/actor"; import { Level } from "../bases/level"; import { LabelComponent } from "../components/label_component"; import { TransformComponent } from "../components/transform_component"; import { Vector2 } from "../utils/vector2"; import { PlayerActor } from "./player_actor"; export class GoalEventActor extends Actor { private transform: TransformComponent; private player: PlayerActor; private label: LabelComponent; private sounded = false; constructor(level: Level, x: number, y: number) { super(level); const players = this.level.filterActors<PlayerActor>((a: Actor): a is PlayerActor => a instanceof PlayerActor); this.player = players[0]; this.label = new LabelComponent(this, "GOAL !!"); this.addComponent(this.label); this.transform = new TransformComponent(this); this.transform.move(new Vector2(x, y)); this.addComponent(this.transform); } updateActor(): void { if (this.player.x === this.transform.position.x && this.player.y === this.transform.position.y) { this.label.show(); if (!this.sounded) { (this.level.scene.assets.goal as g.AudioAsset).play(); this.sounded = true; this.level.goal = true; } } else { this.label.hide(); } } } <file_sep>import { RendererComponent } from "./renderer_component"; export class BackgroundComponent extends RendererComponent { update(): void { // 何もしない } generate(): g.E { const entity = new g.E({scene: this.level.scene}); entity.append(new g.FilledRect({ scene: this.level.scene, cssColor: "#FFFFFF", width: this.level.width, height: this.level.height, })); entity.append(new g.FilledRect({ scene: this.level.scene, cssColor: "#000000", width: 1, height: this.level.height, x: this.level.width / 2, y: 0 })); return entity; } } <file_sep>import { Actor } from "./actor"; import { Level } from "./level"; export abstract class Component { protected actor: Actor; // (このコンポーネントが登録されている)アクターが登録されているレベルを取得する protected get level(): Level { return this.actor.level; } constructor(actor: Actor) { this.actor = actor; } /** * updateメソッドは、登録しているアクターから呼び出される * Actorクラスが呼び出しているので、開発者が明示的に呼び出す必要はない */ abstract update(): void; } <file_sep>import { ControllerActor } from "../actors/controller_actor"; import { PlayerActor } from "../actors/player_actor"; import { Vector2 } from "../utils/vector2"; import { RendererComponent } from "./renderer_component"; export class ControllerComponent extends RendererComponent { private player: PlayerActor; private entity!: g.E; private right!: g.FilledRect; private left!: g.FilledRect; private top!: g.FilledRect; private bottom!: g.FilledRect; constructor(actor: ControllerActor, player: PlayerActor) { super(actor); this.player = player; } update(): void { } getActor(): ControllerActor { return this.actor as ControllerActor; } generate(): g.E { const centerX = this.getActor().width / 2; const centerY = this.getActor().height / 2; this.right = new g.FilledRect({ scene: this.level.scene, cssColor: "#FF0000", width: 32, height: 32, x: centerX + 16, y: centerY + 0, touchable: true }); this.left = new g.FilledRect({ scene: this.level.scene, cssColor: "#00FF00", width: 32, height: 32, x: centerX - (16 + 32), y: centerY + 0, touchable: true }); this.top = new g.FilledRect({ scene: this.level.scene, cssColor: "#0000FF", width: 32, height: 32, x: centerX - 16, y: centerY - 32, touchable: true }); this.bottom = new g.FilledRect({ scene: this.level.scene, cssColor: "#FFFF00", width: 32, height: 32, x: centerX - 16, y: centerY + 32, touchable: true }); // Right this.right.pointDown.add(() => { this.right.cssColor = "black"; this.right.modified(); this.moveRight(); }); this.right.pointUp.add(() => { this.right.cssColor = "#FF0000"; this.right.modified(); }); // Left this.left.pointDown.add(() => { this.left.cssColor = "black"; this.left.modified(); this.moveLeft(); }); this.left.pointUp.add(() => { this.left.cssColor = "#00FF00"; this.left.modified(); }); // Top this.top.pointDown.add(() => { this.top.cssColor = "black"; this.top.modified(); this.moveTop(); }); this.top.pointUp.add(() => { this.top.cssColor = "#0000FF"; this.top.modified(); }); // Bottom this.bottom.pointDown.add(() => { this.bottom.cssColor = "black"; this.bottom.modified(); this.moveBottom(); }); this.bottom.pointUp.add(() => { this.bottom.cssColor = "#FFFF00"; this.bottom.modified(); }); this.entity = new g.E({scene: this.level.scene}); this.entity.append(this.right); this.entity.append(this.left); this.entity.append(this.top); this.entity.append(this.bottom); return this.entity; } moveRight() { if (!this.level.gameover && !this.level.goal) { this.player.move(new Vector2(1, 0)); (this.level.scene.assets.walk as g.AudioAsset).play(); } } moveLeft() { if (!this.level.gameover && !this.level.goal) { this.player.move(new Vector2(-1, 0)); (this.level.scene.assets.walk as g.AudioAsset).play(); } } moveTop() { if (!this.level.gameover && !this.level.goal) { this.player.move(new Vector2(0, -1)); (this.level.scene.assets.walk as g.AudioAsset).play(); } } moveBottom() { if (!this.level.gameover && !this.level.goal) { this.player.move(new Vector2(0, 1)); (this.level.scene.assets.walk as g.AudioAsset).play(); } } } <file_sep>import { Actor } from "../bases/actor"; import { Level } from "../bases/level"; import { TileComponent } from "../components/tile_component"; import { TransformComponent } from "../components/transform_component"; import { Vector2 } from "../utils/vector2"; export class TileActor extends Actor { private tile: TileComponent; private transform: TransformComponent; private get position() { return this.transform.position; } get x() { return this.position.x; } get y() { return this.position.y; } private get width() { return this.tile.width; } private get height() { return this.tile.height; } constructor(level: Level, x: number, y: number) { super(level); this.tile = new TileComponent(this); this.addComponent(this.tile); this.transform = new TransformComponent(this); this.addComponent(this.transform); this.setPosition(x, y); } updateActor(): void { // 何もしない } setPosition(x: number, y: number) { this.transform.move(new Vector2(x, y)); this._entity.x = this.position.x * this.width; this._entity.y = this.position.y * this.height; } /** * 踏んだ場所をコンポーネントに伝える * @param position 踏んだ場所 */ stepOn() { this.tile.stepOn(); } } <file_sep>import { BlockActor } from "../actors/block_actor"; import { FloorActor } from "../actors/floor_actor"; import { PlayerActor } from "../actors/player_actor"; import { TileActor } from "../actors/tile_actor"; import { Layer, LayerTag } from "../bases/layer"; import { Level } from "../bases/level"; import { Vector2 } from "../utils/vector2"; export abstract class NeverAgainLevel extends Level { protected _player!: PlayerActor; get player() { return this._player; } protected floorLayer!: Layer; protected tiles!: TileActor[]; // 通過すべき座標 protected stepedOns!: Vector2[]; /** * 各層を持つ * appendLayerで追加する */ layers!: {layer: Layer; tag: LayerTag}[]; constructor(game: g.Game, assetIds: string[]) { super(game, assetIds); } generateWalls(x: number, y: number, start: Vector2, goal: Vector2) { const ary: BlockActor[] = []; for (let row = 0; row < y; row++) { for (let column = 0; column < x; column++) { if ((column === start.x && row === start.y) || (column === goal.x && row === goal.y)) { continue; } if ( (column === 0) || (column === x-1) || (row === 0) || (row === y-1) ) ary.push(new BlockActor(this, column, row)); } } return ary; } // 通過すべき場所を全て通過しているなら true を返す isAllStepedOn(): boolean { let bool = false; for (const index in this.stepedOns) { const condition = (it: Vector2) => (it.x === this.stepedOns[index].x) && (it.y === this.stepedOns[index].y); bool = this.player.stepedOns.some(condition); if (!bool) { break; } } return bool; } stepOn(position: Vector2) { const floor = this.tiles.filter(tile => (tile.x === position.x) && (tile.y === position.y)); floor[0].stepOn(); } /** * このレベルにレイヤーを追加する * @param layer 追加するレイヤー * @param tag レイヤーの種別 */ appendLayer(layer: Layer, tag: LayerTag): void { this._entity.append(layer.entity); this.layers.push({layer, tag}); } } <file_sep>import { Actor } from "../bases/actor"; import { RendererComponent } from "./renderer_component"; export class TileComponent extends RendererComponent { private entity!: g.E; private frame!: g.FilledRect; private filled!: g.FilledRect; private _width: number; get width() { return this._width; } private _height: number; get height() { return this._height; } constructor(actor: Actor, width = 32, height = 32) { super(actor); this._width = width; this._height = height; } update(): void { // 何もしない } generate(): g.E { this.entity = new g.E({scene: this.level.scene}); const width = 32; const height = 32; this.frame = new g.FilledRect({ scene: this.level.scene, cssColor: "#000000", width: width, height: height, x: 0, y: 0 }); this.entity.append(this.frame); this.filled = new g.FilledRect({ scene: this.level.scene, cssColor: "#C71585", width: width - 2, height: height - 2, x: 1, y: 1 }); this.entity.append(this.filled); return this.entity; } stepOn() { this.filled.cssColor = "#800000"; } } <file_sep>import { Component } from "../bases/component"; import { Vector2 } from "../utils/vector2"; export class TransformComponent extends Component { position: Vector2 = new Vector2(); update(): void { } move(v: Vector2): void { this.position.plus(v); } } <file_sep>import { Level } from "../bases/level"; import { NeverAgainLevel } from "../levels/never_again_level"; import { BlockActor } from "./block_actor"; export class GoalBlockActor extends BlockActor { private sounded = false; constructor(level: Level, x: number, y: number) { super(level, x, y); } updateActor(): void { // プレイヤーが通過すべき場所を全て通過していたら非活性にする if ((this.level as NeverAgainLevel).isAllStepedOn()) { this.block.deactivate(); if (!this.sounded) { (this.level.scene.assets.open as g.AudioAsset).play(); this.sounded = true; } } } } <file_sep>import { Level } from '../src/bases/level'; // (global as any).g = require("@akashic/akashic-engine"); const g = require("@akashic/akashic-engine"); describe('Levelのテスト', () => { it('Level のインスタンスを生成する', () => { // // const gameSpy = jest.spyOn(g.Game, 'width', 'get').mockReturnValue(320); // g.game.width = 320; // expect(g.game.width).toEqual(320); }); });<file_sep>import { Actor } from "../bases/actor"; import { Level } from "../bases/level"; import { FloorComponent } from "../components/floor_component"; import { Vector2 } from "../utils/vector2"; export class FloorActor extends Actor { private floors: FloorComponent[] = []; constructor(tileX: number, tileY: number, level: Level) { super(level); for (let y = 0; y < tileY; y++) { for (let x = 0; x < tileX; x++) { const floor = new FloorComponent(this); floor.setPosition(x * level.tileWidth, y * level.tileHeight); this.addComponent(floor); this.floors.push(floor); } } } updateActor(): void { // 何もしない } /** * 踏んだ場所をコンポーネントに伝える * @param position 踏んだ場所 */ stepedOn(position: Vector2) { const floor = this.floors.filter(floor => (floor.x === position.x) && (floor.y === position.y)); floor[0].steped(); } }
a3848b4b4052b9261fadae181aeb31c77700ca0b
[ "Markdown", "TypeScript" ]
32
TypeScript
pickles-ochazuke/never-again
5f5740261892cd4dc4ca3a5544476c8880be8891
32743b90a050839ec1a8561adf3d09b03a911c7b
refs/heads/master
<repo_name>chebeto/MyPoorStopwatch<file_sep>/05-NavigationBar/ViewController.swift // // ViewController.swift // 05-NavigationBar // // Created by <NAME> on 6/21/16. // Copyright © 2016 elChebs. All rights reserved. // import UIKit class ViewController: UIViewController { var timer = NSTimer() var time = 0 @IBOutlet var timerLabel: UILabel! func result() { time += 1 timerLabel.text = String(time) } @IBAction func playTimer(sender: AnyObject) { timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ViewController.result), userInfo: nil, repeats: true) } @IBAction func pauseTimer(sender: AnyObject) { timer.invalidate() } @IBAction func resetTimer(sender: AnyObject) { timer.invalidate() time = 0 timerLabel.text = "0" } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
cc11227f3c39c0a13dfcfd4e851fc8e957293079
[ "Swift" ]
1
Swift
chebeto/MyPoorStopwatch
f4b987e8ab1bdc4c1b5c35ab4c2039200680e474
5cbba2ba7175f25db7efaca928c7d63c4f82e1a0
refs/heads/master
<file_sep>1. To get started on cli type: source env3.5/bin/activate #in this directory. <file_sep># Height map generator Python code to generate a basic height map <file_sep>from django.apps import AppConfig class FaultlinerConfig(AppConfig): name = 'faultLiner'
79f1686d60a6a9137a1567d0a6949272f0f0250d
[ "Markdown", "Python", "Text" ]
3
Text
craigpars0061/heightmapfaultline
be05688dbffa30cffbea01af2430caefeb6a0a27
ce07bc303ea60b2fe071e081fa4b32d37860a90d
refs/heads/master
<file_sep># FirstGameMovement Beginner Unity Game. <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class CharacterController : MonoBehaviour { [SerializeField] private bool isGrounded = false; [SerializeField] private float moveSpeed = 5; [SerializeField] private bool isRight; [SerializeField] private float jumpForce; private enum State { idle, run, jump, fall } private State state; private Vector3 movement; private bool isJumping; private Animator anim; private Rigidbody2D body2D; private void Awake() { body2D = GetComponent<Rigidbody2D>(); anim = GetComponent<Animator>(); } private void Start() { isRight = true; isJumping = false; } private void Update() { movement = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, 0f); isJumping = Input.GetButtonDown("Jump"); Jump(); } private void FixedUpdate() { Run(); anim.SetInteger("AnimState", (int)state); } // performs movement and animation state changes public bool getGrounded() { return isGrounded; } public void setGrounded(bool flag) { isGrounded = flag; } private void Flip(Vector3 movement) { // flips transforms.scale over y axis if (movement.x > 0) { isRight = true; transform.localScale = new Vector3(1, 1, transform.localScale.z); } if (movement.x < 0) { isRight = false; transform.localScale = new Vector3(-1, 1, transform.localScale.z); } } private void Run() { transform.position += movement * Time.deltaTime * moveSpeed; if (isGrounded && Mathf.Abs(movement.x) < .1f) state = State.idle; else if (isGrounded && Mathf.Abs(movement.x) >= .1f) state = State.run; Flip(movement); } private void Jump() { // y directional coefficient jumpForce = 8f; if (body2D.velocity.y < 0) state = State.fall; else if (body2D.velocity.y > 0) state = State.jump; // not really sure whats happening entirely // isGrounded is based on "Ground" tag on platforms layer // AddForce, ForceMode2D.Impulse() are mysteries atm if (isJumping && isGrounded == true) { gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse); state = State.jump; } } }
04f7130f67f64469ffeee2769cc00c602d3ebd87
[ "Markdown", "C#" ]
2
Markdown
alerubbio/FirstGameMovement
74ef691b446fd29662e33b9fbdb5ee213e669d9d
2a918af8ab899097af76ebff468e76811a617917
refs/heads/master
<file_sep>package network import ( "bufio" "errors" "fmt" "gopkg.in/yaml.v2" "io/ioutil" "net" "os" "path" "strings" "text/template" ) // Config represents a list of network type Config struct { Networks []Network `yaml:"networks"` } // Network represents a network information type Network struct { Name string `yaml:"name"` IPRange string `yaml:"iprange"` NetMask string `yaml:"netmask"` Routes []string `yaml:"routes"` } type clientConfig struct { IP string Netmask string Routes []string } var clientConfigTemplate = `ifconfig-push {{ .IP }} {{ .Netmask }} {{- range .Routes }} push "route {{ . }}" {{- end }} ` // GetNetworkByName searchs for a network name in network configuration func (c *Config) GetNetworkByName(name string) (*Network, error) { for i := 0; i < len(c.Networks); i++ { if c.Networks[i].Name == name { net := Network(c.Networks[i]) return &net, nil } } return nil, fmt.Errorf("network %v not found", name) } // ReadConfigFile reads a network configuration file func ReadConfigFile(path string) *Config { file, err := ioutil.ReadFile(path) config := Config{} if err != nil { fmt.Println(err) os.Exit(1) } err = yaml.Unmarshal(file, &config) if err != nil { fmt.Println(err) os.Exit(1) } return &config } // Increment IP func inc(ip net.IP) { for j := len(ip) - 1; j >= 0; j-- { ip[j]++ if ip[j] > 0 { break } } } // CheckErr print error essage func CheckErr(e error) { if e != nil { fmt.Println(e) } } func (n *Network) iprange() ([]string, error) { var ips []string ip, ipnet, err := net.ParseCIDR(n.IPRange) CheckErr(err) for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); inc(ip) { ips = append(ips, ip.String()) } // remove network address and broadcast address return ips[1 : len(ips)-1], nil } func isConfigFileExist(cn string) bool { if _, err := os.Stat(cn); err != nil { return false } return true } func readClientConfigFile(cn string) (ip, mask string) { var IP, netmask string file, err := os.Open(cn) CheckErr(err) defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { line := scanner.Text() if strings.Contains(line, "ifconfig-push") { line := strings.Split(line, " ") if len(line) == 3 { IP = line[1] netmask = line[2] break } } } return IP, netmask } func getAllUsedIP(ccd string) ([]string, error) { var ipUsed []string dir, err := os.Open(ccd) CheckErr(err) files, err := dir.Readdirnames(-1) for i := 0; i < len(files); i++ { file := path.Join(ccd, files[i]) if isConfigFileExist(file) { ip, _ := readClientConfigFile(file) ipUsed = append(ipUsed, ip) } } return ipUsed, err } func isClientConfigured(cn string, clientNetwork string) bool { if !isConfigFileExist(cn) { return false } file, err := os.Open(cn) defer file.Close() CheckErr(err) ip, _ := readClientConfigFile(cn) _, network, err := net.ParseCIDR(clientNetwork) if network.Contains(net.ParseIP(ip)) { return true } return false } // DeleteClientConfig remove a client network configuration func DeleteClientConfig(path string) error { err := os.Remove(path) if err != nil { fmt.Println(err) } return err } // convertRoutesFormat() convert 192.168.0.1/24 CIDR to 192.168.0.1 255.255.255.0 func (n *Network) convertRoutesFormat() []string { var result []string for i := 0; i < len(n.Routes); i++ { ip, network, err := net.ParseCIDR(n.Routes[i]) CheckErr(err) networkMask := net.IP(network.Mask).String() result = append(result, fmt.Sprintf("%v %v", ip.String(), networkMask)) } return result } // CreateClientConfig will generate a new client configuration under ccd func (n *Network) CreateClientConfig(cn string, ccd string) error { if isClientConfigured(path.Join(ccd, cn), n.IPRange) { fmt.Printf("%v is already in network: %v\n", cn, n.Name) return nil } freeIP, err := n.getFreeIP(ccd) CheckErr(err) config := clientConfig{ IP: freeIP, Netmask: net.ParseIP(n.NetMask).String(), Routes: n.convertRoutesFormat(), } tmpl, err := template.New(cn).Parse(clientConfigTemplate) CheckErr(err) file, err := os.Create(path.Join(ccd, cn)) CheckErr(err) defer file.Close() err = tmpl.Execute(file, config) CheckErr(err) return err } func (n *Network) getFreeIP(ccd string) (string, error) { _, network, err := net.ParseCIDR(n.IPRange) if err != nil { fmt.Println(err) } networkMask, _ := network.Mask.Size() networkIP := network.IP.String() networkCIDR := fmt.Sprintf("%v/%v", networkIP, networkMask) iprange, err := n.iprange() ipUsed, err := getAllUsedIP(ccd) for j := 0; j < len(ipUsed); j++ { // Restart from 0 as ipUsed is not sorted for i := 0; i < len(iprange); i++ { if network.Contains(net.ParseIP(ipUsed[j])) && (iprange[i] == ipUsed[j]) { fmt.Printf("Found used ip: %v\n", ipUsed[j]) iprange = append(iprange[:i], iprange[i+1:]...) break } } } if len(iprange) < 2 { msg := fmt.Sprintf("%v doesn't have free ip anymore", networkCIDR) err := errors.New(msg) fmt.Printf(msg) return "", err } return iprange[1], nil } <file_sep>package cmd import ( "github.com/jenkins-infra/openvpn/utils/easyvpn/checks" "github.com/spf13/cobra" "os" ) func init() { rootCmd.AddCommand(checkCmd) checkCmd.Flags().StringVarP(&CertDir, "cert", "c", "cert", "Cert Directory") } var checkCmd = &cobra.Command{ Use: "check", Short: "Checks various repository config", Args: cobra.ExactArgs(0), Run: func(cmd *cobra.Command, args []string) { rc := 0 if result, _ := checks.IsAllCertsSigned(CertDir); !result { rc = 1 } if result, _ := checks.IsAllClientConfigured(CertDir); !result { rc = 1 } os.Exit(rc) }, } <file_sep>#!/bin/bash set -e OPENVPN_CONF_DIR='/etc/openvpn/server' function configure_tun { [ -d /dev/net ] || mkdir -p /dev/net [ -c /dev/net/tun ] || mknod /dev/net/tun c 10 200 } function configure_certificates { # If custom CA are provided in /usr/local/share/ca-certificates/*.crt, # then this command ensures that these CAs are added to the default CA bundle update-ca-certificates if [ ! -f '/etc/openvpn/server/ca.crt' ]; then : "${OPENVPN_CA_PEM:? Missing OPENVPN_CA_PEM}" echo "$OPENVPN_CA_PEM" > /etc/openvpn/server/ca.crt fi if [ ! -f '/etc/openvpn/server/server.key' ]; then : "${OPENVPN_SERVER_KEY:? Missing OPENVPN_SERVER_KEY }" echo "$OPENVPN_SERVER_KEY" > /etc/openvpn/server/server.key fi if [ ! -f '/etc/openvpn/server/server.crt' ]; then : "${OPENVPN_SERVER_PEM:? Missing OPENVPN_SERVER_PEM }" echo "$OPENVPN_SERVER_PEM" > /etc/openvpn/server/server.crt fi if [ ! -f '/etc/openvpn/server/dh.pem' ]; then : "${OPENVPN_DH_PEM:? Missing OPENVPN_DH_PEM }" echo "$OPENVPN_DH_PEM" > /etc/openvpn/server/dh.pem fi } function ensure_required_variables { : "${AUTH_LDAP_PASSWORD:? AUTH_LDAP_PASSWORD required}" : "${AUTH_LDAP_URL:? AUTH_LDAP_URL required}" : "${AUTH_LDAP_BINDDN:? AUTH_LDAP_BINDDN required}" : "${AUTH_LDAP_GROUPS_MEMBER:? AUTH_LDAP_GROUPS_MEMBER required}" } # Use ~ in order to avoid wrong interpration with / in sed command. # Sed should be replaced by something more robust in the futur. function configure_openvpn { sed -i "s~AUTH_LDAP_PASSWORD~$AUTH_LDAP_PASSWORD~g" "$OPENVPN_CONF_DIR/auth-ldap.conf" sed -i "s~AUTH_LDAP_URL~$AUTH_LDAP_URL~g" "$OPENVPN_CONF_DIR/auth-ldap.conf" sed -i "s~AUTH_LDAP_BINDDN~$AUTH_LDAP_BINDDN~g" "$OPENVPN_CONF_DIR/auth-ldap.conf" sed -i "s~AUTH_LDAP_GROUPS_MEMBER~$AUTH_LDAP_GROUPS_MEMBER~g" "$OPENVPN_CONF_DIR/auth-ldap.conf" } function start_openvpn { openvpn --config "$OPENVPN_CONF_DIR/server.conf" } ensure_required_variables configure_tun configure_certificates configure_openvpn start_openvpn <file_sep>package main import ( "github.com/jenkins-infra/openvpn/utils/easyvpn/cmd" ) func main() { cmd.Execute() } <file_sep>FROM ubuntu:18.04 EXPOSE 443 LABEL \ maintainer="https://github.com/olblak"\ project="https://github.com/jenkins-infra/openvpn" RUN \ addgroup --gid 101 openvpn && \ useradd -d /var/lib/ldap/ -g openvpn -m -u 101 openvpn COPY --chown=openvpn cert/pki/ca.crt /etc/openvpn/server/ca.crt COPY --chown=openvpn cert/pki/crl.pem /etc/openvpn/server/crl.pem COPY --chown=openvpn cert/ccd /etc/openvpn/server/ccd COPY docker/config/server.conf /etc/openvpn/server/server.conf COPY docker/config/auth-ldap.conf /etc/openvpn/server/auth-ldap.conf COPY docker/entrypoint.sh /entrypoint.sh RUN \ apt-get update &&\ apt-get install -y openvpn openvpn-auth-ldap dnsmasq &&\ apt-get clean &&\ rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* &&\ mkdir /etc/ldap/ssl RUN chmod 0750 /entrypoint.sh ENTRYPOINT ["/entrypoint.sh" ] <file_sep>package cmd import ( "github.com/jenkins-infra/openvpn/utils/easyvpn/easyrsa" "github.com/jenkins-infra/openvpn/utils/easyvpn/git" "github.com/jenkins-infra/openvpn/utils/easyvpn/helpers" "github.com/jenkins-infra/openvpn/utils/easyvpn/network" "fmt" "github.com/spf13/cobra" "os" "path" ) func init() { rootCmd.AddCommand(revokeCmd) revokeCmd.Flags().BoolVarP(&Commit, "commit", "", true, "git commit changes") revokeCmd.Flags().BoolVarP(&Push, "push", "", true, "git push changes") revokeCmd.Flags().StringVarP(&CertDir, "cert", "c", "cert", "Cert Directory") } var revokeCmd = &cobra.Command{ Use: "revoke", Short: "Revoke a client certificate", Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { helpers.DecryptPrivateDir() errors := easyrsa.RevokeClientCert(args) if errors != nil { for _, err := range errors { if err != nil { fmt.Printf("%v\n", err) } } } for i := range args { network.DeleteClientConfig(path.Join(CertDir, "ccd", args[i])) } fileToDelete := []string{ path.Join(CertDir, "pki", "index.txt.old"), path.Join(CertDir, "pki", "index.txt.attr.old"), } for i := range fileToDelete { if err := os.Remove(fileToDelete[i]); err != nil { fmt.Println(err) } } if Commit { for i := 0; i < len(args); i++ { msg := "[infra-admin] Revoke " + args[i] + " certificate" files := []string{ path.Join(CertDir, "pki", "crl.pem"), path.Join(CertDir, "pki", "index.txt"), path.Join(CertDir, "pki", "issued", args[i]+".crt"), path.Join(CertDir, "pki", "reqs", args[i]+".req"), path.Join(CertDir, "pki", "certs_by_serial"), path.Join(CertDir, "pki", "index.txt.attr"), path.Join(CertDir, "pki", "revoked"), path.Join(CertDir, "ccd", args[i]), } git.Add(files) git.Commit(files, msg) } } if Push { git.Push() } helpers.CleanPrivateDir() }, } <file_sep>package cmd import ( "fmt" "github.com/spf13/cobra" "os" ) var rootCmd = &cobra.Command{ Use: "easyvpn", Short: "Easyvpn is a client tool to manage Jenkins Infrastructure VPN", } // CertDir define cert directory path var CertDir string // Commit define if changes must be committed or not var Commit bool // Push define if changes must be pushed or not var Push bool // Execute run the main command func Execute() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } } <file_sep>.PHONY: init_linux init_windows init_osx start publish.docker build.docker build.docker: $(MAKE) -C docker build publish.docker: $(MAKE) -C docker publish start: $(MAKE) -C docker up # Sleeping is good for your health buddy! sleep 5 $(MAKE) -C docker client-connect init_windows: $(MAKE) -C utils/easyvpn init_windows init_linux: $(MAKE) -C utils/easyvpn init_linux ln -f -s $(PWD)/utils/easyvpn/easyvpn easyvpn init_osx: $(MAKE) -C utils/easyvpn init_osx ln -f -s $(PWD)/utils/easyvpn/easyvpn easyvpn <file_sep>package checks import ( "github.com/jenkins-infra/openvpn/utils/easyvpn/easyrsa" "github.com/jenkins-infra/openvpn/utils/easyvpn/helpers" "errors" "fmt" "path" "sort" "strings" ) // IsAllCertsSigned validate that every requested certificate are signed func IsAllCertsSigned(certDir string) (bool, []error) { var errs []error result := true req := helpers.GetUsernameFile(path.Join(certDir, "pki/reqs"), ".req") crt := helpers.GetUsernameFile(path.Join(certDir, "pki/issued"), ".crt") sort.Slice(req, func(i, j int) bool { return req[i] < req[j] }) sort.Slice(crt, func(i, j int) bool { return crt[i] < crt[j] }) if len(req) != len(crt) { result = false msg := fmt.Sprintf("Numbers of requested and signed certificates mismatch:\n\t* %v Requested (%v)\n\t* %v Signed (%v)\n", len(req), req, len(crt), crt) err := errors.New(msg) fmt.Println(err) errs = append(errs, err) } for i := range req { var err error reqCN := strings.Split(req[i], ".req") crtCN := strings.Split(crt[i], ".crt") err = easyrsa.ShowClientCertificate(crtCN[0]) if err != nil { result = false fmt.Println(err) errs = append(errs, err) } err = easyrsa.ShowClientRequestCertificate(reqCN[0]) if err != nil { result = false fmt.Println(err) errs = append(errs, err) } if reqCN[0] != crtCN[0] { result = false msg := fmt.Sprintf("Requested and signed certificte mismatch:\n\t%v should match %v\n", req[i], crt[i]) err := errors.New(msg) fmt.Println(err) errs = append(errs, err) } } return result, errs } // IsAllClientConfigured validate that all signed certificate have client configuration func IsAllClientConfigured(certDir string) (bool, []error) { var errs []error result := true clientConfig := helpers.GetUsernameFile(path.Join(certDir, "ccd"), "") crt := helpers.GetUsernameFile(path.Join(certDir, "pki/issued"), ".crt") sort.Slice(clientConfig, func(i, j int) bool { return clientConfig[i] < clientConfig[j] }) sort.Slice(crt, func(i, j int) bool { return crt[i] < crt[j] }) if len(clientConfig) != len(crt) { result = false msg := fmt.Sprintf("Numbers of client configuration and signed certificates mismatch:\n\t* %v Requested (%v)\n\t* %v Signed (%v)\n", len(clientConfig), clientConfig, len(crt), crt) err := errors.New(msg) fmt.Println(err) errs = append(errs, err) } return result, errs } <file_sep>#!/bin/bash set -eux -o pipefail ## Generate certificates in current dir ## Generate LDAP Certificate + Key openssl req \ -newkey rsa:2048 \ -nodes \ -keyout ./ldap.key \ -out ./ldap.csr\ -subj "/C=BE/O=JENKINSPROJECT/CN=ldap" # Generate Certificate Authority Certificate + Key openssl req \ -newkey rsa:2048 \ -nodes \ -keyout ./ca.key \ -x509 \ -days 365 \ -out ./ca.crt\ -subj "/C=BE/O=JENKINSPROJECT/CN=ldap" ## Sign LDAP Certificate with Certificate Authority openssl x509 -req \ -in ./ldap.csr \ -CA ./ca.crt \ -CAkey ./ca.key \ -CAcreateserial \ -CAserial ./ca.srl \ -out ./ldap.crt <file_sep>.PHONY: build publish client-connect up IMAGE = 'jenkinsciinfra/openvpn' TAG = $(shell git rev-parse HEAD | cut -c1-6) build: docker build -f ../Dockerfile --no-cache -t $(IMAGE):$(TAG) -t $(IMAGE):latest .. publish: docker push $(IMAGE):$(TAG) docker push $(IMAGE):latest up: docker-compose build docker-compose up -d docker exec -i -t docker_ldap_1 /entrypoint/restore client-connect: docker-compose exec --workdir=/root/openvpn-client vpn openvpn --config config.ovpn --auth-user-pass auth <file_sep>.PHONY: build_osx build_windows build_linux init_osx init_linux init_windows build_osx: go get -d GO111MODULE=on CGO_ENABLED=0 GOOS=darwin go build -a -installsuffix cgo -v . build_windows: go get -d GO111MODULE=on CGO_ENABLED=0 GOOS=windows go build -v . build_linux: go get -d GO111MODULE=on CGO_ENABLED=0 GOOS=linux go build -installsuffix cgo -v . init_osx: docker run --rm -v "$(CURDIR)":/easyvpn -w /easyvpn -e GOOS=windows golang:1.13 make build_osx init_linux: docker run --rm -v "$(CURDIR)":/easyvpn -w /easyvpn -e GOOS=windows golang:1.13 make build_linux init_windows: docker run --rm -v "$(CURDIR)":/easyvpn -w /easyvpn -e GOOS=windows golang:1.13 make build_windows <file_sep>package cmd import ( "github.com/jenkins-infra/openvpn/utils/easyvpn/easyrsa" "github.com/jenkins-infra/openvpn/utils/easyvpn/git" "github.com/jenkins-infra/openvpn/utils/easyvpn/helpers" "github.com/jenkins-infra/openvpn/utils/easyvpn/network" "fmt" "github.com/spf13/cobra" "os" "path" ) var certDir string var commit bool var config string var push bool func init() { rootCmd.AddCommand(signCmd) signCmd.Flags().BoolVarP(&commit, "commit", "", true, "git commit changes") signCmd.Flags().BoolVarP(&push, "push", "", true, "git push changes") signCmd.Flags().StringVarP(&certDir, "certsDir", "", "cert", "Cert Directory") signCmd.Flags().StringVarP(&ccd, "ccd", "", "cert/ccd", "Client Config Directory") signCmd.Flags().StringVarP(&config, "config", "", "config.yaml", "Network Configuration File") signCmd.Flags().StringVarP(&net, "net", "", "default", "Network to assign the cn") } var signCmd = &cobra.Command{ Use: "sign", Short: "Sign a request certificate", Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { // Sign requested certificate(s) helpers.DecryptPrivateDir() errors := easyrsa.SignClientRequest(args) if errors != nil { for _, err := range errors { if err != nil { fmt.Printf("%v\n", err) } } } // Generate client config config := network.ReadConfigFile(config) network, err := config.GetNetworkByName(net) if err != nil { fmt.Println(err) os.Exit(1) } for i := 0; i < len(args); i++ { network.CreateClientConfig(args[i], ccd) // Commit changes if commit { msg := "[infra-admin] Sign certificate request for " + args[i] files := []string{ path.Join(CertDir, "pki/issued", args[i]+".crt"), path.Join(CertDir, "pki", "index.txt"), path.Join(CertDir, "pki", "index.txt.attr"), path.Join(CertDir, "pki", "certs_by_serial"), path.Join(CertDir, "pki", "serial"), path.Join(CertDir, "ccd", args[i]), } git.Add(files) git.Commit(files, msg) } } // Push changes if push { git.Push() } helpers.CleanPrivateDir() }, } <file_sep>package helpers import ( "fmt" "go.mozilla.org/sops/v3/decrypt" "log" "os" ) // DecryptPrivateDir decrypt ca private key and ca private key password func DecryptPrivateDir() { dirname := "cert/pki/private/" files := []string{"ca.key"} for _, file := range files { out, err := decrypt.File(dirname+file+".enc", "txt") if err != nil { log.Fatal(err) } file, err := os.Create(dirname + file) if err != nil { log.Fatal(err) } defer file.Close() fmt.Fprintf(file, string(out)) } } // CleanPrivateDir delete decrypte ca private key and the file containing his password func CleanPrivateDir() { dirname := "cert/pki/private/" files := []string{"ca.key"} for _, file := range files { err := os.Remove(dirname + file) if err != nil { fmt.Println(err) } } } // GetUsernameFile returns a list of all CN file configuration for a specific extension: .req or .crt func GetUsernameFile(path, extension string) []string { dir, err := os.Open(path) if err != nil { fmt.Println(err) return []string{} } files, err := dir.Readdirnames(-1) if err != nil { log.Fatal(err) } return files } <file_sep>module github.com/jenkins-infra/openvpn/utils/easyvpn go 1.13 require ( cloud.google.com/go v0.49.0 // indirect cloud.google.com/go/storage v1.4.0 // indirect github.com/Azure/azure-sdk-for-go v36.2.0+incompatible // indirect github.com/Azure/go-autorest/autorest/adal v0.8.0 // indirect github.com/Azure/go-autorest/autorest/azure/auth v0.4.0 // indirect github.com/aws/aws-sdk-go v1.25.46 // indirect github.com/golang/groupcache v0.0.0-20191027212112-611e8accdfc9 // indirect github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect github.com/hashicorp/go-retryablehttp v0.6.4 // indirect github.com/hashicorp/golang-lru v0.5.3 // indirect github.com/howeyc/gopass v0.0.0-20190910152052-7cb4b85ec19c // indirect github.com/jstemmer/go-junit-report v0.9.1 // indirect github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect github.com/mattn/go-colorable v0.1.4 // indirect github.com/mattn/go-isatty v0.0.10 // indirect github.com/pierrec/lz4 v2.3.0+incompatible // indirect github.com/spf13/cobra v0.0.5 go.mozilla.org/sops/v3 v3.5.0 go.opencensus.io v0.22.2 // indirect golang.org/x/crypto v0.0.0-20191202143827-86a70503ff7e // indirect golang.org/x/exp v0.0.0-20191129062945-2f5052295587 // indirect golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f // indirect golang.org/x/net v0.0.0-20191126235420-ef20fe5d7933 // indirect golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6 // indirect golang.org/x/sys v0.0.0-20191128015809-6d18c012aee9 // indirect golang.org/x/time v0.0.0-20191024005414-555d28b269f0 // indirect golang.org/x/tools v0.0.0-20191203134012-c197fd4bf371 // indirect google.golang.org/appengine v1.6.5 // indirect google.golang.org/genproto v0.0.0-20191203145615-049a07e0debe // indirect google.golang.org/grpc v1.25.1 // indirect gopkg.in/ini.v1 v1.51.0 // indirect gopkg.in/square/go-jose.v2 v2.4.0 // indirect gopkg.in/yaml.v2 v2.2.2 ) <file_sep>version: '2' volumes: ldap_data: services: vpn: build: .. # image: jenkinsciinfra/openvpn@sha256:da7df2af12676863b3aa4b52e48650a8ba11692a0cbf582f86c7425945160496 cap_add: - NET_ADMIN depends_on: - ldap environment: - "AUTH_LDAP_PASSWORD=<PASSWORD>" - "AUTH_LDAP_URL=ldaps://ldap" - "AUTH_LDAP_BINDDN=cn=admin,dc=jenkins-ci,dc=org" - "AUTH_LDAP_GROUPS_MEMBER=cn=all" volumes: - ./mock/vpn/ccd:/etc/openvpn/server/ccd:ro - ./mock/vpn/ca.crt:/etc/openvpn/server/ca.crt:ro - ./mock/ldap/ca.crt:/usr/local/share/ca-certificates/ldapca.crt:ro - ./mock/vpn/vpn.crt:/etc/openvpn/server/server.crt:ro - ./mock/vpn/dh.pem:/etc/openvpn/server/dh.pem:ro - ./mock/vpn/vpn.key:/etc/openvpn/server/server.key:ro - ./mock/vpn/ca.crt:/usr/local/share/ca-certificates/ca.crt:ro - ./mock/clients:/root/openvpn-client:ro ports: - 443:443 # Don't forget to run /entrypoint/restore, once database is started ldap: image: jenkinsciinfra/ldap@sha256:bee8e769077e82984ada23d25b06c7f42130a4b9f9fa92ead20916e01c1af8de environment: - "OPENLDAP_DEBUG_LEVEL=1" volumes: - ldap_data:/var/lib/ldap - ./mock/ldap/ca.crt:/usr/local/share/ca-certificates/ca.crt:ro - ./mock/ldap/ca.crt:/etc/ldap/ssl-ca/ca.crt:ro # Override the Let's Encrypt CA embeded in the image - ./mock/ldap/ldap.crt:/etc/ldap/ssl/cert.pem:ro - ./mock/ldap/ldap.key:/etc/ldap/ssl/privkey.key:ro - ./mock/mock.ldif:/var/backups/backup.latest.ldif:ro <file_sep>package easyrsa import ( "bytes" "fmt" "os" "os/exec" "path" "strings" ) var ( easyrsaDir = "cert" ) func easyrsa(args ...string) error { cmd := exec.Command("./easyrsa", args...) cmd.Dir = easyrsaDir var outb, errb bytes.Buffer cmd.Stdout = &outb //cmd.Stderr = &errb err := cmd.Run() fmt.Printf("Exec: %v/easyrsa %v\n", cmd.Dir, strings.Join(cmd.Args[1:], " ")) fmt.Printf("%v", outb.String()) fmt.Printf("---\n") //fmt.Printf("%v\n", errb.String()) if err != nil { fmt.Println(errb.String()) } return err } // GenerateRevocationListCert generate a certificate revocation List func GenerateRevocationListCert() error { err := easyrsa("revoke") return err } // RequestClientCert generate a client private key and an associated certificate request func RequestClientCert(CNs []string) []error { var err []error for _, CN := range CNs { err = append(err, easyrsa("--batch", "--req-cn="+CN, "gen-req", CN, "nopass")) } return err } // RevokeClientCert revoke a client certificate func RevokeClientCert(CNs []string) []error { var errors []error for _, CN := range CNs { errors = append(errors, easyrsa("--batch", "revoke", CN)) } errors = append(errors, easyrsa("gen-crl")) return errors } // SignClientRequest sign client certificate requests func SignClientRequest(CNs []string) []error { var errors []error for _, CN := range CNs { errors = append(errors, easyrsa("--batch", "sign-req", "client", CN)) } // Delete useless files generated from easyrsa files := []string{ "index.txt.attr.old", "index.txt.old", "serial.old", "extensions.temp"} for _, file := range files { fmt.Printf("Deleting unneeded file: %v\n", file) err := os.Remove(path.Join(easyrsaDir, "pki", file)) if err != nil { fmt.Println(err) } } return errors } // ShowClientCertificate display client certificate information func ShowClientCertificate(CN string) error { err := easyrsa("show-cert", CN) return err } // ShowClientRequestCertificate display client certificate request information func ShowClientRequestCertificate(CN string) error { err := easyrsa("show-req", CN) return err } <file_sep>package cmd import ( "github.com/jenkins-infra/openvpn/utils/easyvpn/git" "github.com/jenkins-infra/openvpn/utils/easyvpn/network" "fmt" "github.com/spf13/cobra" "os" "path" ) var delete bool var ccd string var configuration string var net string func init() { rootCmd.AddCommand(configCmd) configCmd.Flags().StringVarP(&ccd, "ccd", "", "cert/ccd", "Client Config Directory") configCmd.Flags().StringVarP(&configuration, "config", "c", "config.yaml", "Network Configuration File") configCmd.Flags().StringVarP(&net, "net", "", "default", "Network assigned") configCmd.Flags().BoolVarP(&commit, "commit", "", true, "Commit changes") configCmd.Flags().BoolVarP(&commit, "push", "", true, "Push changes") configCmd.Flags().BoolVarP(&delete, "delete", "d", false, "Delete Network Configuration File") } var configCmd = &cobra.Command{ Use: "config", Short: "Configure client network ip", Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { if delete == true { for j := 0; j < len(args); j++ { network.DeleteClientConfig(path.Join(ccd, args[j])) if commit { msg := fmt.Sprintf("[infra-admin] Delete %v network configuration", args[j]) files := []string{ path.Join(ccd, args[j]), } git.Add(files) git.Commit(files, msg) } } } else { config := network.ReadConfigFile(config) network, err := config.GetNetworkByName(net) if err != nil { fmt.Println(err) os.Exit(1) } for j := 0; j < len(args); j++ { network.CreateClientConfig(args[j], ccd) if commit { msg := fmt.Sprintf("[infra-admin] Update %v network configuration", args[j]) files := []string{ path.Join(ccd, args[j]), } git.Add(files) git.Commit(files, msg) } } } if push { git.Push() } }, } <file_sep>package git import ( "bytes" "fmt" "os/exec" "strings" ) var debug = false func git(args ...string) (string, error) { cmd := exec.Command("git", args...) var outb, errb bytes.Buffer cmd.Stdout = &outb cmd.Stderr = &errb err := cmd.Run() fmt.Printf("Exec: %v\n", strings.Join(cmd.Args, " ")) fmt.Printf("%v", outb.String()) fmt.Printf("---\n") if err != nil { fmt.Println(errb.String()) } return outb.String(), err } // Commit create a new commit func Commit(files []string, msg string) { args := []string{"commit"} for _, file := range files { args = append(args, file) } args = append(args, "-m") args = append(args, msg) git(args...) } // Add create a new commit func Add(files []string) { args := []string{"add"} for _, file := range files { args = append(args, file) } git(args...) } // Pull fetch from origin func Pull() { args := []string{"pull"} git(args...) } // getRepoOwner returns local branch func getLocalBranch() string { args := []string{"rev-parse", "--abbrev-ref", "HEAD"} branch, _ := git(args...) fmt.Printf("Current git branch: %v\n", branch) return branch } // getRepoOwner returns current github owner func getRepoOwner() (string, error) { var owner string args := []string{"config", "remote.origin.url"} url, _ := git(args...) if strings.HasPrefix(url, "<EMAIL>:") { url := strings.Split(url, ":") owner = strings.Split(url[1], "/")[0] } else if strings.HasPrefix(url, "https://github.com/") { owner = strings.Split(url, "/")[3] } else { err := fmt.Errorf("Couldn't find current repository owner in %v", url) return "", err } fmt.Printf("Current repository owner: %v\n", owner) return owner, nil } // Push the branch on remote master branch func Push() { branch := getLocalBranch() owner, err := getRepoOwner() args := []string{"push"} git(args...) if err == nil { fmt.Printf("You can now open your Pull Request via \n\t https://github.com/jenkins-infra/openvpn/compare/staging...%v:%v\n", owner, branch) } } // Rebase from origin func Rebase() { args := []string{"rebase", "origin/master"} git(args...) }
795658ea20dab6f64a2cf9cc97bc610d6cbb00b5
[ "YAML", "Makefile", "Go", "Go Module", "Dockerfile", "Shell" ]
19
Go
garethjevans/openvpn
47ee4c34da6f845a0e78691f966dba5b3581f23a
479c4e14ac919bb32d1f8b2f15c5721f417fb781
refs/heads/master
<repo_name>ashishdedania/tictac<file_sep>/app/Models/Games/Traits/Attribute/GameAttribute.php <?php namespace App\Models\Games\Traits\Attribute; /** * Class GameAttribute. */ trait GameAttribute { } <file_sep>/README.md # Getting started ## Introduction Laravel API Boilerplate is a "starter kit" you can use to build your first API in seconds. As you can easily imagine, it is built on top of the awesome Laravel Framework. ## Installation Switch to the repo folder cd laravel-api-boilerplate-jwt Install all the dependencies using composer composer install Copy the example env file and make the required configuration changes in the .env file cp .env.example .env Generate a new application key php artisan key:generate Generate a new JWT authentication secret key php artisan jwt:generate Run the database migrations (**Set the database connection in .env before migrating**) php artisan migrate Start the local development server php artisan serve You can now access the server at http://localhost:8000 **TL;DR command list** git clone cd laravel-api-boilerplate-jwt composer install cp .env.example .env php artisan key:generate php artisan jwt:generate **Make sure you set the correct database connection information before running the migrations** [Environment variables](#environment-variables) php artisan migrate php artisan serve ## Environment variables - `.env` - Environment variables can be set in this file ***Note*** : You can quickly set the database information and other variables in this file and have the application fully working. # Authentication This applications uses JSON Web Token (JWT) to handle authentication. The token is passed with each request using the `Authorization` header with `Token` scheme. The JWT authentication middleware handles the validation and authentication of the token. Please check the following sources to learn more about JWT. - https://jwt.io/introduction/ - https://self-issued.info/docs/draft-ietf-oauth-json-web-token.html # <file_sep>/app/Http/Controllers/Api/V1/GamesController.php <?php namespace App\Http\Controllers\Api\V1; use App\Http\Resources\GamesResource; use App\Models\Games\Game; use App\Repositories\Backend\Games\GamesRepository; use Illuminate\Http\Request; use Validator; class GamesController extends APIController { protected $repository; /** * __construct. * * @param $repository */ public function __construct(GamesRepository $repository) { $this->repository = $repository; } /** * Do game move. * * @param Request $request * * @return \Illuminate\Http\JsonResponse */ public function doMove(Request $request) { $validation = $this->validateBlog($request); if ($validation->fails()) { return $this->throwValidation($validation->messages()->first()); } $result = $this->repository->makeMove($request->all()); return new GamesResource($result); } } <file_sep>/app/Models/Games/Game.php <?php namespace App\Models\Games; use App\Models\BaseModel; use App\Models\Blogs\Traits\Attribute\GameAttribute; use App\Models\Blogs\Traits\Relationship\GameRelationship; use App\Models\ModelTrait; use Illuminate\Database\Eloquent\SoftDeletes; class Game extends BaseModel { use ModelTrait, SoftDeletes, GameAttribute, GameRelationship { } protected $fillable = [ 'game_id', 'user_id', 'x_position', 'y_position', ]; protected $dates = [ 'created_at', 'updated_at', ]; /** * The database table used by the model. * * @var string */ protected $table; public function __construct(array $attributes = []) { parent::__construct($attributes); $this->table = config('module.games.table'); } } <file_sep>/app/Repositories/Backend/Games/GamesRepository.php <?php namespace App\Repositories\Backend\Games; use App\Exceptions\GeneralException; use App\Models\Games\Game; use App\Repositories\BaseRepository; use Carbon\Carbon; use DB; use Illuminate\Support\Facades\Storage; /** * Class GamesRepository. */ class GamesRepository extends BaseRepository { /** * Associated Repository Model. */ const MODEL = Game::class; public function __construct() { } /** * @param array $input * * @throws \App\Exceptions\GeneralException * * @return array */ public function makeMove(array $input) { $gameId = $input['game_id']; $userId = $input['user_id']; $xPosition = $input['pos_x']; $yPosition = $input['pos_y']; $totalMoves = Game::where('id',$gameId)->count(); if($totalMoves >= 9) { throw new GeneralException('Game is finished'); } DB::transaction(function () use ($input) { $move = Game::create($input); $user = User::where('id',$input['user_id'])->first(); //check is winner $winResult = $this->calculateWin($input['game_id'], $input['user_id']); if($winResult) { return [ 'id' => $input['game_id'], 'username' => $user->first_name.' '.$user->last_name, 'status' => 'You Win' ]; } //check is game over $totalMoves = Game::where('id',$gameId)->count(); if($totalMoves >= 9) { return [ 'id' => $input['game_id'], 'username' => $user->first_name.' '.$user->last_name, 'status' => 'Game Draw' ]; } //default return return [ 'id' => $input['game_id'], 'username' => $user->first_name.' '.$user->last_name, 'status' => 'Your step recorded' ]; throw new GeneralException('Some error occure please try again'); }); } /** * @param $gameId, $userId * * @throws \App\Exceptions\GeneralException * * @return bool */ public function calculateWin($gameId, $userId) { // check horizontal $horizontalOne = Game::where('game_id',$gameId)->where('user_id',$userId)->where('x_position',1)->count(); $horizontalTwo = Game::where('game_id',$gameId)->where('user_id',$userId)->where('x_position',2)->count(); $horizontalThree = Game::where('game_id',$gameId)->where('user_id',$userId)->where('x_position',3)->count(); // check vertical $verticalOne = Game::where('game_id',$gameId)->where('user_id',$userId)->where('y_position',1)->count(); $verticalTwo = Game::where('game_id',$gameId)->where('user_id',$userId)->where('y_position',2)->count(); $verticalThree = Game::where('game_id',$gameId)->where('user_id',$userId)->where('y_position',3)->count(); // check diagonal $position_1_1 = Game::where('game_id',$gameId)->where('user_id',$userId)->where('x_position',1)->where('y_position',1)->count(); $position_2_2 = Game::where('game_id',$gameId)->where('user_id',$userId)->where('x_position',2)->where('y_position',2)->count(); $position_3_3 = Game::where('game_id',$gameId)->where('user_id',$userId)->where('x_position',3)->where('y_position',3)->count(); $position_1_3 = Game::where('game_id',$gameId)->where('user_id',$userId)->where('x_position',1)->where('y_position',3)->count(); $position_3_1 = Game::where('game_id',$gameId)->where('user_id',$userId)->where('x_position',3)->where('y_position',1)->count(); $diagon1 = $position_1_1 + $position_2_2 + $position_3_3; $diagon2 = $position_1_3 + $position_2_2 + $position_3_1; if($horizontalOne == 3 || $horizontalTw0 == 3 || $horizontalThree==3 || $verticalOne==3 || $verticalTwo==3 || $verticalThree==3 || $diagon1==3 || $diagon2==3) { return true; } else { return false; } } } <file_sep>/app/Models/Games/Traits/Relationship/GameRelationship.php <?php namespace App\Models\Games\Traits\Relationship; use App\Models\Access\User\User; /** * Class GameRelationship. */ trait GameRelationship { /** * Games belongsTo with User. */ public function player() { return $this->belongsTo(User::class, 'created_by'); } }
ec71ec29b24d6cf0db4584841db41f78140388be
[ "Markdown", "PHP" ]
6
PHP
ashishdedania/tictac
9fc61741037d4d820e1bc6f898958f6407e0f535
6bc046a5fd1d390202f2e39054fe8491186f7a71
refs/heads/master
<file_sep>const {factory:RouteIns }= require("../dist/route.js") async function add_attr(ctx,next){ ctx.number = 1 await next(); } async function add_one(ctx,next){ ctx.number++ await next(); } async function add_some(ctx,num,next){ ctx.number += num await next(); } async function print_attr(ctx,next){ console.log(ctx) } var middles = [ 'add_attr','add_one', { name:'add_some', argument:100, }, 'print_attr' ] console.log(RouteIns) RouteIns.container.register([add_attr,print_attr,add_one,add_some]) var route_1 = RouteIns.create('/not_match',middles) var route_2 = RouteIns.create('/',middles) var ctx = { method:'POST', url:'/' } async function main(){ console.log('===========start===========') await route_1.routes(ctx,function(){ console.log('===========no match===========') }) await route_2.routes(ctx,function(){}) } main(); <file_sep>interface anyObj { [propName:string]:any } interface CTX { [propName:string]:any } interface CONFIG{ [propName:string]:any } interface Middleware_Function_2_Parameter { (ctx:CTX,next:Function):void; } interface Middleware_Function_3_Parameter { (ctx:CTX,config:CONFIG,next:Function):void; } type Middleware_Function = Middleware_Function_3_Parameter | Middleware_Function_2_Parameter interface containerType { readonly separator:string; register(list: Middleware_Function[] | Middleware_Function ,namespace:string | undefined):void; get(name:string, namespace:string | undefined):Function; } interface Middleware_describe { name:string; namespace?:string; argument?:anyObj; } <file_sep>import container from './container' import pathToRegexp from 'path-to-regexp' import Debug from 'debug' const debug = Debug('koa-route-ex') class route { Middles:(string | Middleware_describe)[] container:containerType url_regx:RegExp Method:string = 'POST' //default constructor(url_regx:string,middles:[],container:containerType) { this.url_regx = pathToRegexp(url_regx) this.Middles = middles; this.container = container; } /** 设定 方法 use GET POST */ setMethod(method:string) { this.Method = method } /** 加入 Middles ,容器*/ add(middles: string | string[] | Middleware_describe | Middleware_describe[]) { if(Array.isArray(middles)){ this.Middles = this.Middles.concat(middles) } else{ this.Middles.push(middles) } } getMiddle(i:number):Function | undefined{ if( i >= this.Middles.length) return undefined let describe = this.Middles[i]; let name:string let name_space:string |undefined = undefined let argument : anyObj | undefined = undefined if( typeof describe === 'string'){ let split_name = describe.split(this.container.separator) if( split_name.length > 2) throw new Error(`to many split character ${this.container.separator} !`) if( split_name.length == 2){ name = split_name[1] name_space = split_name[0] } else { name = split_name[0] } } else { name = describe.name name_space = describe.namespace argument = describe.argument } let fn = this.container.get(name, name_space) if( !argument){ return fn } else return async function(ctx:CTX,next:Function){ return fn(ctx,argument,next) } } match(ctx:any):boolean{ let matchMethod = false let matchUrl = false if( ctx.Method === undefined) matchMethod = true; else if(ctx.Method === this.Method) matchMethod = true; if( ctx.url === undefined) matchUrl = true else if ( this.url_regx.exec(ctx.url)) matchUrl = true return matchUrl && matchMethod } async routes(ctx:any,next:Function){ /** 1 if match */ if(this.match(ctx)){ debug('match') let com = this.compose() await com(ctx,next) } else return next() } /** 运行 */ compose(){ let self = this return function(context:CTX,next:Function){ let index = -1; return dispatch(0) function dispatch(i:number):any { if( i <= index) return Promise.reject(new Error('next() called multiple times')) index = i; let fn = self.getMiddle(i) if( i === self.Middles.length ) fn = next if( !fn ) return Promise.resolve() try { return Promise.resolve(fn(context,dispatch.bind(null,i+1))) }catch(err){ return Promise.reject(err) } } } } } class routeFactory { container:containerType; constructor(){ this.container = new container(); } create(url_regx:string,middles:[]){ return new route(url_regx,middles,this.container) } } //export default route export var factory = new routeFactory()
acb40d2d995adf985001fd2a32bcd942a2e7b153
[ "JavaScript", "TypeScript" ]
3
JavaScript
slimeoj/koa-route-ex
a2027cc449dab240266195ecab59b42e0a1b12ca
fe93d947890e1777bcb352b209a4903c52761bfb
refs/heads/master
<file_sep>#ifndef EM_PORT_API # if defined(__EMSCRIPTEN__) # include <emscripten.h> # if defined(__cplusplus) # define EM_PORT_API(rettype) extern "C" rettype EMSCRIPTEN_KEEPALIVE # else # define EM_PORT_API(rettype) rettype EMSCRIPTEN_KEEPALIVE # endif # else # if defined(__cplusplus) # define EM_PORT_API(rettype) extern "C" rettype # else # define EM_PORT_API(rettype) rettype # endif # endif #endif #include <stdint.h> #include <malloc.h> #include <time.h> #include <stdlib.h> bool *cells0 = NULL, *cells1 = NULL; uint32_t *img_buf = NULL; int width = 0, height = 0; bool pausing = false; int scale = 2; void create_seeds() { if (cells0 == NULL) return; srand(clock()); for (int i = 0; i < width * height; i++){ cells0[i] = (rand() % 2) != 1; } } EM_PORT_API(void) reset() { create_seeds(); } EM_PORT_API(void) pause() { pausing=!pausing; } EM_PORT_API(void) init_env(int w, int h, int s) { if (cells0) free(cells0); if (cells1) free(cells1); if (img_buf) free(img_buf); width = w; height = h; scale = s; cells0 = (bool*)malloc(w * h); cells1 = (bool*)malloc(w * h); img_buf = (uint32_t*)malloc(w * h * scale * scale * 4); create_seeds(); } struct DIR{ int x, y; }; void evolve(){ static DIR dirs[] = {{-1, -1}, {0, -1}, {1, -1}, {-1, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1}}; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int live_count = 0; for (int i = 0; i < 8; i++) { int nx = (x + dirs[i].x + width) % width; int ny = (y + dirs[i].y + height) % height; if (cells0[ny * width + nx]) { live_count++; } } if (cells0[y * width + x]) { switch (live_count) { case 2: case 3: cells1[y * width + x] = true; break; default: cells1[y * width + x] = false; break; } } else { switch (live_count) { case 3: cells1[y * width + x] = true; break; default: cells1[y * width + x] = false; break; } } } } bool *temp = cells0; cells0 = cells1; cells1 = temp; } EM_PORT_API(uint8_t*) step() { if (img_buf == NULL) return NULL; if (!pausing) { evolve(); } for (int x = 0; x < width; x++){ for (int y = 0; y < height; y++){ uint32_t color = cells0[y * width + x] ? 0xFF0000FF : 0xFFFFFFFF; for (int i = 0; i < scale; i++){ for (int j = 0; j < scale; j++){ int d = ((y * scale + j) * width * scale + x * scale + i); img_buf[d] = color; } } } } return (uint8_t*)img_buf; } EM_PORT_API(void) on_mouse_click(int x, int y){ if (!pausing) return; x /= scale; y /= scale; if (x < 0 || x >= width || y < 0 || y >= height) return; cells0[y * width + x] = !cells0[y * width + x]; } EM_PORT_API(void) on_key_up(const char* key) { if (!key) return; switch(*key) { case 'p': pausing = !pausing; break; case 'r': create_seeds(); break; } }<file_sep>Welcome to my default Web Page of GitHub Pages. The [main website](Home_Page/home.html) is under construction. Check out some of the things I created while learning Emscripten. They are listed below. 1. [Conway's Game of Life](Conway's_Game/game.html) 2. Magic Calculator 3. Virtual Drum Set 4. [Tetris](Tetris/public/index.html)
e2f69a7ce46be0d48bd552e2320f562bd261ab61
[ "Markdown", "C++" ]
2
C++
mohit2399/old-website-mine
a597fe25d02163a8af088bcbfe0cb77f71e5e4d7
6c6a860be53161554b88c073a554c4eff55ca6c9
refs/heads/master
<repo_name>simon3z/openstack-java-sdk<file_sep>/quantum-model/src/main/java/com/woorea/openstack/quantum/model/RouterForCreate.java package com.woorea.openstack.quantum.model; import java.util.List; import org.codehaus.jackson.annotate.JsonProperty; import org.codehaus.jackson.map.annotate.JsonRootName; @JsonRootName("router") public class RouterForCreate { @JsonProperty("name") String name; private List<String> routers; @JsonProperty("admin_state_up") String admin_state_up; @JsonProperty("status") String status; @JsonProperty("external_gateway_info") String externalGatewayInfo; @JsonProperty("tenant_id") String tenantId; @JsonProperty("id") String id; public String getName() { return name; } public void setName(String name) { this.name = name; } public List<String> getRouters() { return routers; } public void setRouters(List<String> routers) { this.routers = routers; } public String getAdmin_state_up() { return admin_state_up; } public void setAdmin_state_up(String admin_state_up) { this.admin_state_up = admin_state_up; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getExternalGatewayInfo() { return externalGatewayInfo; } public void setExternalGatewayInfo(String externalGatewayInfo) { this.externalGatewayInfo = externalGatewayInfo; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getId() { return id; } public void setId(String id) { this.id = id; } } <file_sep>/nova-client/src/main/java/com/woorea/openstack/nova/api/extensions/AggregatesExtension.java package com.woorea.openstack.nova.api.extensions; import java.util.Map; import com.woorea.openstack.base.client.HttpMethod; import com.woorea.openstack.base.client.OpenStackClient; import com.woorea.openstack.base.client.OpenStackRequest; import com.woorea.openstack.nova.model.HostAggregate; import com.woorea.openstack.nova.model.HostAggregates; public class AggregatesExtension { private final OpenStackClient CLIENT; public AggregatesExtension(OpenStackClient client) { CLIENT = client; } public List list() { return new List(); } public ShowAggregate showAggregate(String id) { return new ShowAggregate(id); } public UpdateAggregateMetadata updateAggregateMetadata(String id, Map<String, String> metadata) { return new UpdateAggregateMetadata(id, metadata); } public DeleteAggregate deleteAggregate(String id) { return new DeleteAggregate(id); } public AddHost addHost(String aggregateId, String hostId) { return new AddHost(aggregateId, hostId); } public RemoveHost removeHost(String aggregateId, String hostId) { return new RemoveHost(hostId, aggregateId); } public class List extends OpenStackRequest<HostAggregates> { public List() { super(CLIENT, HttpMethod.GET, "/os-aggregates", null, HostAggregates.class); } } public class ShowAggregate extends OpenStackRequest<HostAggregate> { public ShowAggregate(String id) { method(HttpMethod.GET); path("/os-aggregates/").path(id); header("Accept", "application/json"); returnType(HostAggregate.class); } } public class UpdateAggregateMetadata extends OpenStackRequest<HostAggregate> { private String id; private Map<String, String> metadata; public UpdateAggregateMetadata(String id, Map<String, String> metadata) { this.id = id; this.metadata = metadata; method(HttpMethod.POST); path("/os-aggregates/").path(id); header("Accept", "application/json"); json("{\"set_metadata\" : }"); returnType(HostAggregate.class); } } public class DeleteAggregate extends OpenStackRequest<Void> { public DeleteAggregate(String id) { method(HttpMethod.DELETE); path("/os-aggregates/").path(id); header("Accept", "application/json"); } } public static class AddHost extends OpenStackRequest<Void> { private String aggregateId; private String hostId; public AddHost(String aggregateId, String hostId) { this.aggregateId = aggregateId; this.hostId = hostId; // target.path("os-aggregates").request(MediaType.APPLICATION_JSON).post(Entity.json("{\"add_host\" : }")); } } public class RemoveHost extends OpenStackRequest<Void> { private String aggregateId; private String hostId; public RemoveHost(String hostId, String aggregateId) { this.aggregateId = aggregateId; this.hostId = hostId; // target.path("os-aggregates").path("aggregate").path("os-volume-attachments").request(MediaType.APPLICATION_JSON).post(Entity.json("{\"remove_host\" : }")); } } } <file_sep>/keystone-client/src/main/java/com/woorea/openstack/keystone/api/Authenticate.java package com.woorea.openstack.keystone.api; import com.woorea.openstack.base.client.HttpMethod; import com.woorea.openstack.base.client.OpenStackRequest; import com.woorea.openstack.keystone.model.Access; import com.woorea.openstack.keystone.model.Authentication; import com.woorea.openstack.keystone.model.authentication.AccessKey; import com.woorea.openstack.keystone.model.authentication.TokenAuthentication; import com.woorea.openstack.keystone.model.authentication.UsernamePassword; public class Authenticate extends OpenStackRequest<Access> { private Authentication authentication; public Authenticate(Authentication authentication) { method(HttpMethod.POST); path("/tokens"); json(authentication); header("Accept", "application/json"); returnType(Access.class); } public Authenticate withTenantId(String tenantId) { authentication.setTenantId(tenantId); return this; } public Authenticate withTenantName(String tenantName) { authentication.setTenantName(tenantName); return this; } public class Builder { public Authenticate withUsernamePassword(String username, String password) { authentication = new UsernamePassword(username, password); return Authenticate.this; } public Authenticate withToken(String token) { authentication = new TokenAuthentication(token); return Authenticate.this; } public Authenticate withAccessKey(String accessKey, String secretKey) { authentication = new AccessKey(accessKey, secretKey); return Authenticate.this; } } } <file_sep>/quantum-client/src/main/java/com/woorea/openstack/quantum/api/PortsResource.java package com.woorea.openstack.quantum.api; import com.woorea.openstack.base.client.Entity; import com.woorea.openstack.base.client.HttpMethod; import com.woorea.openstack.base.client.OpenStackClient; import com.woorea.openstack.base.client.OpenStackRequest; import com.woorea.openstack.quantum.model.Port; import com.woorea.openstack.quantum.model.PortForCreate; import com.woorea.openstack.quantum.model.Ports; public class PortsResource { private final OpenStackClient CLIENT; public PortsResource(OpenStackClient client) { CLIENT = client; } public List list() { return new List(); } public Create create(PortForCreate net){ return new Create(net); } public Delete delete(String netId){ return new Delete(netId); } public Show show(String netId){ return new Show(netId); } public class List extends OpenStackRequest<Ports> { public List() { super(CLIENT, HttpMethod.GET, "ports", null, Ports.class); } } public class Query extends OpenStackRequest<Ports> { public Query(Port port) { //super(port); // target = target.path("v2.0").path("ports"); // target = queryParam(target); // return target.request(MediaType.APPLICATION_JSON).get(Ports.class); } } public class Create extends OpenStackRequest<Port> { public Create(PortForCreate port){ super(CLIENT, HttpMethod.POST, "ports", Entity.json(port), Port.class); } } public class Show extends OpenStackRequest<Port> { public Show(String id) { super(CLIENT, HttpMethod.GET, buildPath("ports/", id), null, Port.class); } } public class Delete extends OpenStackRequest<Void> { public Delete(String id){ super(CLIENT, HttpMethod.DELETE, buildPath("ports/", id), null, Void.class); } } } <file_sep>/quantum-model/src/main/java/com/woorea/openstack/quantum/model/NetworkForCreate.java package com.woorea.openstack.quantum.model; import java.io.Serializable; import org.codehaus.jackson.annotate.JsonProperty; import org.codehaus.jackson.map.annotate.JsonRootName; @JsonRootName("network") public class NetworkForCreate implements Serializable{ private String name; @JsonProperty("admin_state_up") private boolean adminStateUp; @JsonProperty("provider:network_type") private String providerNetworkType; @JsonProperty("provider:physical_network") private String providerPhysicalNetwork; @JsonProperty("provider:segmentation_id") private Integer providerSegmentationId; @JsonProperty("tenant_id") private String tenantId; /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the adminStateUp */ public boolean isAdminStateUp() { return adminStateUp; } /** * @param adminStateUp the adminStateUp to set */ public void setAdminStateUp(boolean adminStateUp) { this.adminStateUp = adminStateUp; } public String getProviderNetworkType() { return providerNetworkType; } public void setProviderNetworkType(String providerNetworkType) { this.providerNetworkType = providerNetworkType; } public String getProviderPhysicalNetwork() { return providerPhysicalNetwork; } public void setProviderPhysicalNetwork(String providerPhysicalNetwork) { this.providerPhysicalNetwork = providerPhysicalNetwork; } public Integer getProviderSegmentationId() { return providerSegmentationId; } public void setProviderSegmentationId(Integer providerSegmentationId) { this.providerSegmentationId = providerSegmentationId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
5e0a91f9dc249e89e94ee8640850cdc5145b3fd1
[ "Java" ]
5
Java
simon3z/openstack-java-sdk
0c6d39d34de0577ca300b3bc233c4d59dfeb8f3f
80f493209bedccdfe7aaaf07f6f7bdd8e8f3f022
refs/heads/master
<file_sep> // Dependencies var restful = require('node-restful'); var mongoose = restful.mongoose; // Schema var workbookSchema = new mongoose.Schema({ project: {id:String, name:String}, owner: {id: String}, tags : {}, id: String, name:String, contentUrl:String, showTabs:String, size:String, createdAt:String, updatedAt:String, }); // Return model module.exports = restful.model('Workbook', workbookSchema);
9044dd35a09b1ea10c4e71bf9ba3f1b546b09183
[ "JavaScript" ]
1
JavaScript
tharun06/rest
a0da563743f0324533f41a8ef9c4181d36f110de
a4284e00f15e7cd8310d2b8248d3b88823ee7992
refs/heads/master
<repo_name>five562/Test-Case-Editor<file_sep>/TestCaseEditor/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; using System.Xml.Serialization; using System.IO; namespace TestCaseEditor { public partial class Form1 : Form { //Variables Dictionary<string, string[]> filePaths = new Dictionary<string, string[]>(); Dictionary<string, string> fileName = new Dictionary<string, string>(); Dictionary<string, string> xmlFileNode = new Dictionary<string, string>(); public class newTestCase { public string project; public string version; public string module; public string createdBy; public string executedBy; public string date; public string passFail; public string testCaseId; public string step; public string expectation; public string comment; } public Form1() { InitializeComponent(); setComboBoxList("C:\\TestCases", this.projectNameComboBox); } private void projectNameComboBox_SelectedIndexChanged(object sender, EventArgs e) { versionComboBox.Text = moduleComboBox.Text = testCaseIdComboBox.Text = ""; versionComboBox.Items.Clear(); moduleComboBox.Items.Clear(); testCaseIdComboBox.Items.Clear(); generateFilePaths(); setComboBoxList(filePaths["Version"][0], this.versionComboBox); filePaths.Clear(); fileName.Clear(); } private void versionComboBox_SelectedIndexChanged(object sender, EventArgs e) { moduleComboBox.Text = testCaseIdComboBox.Text = ""; moduleComboBox.Items.Clear(); testCaseIdComboBox.Items.Clear(); generateFilePaths(); setComboBoxList(filePaths["Module"][0], this.moduleComboBox); filePaths.Clear(); fileName.Clear(); } private void moduleComboBox_SelectedIndexChanged(object sender, EventArgs e) { testCaseIdComboBox.Text = ""; testCaseIdComboBox.Items.Clear(); generateFilePaths(); string[] fileDirectories = Directory.GetFiles(filePaths["TestCases"][0] + "TestCases\\"); foreach (string directory in fileDirectories) { testCaseIdComboBox.Items.Add(Path.GetFileNameWithoutExtension(directory)); } filePaths.Clear(); fileName.Clear(); } private void dateTextBox_TextChanged(object sender, EventArgs e) { } private void testCaseIdComboBox_SelectedIndexChanged(object sender, EventArgs e) { } private void saveButton_Click(object sender, EventArgs e) { try { generateFilePaths(); saveFile(); MessageBox.Show("File is saved sucessfully"); cleanTextBoxes(); filePaths.Clear(); fileName.Clear(); } catch(Exception ex) { Console.WriteLine("Invalid xml file path"); Console.WriteLine(ex.ToString()); } } //This method will return the names of existed folders/files in the given directory public static List<string> processDirectory(string targetDirectory) { List<string> folderNameList = new List<string>(); //Get all files or subfolders undert a given directory string[] fileEntries = Directory.GetDirectories(targetDirectory); foreach (string fileName in fileEntries) { folderNameList.Add(Path.GetFileName(fileName)); } return folderNameList; } //Edit comboBox item list public void setComboBoxList(string directory, ComboBox comboBox) { if (Directory.Exists(directory)) { List<string> itemsList = processDirectory(directory).ToList(); foreach (string item in itemsList) { comboBox.Items.Add(item); } } } private void getButton_Click(object sender, EventArgs e) { generateFilePaths(); XmlParser p = new XmlParser(); Dictionary<string, string> xmlFile = p.loadXmlFile(filePaths["TestCasePath"][0], filePaths["TestCasePath"][1]); presentDataFromXmlFile(); executedByComboBox.Enabled = true; dateTextBox.Enabled = true; passFailComboBox.Enabled = true; } public void cleanTextBoxes() { projectNameComboBox.Text = versionComboBox.Text = moduleComboBox.Text = createdByComboBox.Text = executedByComboBox.Text = dateTextBox.Text = passFailComboBox.Text = testCaseIdComboBox.Text = stepRichTextBox.Text = expectationRichTextBox.Text = commentRichTextBox.Text = ""; projectNameComboBox.Items.Clear(); setComboBoxList("C:\\TestCases\\", this.projectNameComboBox); versionComboBox.Items.Clear(); moduleComboBox.Items.Clear(); executedByComboBox.Enabled = false; dateTextBox.Enabled = false; passFailComboBox.Enabled = false; } public void generateFilePaths() { newTestCase tC = new newTestCase(); try { if (projectNameComboBox.Text != "" || versionComboBox.Text != "" || moduleComboBox.Text != "" && testCaseIdComboBox.Text != "") { tC.project = projectNameComboBox.Text; tC.version = versionComboBox.Text; tC.module = moduleComboBox.Text; tC.testCaseId = testCaseIdComboBox.Text; filePaths.Add("Project", new string[] { "C:\\TestCases\\", "/Project" }); filePaths.Add("Version", new string[] { "C:\\TestCases\\" + tC.project + "\\", "/Version" }); filePaths.Add("Module", new string[] { "C:\\TestCases\\" + tC.project + "\\" + tC.version + "\\", "/Module" }); filePaths.Add("TestCases", new string[] { "C:\\TestCases\\" + tC.project + "\\" + tC.version + "\\" + tC.module + "\\", "/TestCases" }); filePaths.Add("TestResults", new string[] { "C:\\TestCases\\" + tC.project + "\\" + tC.version + "\\" + tC.module + "\\", "/TestResults" }); filePaths.Add("TestCasePath", new string[] { "C:\\TestCases\\" + tC.project + "\\" + tC.version + "\\" + tC.module + "\\TestCases\\" + tC.testCaseId + ".xml", "/TestCase" }); filePaths.Add("TestResultPath", new string[] { "C:\\TestCases\\" + tC.project + "\\" + tC.version + "\\" + tC.module + "\\TestResults\\" + tC.testCaseId + ".xml", "/TestCase" }); fileName.Add("Project", tC.project); fileName.Add("Version", tC.version); fileName.Add("Module", tC.module); fileName.Add("TestCases", tC.testCaseId); fileName.Add("TestResults", tC.testCaseId); //Generate all folders if (projectNameComboBox.Text != "" && versionComboBox.Text != "" && moduleComboBox.Text != "" && testCaseIdComboBox.Text != "") { if (!Directory.Exists(filePaths["TestCases"][0] + "TestCases\\")) { System.IO.Directory.CreateDirectory(filePaths["TestCases"][0] + "TestCases\\"); System.IO.Directory.CreateDirectory(filePaths["TestResults"][0] + "TestResults\\"); } } } }catch(Exception ex) { Console.WriteLine(ex.ToString()); } } private void saveFile() { try { if (executedByComboBox.Text == "") { string filePath = filePaths["TestCasePath"][0]; generateTestCaseXmlFile(filePath); } else { string filePath = filePaths["TestResultPath"][0]; generateTestCaseXmlFile(filePath); } }catch(Exception ex) { Console.WriteLine(ex.ToString()); } } private void presentDataFromXmlFile() { XmlParser p = new XmlParser(); Dictionary<string, string> xmlFile = p.loadXmlFile(filePaths["TestCasePath"][0], filePaths["TestCasePath"][1]); projectNameComboBox.Text = xmlFile["project"]; versionComboBox.Text = xmlFile["version"]; moduleComboBox.Text = xmlFile["module"]; createdByComboBox.Text = xmlFile["createdBy"]; executedByComboBox.Text = xmlFile["executedBy"]; dateTextBox.Text = xmlFile["date"]; passFailComboBox.Text = xmlFile["passFail"]; testCaseIdComboBox.Text = xmlFile["testCaseId"]; stepRichTextBox.Text = xmlFile["step"]; expectationRichTextBox.Text = xmlFile["expectation"]; commentRichTextBox.Text = xmlFile["comment"]; filePaths.Clear(); fileName.Clear(); } private void generateTestCaseXmlFile(string xmlFilePath) { try { XmlDocument testCaseXml = new XmlDocument(); //root element XmlElement rootElement = testCaseXml.CreateElement("TestCase"); testCaseXml.AppendChild(rootElement); //project element XmlElement projectElement = testCaseXml.CreateElement("project"); projectElement.InnerText = projectNameComboBox.Text; rootElement.AppendChild(projectElement); //version element XmlElement versionElement = testCaseXml.CreateElement("version"); versionElement.InnerText = versionComboBox.Text; rootElement.AppendChild(versionElement); //module elemnt XmlElement moduleElement = testCaseXml.CreateElement("module"); moduleElement.InnerText = moduleComboBox.Text; rootElement.AppendChild(moduleElement); //createdBy elemnt XmlElement createdByElement = testCaseXml.CreateElement("createdBy"); createdByElement.InnerText = createdByComboBox.Text; rootElement.AppendChild(createdByElement); //executedBy elemnt XmlElement executedByElement = testCaseXml.CreateElement("executedBy"); executedByElement.InnerText = executedByComboBox.Text; rootElement.AppendChild(executedByElement); //date elemnt XmlElement dateElement = testCaseXml.CreateElement("date"); dateElement.InnerText = dateTextBox.Text; rootElement.AppendChild(dateElement); //passFail elemnt XmlElement passFailElement = testCaseXml.CreateElement("passFail"); passFailElement.InnerText = passFailComboBox.Text; rootElement.AppendChild(passFailElement); //testCaseId elemnt XmlElement testCaseIdElement = testCaseXml.CreateElement("testCaseId"); testCaseIdElement.InnerText = testCaseIdComboBox.Text; rootElement.AppendChild(testCaseIdElement); //step elemnt XmlElement stepElement = testCaseXml.CreateElement("step"); stepElement.InnerText = stepRichTextBox.Text; rootElement.AppendChild(stepElement); //expectation elemnt XmlElement expectationElement = testCaseXml.CreateElement("expectation"); expectationElement.InnerText = expectationRichTextBox.Text; rootElement.AppendChild(expectationElement); //comment elemnt XmlElement commentElement = testCaseXml.CreateElement("comment"); commentElement.InnerText = commentRichTextBox.Text; rootElement.AppendChild(commentElement); testCaseXml.Save(xmlFilePath); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } } } <file_sep>/TestCaseEditor/Chart.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.Windows.Forms.DataVisualization.Charting; namespace TestCaseEditor { public partial class Chart : Form { string fileDirectory = @"C:\TestCases"; public Chart() { InitializeComponent(); setComboBoxItems(projectComboBox, getItems(fileDirectory)); } private void projectComboBox_SelectedIndexChanged(object sender, EventArgs e) { fileDirectory += @"\" + projectComboBox.Text; setComboBoxItems(versionComboBox, getItems(fileDirectory)); fileDirectory = @"C:\TestCases"; } private void versionComboBox_SelectedIndexChanged(object sender, EventArgs e) { } private void testerComboBox_SelectedIndexChanged(object sender, EventArgs e) { } private void showChartButton_Click(object sender, EventArgs e) { fileDirectory += @"\" + projectComboBox.Text + @"\" + versionComboBox.Text; setChart(fileDirectory); fileDirectory = @"C:\TestCases"; versionComboBox.Items.Clear(); } public void setChart(string directory) { this.dataChart.Series.Clear(); this.dataChart.Titles.Clear(); this.dataChart.Titles.Add("Module Data"); Series series = this.dataChart.Series.Add("Module Data"); Series resultSeries = this.dataChart.Series.Add("Result Data"); series.ChartType = SeriesChartType.Column; resultSeries.ChartType = SeriesChartType.Column; //Prepare X and Y values string[] modules = getItems(directory); foreach(string module in modules) { string[] testCaseList = Directory.GetFiles(directory + @"\" + module + @"\TestCases\"); string[] testResultList = Directory.GetFiles(directory + @"\" + module + @"\TestResults\"); double x = testCaseList.Length; double y = testResultList.Length; series.Points.AddXY(module, x ); resultSeries.Points.AddXY(module, y ); } } public string[] getItems(string directory) { List<string> nameList = new List<string>(); try { if (Directory.Exists(directory)) { string[] fileEntries = Directory.GetDirectories(directory); foreach (string file in fileEntries) { nameList.Add(Path.GetFileName(file)); } } }catch(Exception e) { Console.WriteLine(e.ToString()); } return nameList.ToArray(); } public void setComboBoxItems(ComboBox combox, string[] items) { foreach(string item in items) { combox.Items.Add(item); } } } } <file_sep>/TestCaseEditor/XmlParser.cs using System; using System.Collections.Generic; //using System.Linq; //using System.Text; //using System.Threading.Tasks; using System.Xml; //using System.Xml.Linq; using System.IO; namespace TestCaseEditor { class XmlParser { public Dictionary<string,string> loadXmlFile(string xmlFilePath, string xmlNode) { Dictionary<string, string> file = new Dictionary<string, string>(); XmlDocument xmlfile = new XmlDocument(); try { xmlfile.Load(xmlFilePath); XmlNode root; root = xmlfile.SelectSingleNode(xmlNode); if (root.HasChildNodes) { foreach (XmlNode n in root.ChildNodes) { file.Add(n.Name, n.InnerText); } } } catch(Exception ex) { Console.WriteLine(ex.ToString()); } return file; } } }
e340051cb43723f51d872adfbce03c2e5c3d388a
[ "C#" ]
3
C#
five562/Test-Case-Editor
c4c3ab32d22ac407e015fae72d19d24c93ac7734
b81180c8564a9734724be3036c73f0cecccebcb5
refs/heads/master
<file_sep>__version__ = "0.1.1" from kivy.app import App from kivy.uix.label import Label class MyApp(App): def build(self): return Label(text="Preprandonos para el taller de Kivy") if __name__ == '__main__': MyApp().run() <file_sep># README Realizar estos pasos en Linux o máquina virtual. Esto descarga muchas cosas en ~/.buildozer que no vamos a poder descargar en la red de la UNS: * `sudo pip install buildozer` * `buildozer android debug`
29795df0972251d77234df01bad92b9b09f34c23
[ "Markdown", "Python" ]
2
Python
D3f0/pyconar16_kivy_warmup
8c0debb97cc6aa80bcc8efea588d156bad31cf2a
6ff0db89ba48ac46d48de0e9cb248784f751fe44
refs/heads/master
<repo_name>corting/Script-JavaScript-Arcgis<file_sep>/Bottons.js 'use strict'; var map; require(['esri/map', 'esri/layers/ArcGISTiledMapServiceLayer', 'esri/layers/ArcGISDynamicMapServiceLayer', 'esri/symbols/LineSymbol', 'esri/layers/FeatureLayer', 'dojo/domReady!'], function(Map, ArcGISTiledMapServiceLayer, ArcGISDynamicMapServiceLayer, LineSymbol, FeatureLayer) { map = new Map('mapaCache',{ center: [-56.049,38.485], zoom: 3, basemap: 'streets' }); var btn2 = document.getElementById('btn2'); var btn = document.getElementById('btn'); /*this botton add a base map and delete all layers*/ btn.addEventListener('click', function(){ var satellite = map.setBasemap('satellite'); map.removeAllLayers() }); /*this other botton ad layer*/ btn2.addEventListener('click', function(){ var UrlCache = 'http://services.arcgisonline.com/arcgis/rest/services/Ocean_Basemap/MapServer'; var Urldinamic = 'http://sampleserver6.arcgisonline.com/arcgis/rest/services/USA/MapServer'; var Urlfeature = 'http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/PublicSafety/PublicSafetyFeedSample/MapServer/1'; var mapacache = new ArcGISTiledMapServiceLayer(UrlCache) map.addLayer(mapacache); var mapadinamico = new ArcGISDynamicMapServiceLayer(Urldinamic) map.addLayer(mapadinamico); var mapafeautre = new FeatureLayer(Urlfeature) map.addLayer(mapafeautre); }); });
0d241bc15583d28fae1086ff039a4a2392fcff35
[ "JavaScript" ]
1
JavaScript
corting/Script-JavaScript-Arcgis
82f7f95e1c80fa64332fbc4dcf3c8a29d5480ef7
4a06ea4bd6c228306b84e96a23e9d8e946b73313
refs/heads/master
<file_sep>var fs = require('fs'), path = './index.html', stats; try { stats = fs.statSync(path); console.log("Index.html exists; if there are other files, they will be listed below:"); } catch (e) { console.log("Index.html is not present; if there are other files, they will be listed below:"); } var fs = require('fs'); fs.realpath(__dirname, function(err, path) { if (err) { console.log(err); return; } console.log('Path is : ' + path); }); fs.readdir(__dirname, function(err, files) { if (err) return; files.forEach(function(f) { console.log('Files: ' + f); }); }); <file_sep># DevOps tasks ## Task 1 In the zip file new_tasks.zip you can find several tasks that are given to front-end candidates. Your job is to do your best to create tests that would check if candidates followed the instructions. Your tests should cover as much possible the sections "Definition of Done" and "You will fail". Lack of information in the task description is intentional. You are free to use any tools you need, however, the only acceptable language is JS. Example: ## Task5 front-end requirements ### You will fail * if you use anything else apart what is in the index.html file (nothing more than Bootstrap) Possible solution: * Create a nodeJS script that checks if the folder contains anything besides the index.html file ## Task 2 Create a Node app from Task3, package it as Docker. Put nginx in front of it; must be its own image. Bonus - make additional route /admin and protect it from nginx. ### You will fail * If you don't package your solution with Docker, if you don't combine containers ## Task 3 Create a IIS (config file) with common security headers, and find a way to inject GTM script through IIS. ### You will fail * If you don't include at least Strict Transport Security, X-Powered-By and Content-Type Option headers. * For the GTM part, we are more interested in your approach to solving this, but you will fail if you don't propose any solution. <!--stackedit_data: eyJoaXN0b3J5IjpbLTE4MTE0MzUxMF19 --><file_sep># Responsive banner ## Description We need to build a responsive ad in several sizes as required by the client. The ad should adapt at least for the sizes set below. There is a poster in the img folder, that was used in a previous campaign. You can use the poster as a reference. The word "Familiar" should always stay on top or on the left side, depending on the banner size. "Join our team" should always be on bottom or right, depending on the banner size. Logos in square containers should stay square. e.g. 120x600 One solution could be to have "Familiar" and "Join our team" at the top and bottom while the logos could fall one below the other. e.g. 240x400 Same as above, but the logos fall one below the other in pairs Note: It is not expected to be pretty just to be working. ## Assets/Logos * [CSS](https://commons.wikimedia.org/wiki/File:CSS3_logo_and_wordmark.svg) * [HTML](https://commons.wikimedia.org/wiki/File:HTML5_logo_and_wordmark.svg) * [React](https://commons.wikimedia.org/wiki/File:React-icon.svg) * [Mongo](https://worldvectorlogo.com/logo/mongodb) * [JS](https://commons.wikimedia.org/wiki/File:JavaScript-logo.png) * [MYSQL](https://worldvectorlogo.com/logo/mysql) * [Node](https://commons.wikimedia.org/wiki/File:Node.js_logo.svg) * [CMG](https://www.convergent-usa.com/_nuxt/img/logo.d5d3c6a.png) ## Definition Of Done * body is used as the root container * the banner is responsive and adapts to the following sizes * Half Page (300×600) * Vertical rectangle (240x400) * Skyscraper (120x600) * Full banner (468x60) * Does not have inappropriate margins and borders. * Everything is in one file below 50KB * We don't have to install anything (plain HTML) * no CSS frameworks used (JS neither) ## You will fail * if any element has position: absolute; * if logos are not in square containers ## Bonus * Use of CSS animations
4f4fdf4a394663367d645c871cc3ce37c8acc11e
[ "JavaScript", "Markdown" ]
3
JavaScript
theFest/Job-Interview-2
3e85f598e039c5e7c6a4489d28aad5aeede435e0
09c484bef026510093eef22dc88b06a196a42fb9
refs/heads/master
<file_sep>#include "arrow.hpp" #include <QtCore/QPoint> #include <QtGui/QPainter> #include <QtGui/QPaintEvent> #include <QtCore/qmath.h> Arrow::Arrow(const QPoint &begin, const QPoint &end) : _begin(begin), _end(end) { } QPoint Arrow::getBegin() const { return _begin; } QPoint Arrow::getEnd() const { return _end; } double Arrow::height() const { return qSqrt(qPow(_begin.x() - _end.x(), 2) + qPow(_begin.y() - _end.y(), 2)); } void Arrow::setBegin(const QPoint &begin) { _begin = begin; } void Arrow::setEnd(const QPoint &end) { _end = end; } void Arrow::paint(QPainter &painter) { painter.drawLine(_begin, _end); // Fix this int r = static_cast<int>(height()) * _RATIO; painter.drawEllipse(_end, r, r); } ThinLens::AbstractObject *Arrow::clone() const { return new Arrow(*this); } <file_sep>#ifndef THINLENSSYSTEM_HPP #define THINLENSSYSTEM_HPP #include <QtGui/QWidget> #include <QtGui/QPainter> #include <QtGui/QPaintEvent> #include <memory> #include "abstractobject.hpp" namespace ThinLens { class ThinLensSystem : public QWidget { Q_OBJECT public: enum { showRays = 0x1, showInfo = 0x2 // Show F, f, d, height of object and image }; explicit ThinLensSystem ( AbstractObject &object, int focus = 50, unsigned flags = showInfo, QWidget *parent = 0 ); int getFocus() const noexcept; void setFocus(int) noexcept; void switchType() noexcept; const AbstractObject& getObject() const noexcept; void setObject(AbstractObject &object) noexcept; const AbstractObject& getImage() const noexcept; unsigned getFlags() const noexcept; void setFlags(unsigned) noexcept; int getObjectDistance() const noexcept; void setObjectDistance(int) noexcept; int getImageDistance() const; double getImageHeight() const; QPoint getFocalPoint(const QPoint &) const noexcept; QPoint getAxisCenter() const noexcept; protected: void paintEvent(QPaintEvent *); private: void _drawAxis(QPainter &) const noexcept; void _drawLens(QPainter &) const noexcept; void _drawRays(QPainter &) const noexcept; void _drawInfo(QPainter &) const noexcept; void _drawRaysFromPoint(QPainter &, const QPoint &) const noexcept; QPoint _calculatePoint(const QPoint &) const; void _calculateImage() noexcept; private: AbstractObject &_object; std::shared_ptr<AbstractObject> _image; int _focus; unsigned _flags; }; } // namespace ThinLens #endif // THINLENSSYSTEM_HPP <file_sep>#include <QtGui/QApplication> #include <QtCore/QPoint> #include "arrow.hpp" #include "mainwindow.hpp" #include "thin_lens_widget/thinlenssystem.hpp" int main(int argc, char *argv[]) { QApplication a(argc, argv); Arrow arrow(QPoint(200, 100), QPoint(200, 50)); MainWindow w(arrow); w.showMaximized(); return a.exec(); } <file_sep>#ifndef MAINWINDOW_HPP #define MAINWINDOW_HPP #include <QtGui/QMainWindow> #include <QtCore/QPoint> #include <memory> #include "arrow.hpp" #include "thin_lens_widget/abstractobject.hpp" #include "thin_lens_widget/thinlenssystem.hpp" class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow ( ThinLens::AbstractObject &, int focus = 40, unsigned flags = ThinLens::ThinLensSystem::showInfo, QWidget *parent = 0 ); ~MainWindow(); protected: void mousePressEvent(QMouseEvent *); void mouseMoveEvent(QMouseEvent *); void wheelEvent(QWheelEvent *); private: void _moveObject(const QPoint &center); private: ThinLens::AbstractObject &_object; ThinLens::ThinLensSystem _system; private: static constexpr auto DELTA_FOCUS = 2u; }; #endif // MAINWINDOW_HPP <file_sep>#ifndef LINE_HPP #define LINE_HPP #include <QtCore/QPointF> namespace soon { namespace geometry { // FIXME // We can't specify a line || OY class Line { public: Line(int, int, int, int) noexcept; Line(const QPoint &, const QPoint &) noexcept; Line(const QPoint &, int, int) noexcept; Line(int, int, const QPoint &) noexcept; int y(int x) const noexcept; friend bool operator|| (const Line &, const Line &) noexcept; friend QPoint operator& (const Line &, const Line &); bool operator== (const Line &) noexcept; private: double _k; double _b; }; } // namespace geometry } // namespace soon #endif // LINE_HPP <file_sep>#ifndef ABSTRACTOBJECT_HPP #define ABSTRACTOBJECT_HPP #include <QtCore/QPoint> #include <QtGui/QPainter> #include <QtGui/QPaintEvent> namespace ThinLens { class AbstractObject { public: virtual ~AbstractObject() { } virtual QPoint getBegin() const = 0; virtual QPoint getEnd() const = 0; virtual double height() const = 0; virtual void setBegin(const QPoint &) = 0; virtual void setEnd(const QPoint &) = 0; virtual void paint(QPainter &) = 0; virtual AbstractObject *clone() const = 0; }; } // namespace ThinLens #endif // ABSTRACTOBJECT_HPP <file_sep>#ifndef ARROW_HPP #define ARROW_HPP #include <QtCore/QPoint> #include <QtGui/QPainter> #include <QtGui/QPaintEvent> #include <QtCore/qmath.h> #include "thin_lens_widget/abstractobject.hpp" class Arrow : public ThinLens::AbstractObject { public: explicit Arrow(const QPoint &, const QPoint &); QPoint getBegin() const; QPoint getEnd() const; double height() const; void setBegin(const QPoint &); void setEnd(const QPoint &); void paint(QPainter &); ThinLens::AbstractObject *clone() const; private: QPoint _begin; QPoint _end; // static constexpr double _ANGLE = M_PI / 18; static constexpr double _RATIO = 0.1; }; #endif // ARROW_HPP <file_sep>#include "mainwindow.hpp" #include <QtCore/QPoint> #include <algorithm> MainWindow::MainWindow ( ThinLens::AbstractObject &object, int focus, unsigned flags, QWidget *parent ) : QMainWindow(parent), _object(object), _system(_object, focus, flags) { setCentralWidget(&_system); } void MainWindow::_moveObject(const QPoint &center) { auto delta = center - QPoint ( (_object.getBegin().x() + _object.getEnd().x()) / 2, (_object.getBegin().y() + _object.getEnd().y()) / 2 ); _object.setBegin(_object.getBegin() + delta); _object.setEnd(_object.getEnd() + delta); update(); } void MainWindow::mousePressEvent(QMouseEvent *event) { if(event -> button() == Qt::LeftButton) _moveObject(event -> pos()); } void MainWindow::mouseMoveEvent(QMouseEvent *event) { if(event -> buttons() & Qt::LeftButton) { auto p = event -> pos(); if((p.x() > 0) && (p.x() < width()) && (p.y() > 0) && (p.y() < height())) _moveObject(p); } } void MainWindow::wheelEvent(QWheelEvent *event) { _system.setFocus ( _system.getFocus() + ( (event -> delta() > 0) ? (DELTA_FOCUS) : (-DELTA_FOCUS) ) ); update(); } MainWindow::~MainWindow() { } <file_sep>#include "thinlenssystem.hpp" #include <Qt> #include <QtCore/QRect> #include <QtCore/QPoint> #include <QtCore/QString> #include <string> #include <algorithm> #include <stdexcept> #include <cmath> #include "geometry/line.hpp" namespace ThinLens { ThinLensSystem::ThinLensSystem ( AbstractObject &object, int focus, unsigned flags, QWidget *parent ) : QWidget(parent), _object(object), _image(_object.clone()), _focus(focus), _flags(flags) { } int ThinLensSystem::getFocus() const noexcept { return _focus; } void ThinLensSystem::setFocus(int focus) noexcept { _focus = focus; update(); } void ThinLensSystem::switchType() noexcept { _focus = -_focus; update(); } const AbstractObject &ThinLensSystem::getObject() const noexcept { return _object; } void ThinLensSystem::setObject(AbstractObject &object) noexcept { _object = object; _image.reset(_object.clone()); update(); } const AbstractObject &ThinLensSystem::getImage() const noexcept { return *_image; } int ThinLensSystem::getObjectDistance() const noexcept { return std::abs(width() / 2 - _object.getBegin().x()); } void ThinLensSystem::setObjectDistance(int dist) noexcept { _object.setBegin(_object.getBegin() + QPoint(dist, 0)); _object.setEnd(_object.getEnd() + QPoint(dist, 0)); update(); } int ThinLensSystem::getImageDistance() const { if(!_image) throw std::invalid_argument("No image"); // return _image -> getBegin().x() - width() / 2; auto d = getObjectDistance(); return ((d == _focus) ? (0) : ((_focus * d) / (d - _focus))); } unsigned ThinLensSystem::getFlags() const noexcept { return _flags; } void ThinLensSystem::setFlags(unsigned flags) noexcept { _flags = flags; } QPoint ThinLensSystem::getFocalPoint(const QPoint &point) const noexcept { return QPoint(width() / 2 + ((point.x() > width() / 2) ? (-_focus) : (_focus)), height() / 2); } QPoint ThinLensSystem::getAxisCenter() const noexcept { return QPoint(width() / 2, height() / 2); } void ThinLensSystem::_drawAxis(QPainter &painter) const noexcept { painter.drawLine(0, height() / 2, width(), height() / 2); painter.drawLine ( width() / 2 + _focus, height() / 2 - 5, width() / 2 + _focus, height() / 2 + 5 ); painter.drawLine ( width() / 2 + 2 * _focus, height() / 2 - 5, width() / 2 + 2 * _focus, height() / 2 + 5 ); painter.drawLine ( width() / 2 - _focus, height() / 2 - 5, width() / 2 - _focus, height() / 2 + 5 ); painter.drawLine ( width() / 2 - 2 * _focus, height() / 2 - 5, width() / 2 - 2 * _focus, height() / 2 + 5 ); // Switch F and F' if the object in the right side of the lens auto k = ((_object.getBegin().x() > width() / 2) ? (-1) : (1)); if(std::abs(_focus) > 10) { painter.drawText(width() / 2 + _focus * k - 2, height() / 2 + 20, "F"); painter.drawText(width() / 2 - _focus * k - 2, height() / 2 + 20, "F'"); } if(std::abs(_focus) > 20) { painter.drawText ( width() / 2 + 2 * _focus * k - 2, height() / 2 + 20, "2F" ); painter.drawText ( width() / 2 - 2 * _focus * k - 2, height() / 2 + 20, "2F'" ); } } void ThinLensSystem::_drawLens(QPainter &painter) const noexcept { auto dist = std::max ( std::abs(height() / 2 - _object.getBegin().y()), std::abs(height() / 2 - _object.getEnd().y()) ) + 20; painter.drawLine ( width() / 2, height() / 2 - dist, width() / 2, height() / 2 + dist ); auto delta = ((_focus > 0) ? (10) : (-10)); painter.drawLine ( width() / 2, height() / 2 - dist, width() / 2 + std::abs(delta), height() / 2 - dist + delta ); painter.drawLine ( width() / 2, height() / 2 - dist, width() / 2 - std::abs(delta), height() / 2 - dist + delta ); painter.drawLine ( width() / 2, height() / 2 + dist, width() / 2 + std::abs(delta), height() / 2 + dist - delta ); painter.drawLine ( width() / 2, height() / 2 + dist, width() / 2 - std::abs(delta), height() / 2 + dist - delta ); } void ThinLensSystem::_drawRaysFromPoint ( QPainter &painter, const QPoint &point ) const noexcept { // From point to lens || OX painter.drawLine(point, QPoint(width() / 2, point.y())); // From point to axis center painter.drawLine(point, getAxisCenter()); try { auto end = _calculatePoint(point); // From end to lens || OX painter.drawLine(end, QPoint(width() / 2, point.y())); // From end to axis center painter.drawLine(end, getAxisCenter()); } catch(std::invalid_argument) { // TODO } } void ThinLensSystem::_drawRays(QPainter &painter) const noexcept { _drawRaysFromPoint(painter, _object.getBegin()); _drawRaysFromPoint(painter, _object.getEnd()); } void ThinLensSystem::_drawInfo(QPainter &painter) const noexcept { QString info; info += QString("F: ") += QString::number(_focus); info += ((_focus > 0) ? (" (collecting)") : (" (diverging)")); info += '\n'; info += QString("d: ") += QString::number(getObjectDistance()) += '\n'; try { auto f = getImageDistance(); info += QString("f: ") += QString::number(f); info += ((f > 0) ? (" (real)") : (" (imaginary)")); info += '\n'; } catch(std::invalid_argument) { info += "f: No image\n"; } info += '\n'; info += QString("Object height: ") += QString::number(_object.height()) += '\n'; if(_image) { info += QString("Image height: ") += QString::number(_image -> height()) += '\n'; info += QString("k: ") += QString::number(_image -> height() / _object.height()) += '\n'; } painter.drawText(QRect(20, 20, 150, 150), Qt::TextWordWrap, info); } QPoint ThinLensSystem::_calculatePoint(const QPoint &p) const { using namespace soon::geometry; // From point to axis center Line l1(p, getAxisCenter()); // From lens to focal point Line l2(width() / 2, p.y(), getFocalPoint(p)); if(l1 == l2) { Line rnd(p.x(), p.y() + 100000, getAxisCenter()); auto intersectionWithFocal = QPoint(getFocalPoint(p).x(), rnd.y(getFocalPoint(p).x())); l2 = Line(width() / 2, height() / 2 - 100000, intersectionWithFocal); // FIXME // Line focal(width() / 2 + _focus * k, height() / 2, width() / 2 + _focus * k, height() / 2 - 10); // Line rnd(p.x(), p.y() - 10, width() / 2, height() / 2); // auto frp = focal & rnd; // l1 = Line(p, width() / 2 + 10, height() / 2); // l2 = Line(width() / 2 + 10, height() / 2, frp); } return l1 & l2; } void ThinLensSystem::_calculateImage() noexcept { try { auto begin = _calculatePoint(_object.getBegin()); auto end = _calculatePoint(_object.getEnd()); if(!_image) _image.reset(_object.clone()); _image -> setBegin(begin); _image -> setEnd(end); } catch(std::invalid_argument) { _image.reset(); } } void ThinLensSystem::paintEvent(QPaintEvent *) { QPainter painter(this); _drawAxis(painter); _drawLens(painter); _object.paint(painter); _calculateImage(); if(_image) _image -> paint(painter); if(_flags & showRays) _drawRays(painter); if(_flags & showInfo) _drawInfo(painter); } } // namespace ThinLens <file_sep>#include "line.hpp" #include <QtCore/QPoint> #include <limits> #include <cmath> #include <stdexcept> namespace soon { namespace geometry { Line::Line(int x1, int y1, int x2, int y2) noexcept : _k(static_cast<double>(y1 - y2) / (x1 - x2)), _b(y1 - _k * x1) { } Line::Line(const QPoint &p1, const QPoint &p2) noexcept : Line(p1.x(), p1.y(), p2.x(), p2.y()) { } Line::Line(const QPoint &p, int x, int y) noexcept : Line(p.x(), p.y(), x, y) { } Line::Line(int x, int y, const QPoint &p) noexcept : Line(p, x, y) { } int Line::y(int x) const noexcept { return static_cast<int>(_k * x + _b); } bool operator|| (const Line &l1, const Line &l2) noexcept { return std::abs(l1._k - l2._k) < std::numeric_limits<double>::epsilon(); } QPoint operator& (const Line &l1, const Line &l2) { if(l1 || l2) throw std::invalid_argument("The lines are parralel"); auto x = -(l1._b - l2._b) / (l1._k - l2._k); return QPoint(x, l1.y(x)); } bool Line::operator== (const Line &l) noexcept { return (*this || l) && (std::abs(_b - l._b) < std::numeric_limits<double>::epsilon()); } } // namespace geometry } // namespace soon
40fdbf65513e3938ebdb2524cc648453db1e4c83
[ "C++" ]
10
C++
soon/thin_lens
80f4d710310efa12120789ddad360d356cab73b4
f4233f2f20f0f824aeaa3b93e1fa4ad2be9c4fb2
refs/heads/master
<repo_name>kkrawczyk5/Module-7-Functions<file_sep>/Problem5Squares.py #Created by <NAME> #02/29/2020 #Problem 5 #This program takes the starter code provided and creates the picture that was requested. import turtle def drawSquare(t, sz): """Get turtle t to draw a square of sz side""" for i in range(4): t.forward(sz) t.left(90) wn = turtle.Screen() alex = turtle.Turtle() alex.color("blue") new_position= -5 for n in range(10, 60, 10): drawSquare(alex, n) alex.penup() alex.goto(new_position, new_position) alex.pendown() new_position = new_position -5 wn.exitonclick() #import turtle #def drawSquare(t, sz): # """Get turtle t to draw a square of sz side""" # for i in range(4): # t.forward(sz) # t.left(90) #wn = turtle.Screen() #alex = turtle.Turtle() #alex.color("blue") #size = [20, 40, 60, 80, 100] #for x in size: # drawSquare(alex,x) # alex.penup() # alex.backward(10) # move alex to the starting position for the next square # alex.right(90) # alex.forward(10) # alex.left(90) # alex.pendown() #wn.exitonclick() <file_sep>/Problem1AreaOfCircle.py # Created by <NAME> # 02/29/2020 # Problem 1 # This problem uses a function to calculate the area of a circle and returns the radius import math #import math library def areaOfCircle(r): #function to calculate the area y = r**2 * math.pi return y print (areaOfCircle(5)) #prints the result <file_sep>/Problem2CheckRange.py # Created by <NAME> # 02/29/2020 # Problem 2 # This problem takes a number and outputs if the number is within the given range def given_range(x): #function for the range if x in range(1,10): print (x, "is in the range") else: print(x, "is not in the range") given_range(5) #number to see if it is in range <file_sep>/Problem3MultiplyList.py # Created by <NAME> # 02/29/2020 # Problem 3 # This problem uses a function to multiple a list of numbers def multiply_list(num): #function to multiple the list of numbers total = 1 for x in num: total *= x return total print(multiply_list((5, 2, 7, -1))) #output and the list of numbers<file_sep>/README.md # Module-7-Functions This repository was created to display week 7 assignments for my CSS225 course. <file_sep>/Problem4Unique.py # Created by <NAME> # 02/29/2020 # Problem 4 # This problem uses a function look at a list of numbers and remove any repeats def new_unique_list(num): #function to remove the repeat numbers list = [] for n in num: if n not in list: list.append(n) return list print (new_unique_list([1, 3, 3, 3, 6, 2, 3, 5])) #prints the list with only non-repeated numbers<file_sep>/Problem6Flower.py #Created by <NAME> #02/29/2020 #Problem 6 #This program creates the shape that was requested for this activity #I was unable to figure out how to perfectly recreate the shape displayed import turtle def drawShape(t): for i in range(5): t.forward(120) t.left(72) wn = turtle.Screen() alex = turtle.Turtle() alex.color("pink") for n in range(60, 670, 60): drawShape(alex) alex.penup() alex.goto(0,0) alex.left(32) alex.pendown() wn.exitonclick()
c867a6da111d15f94af7d7c4b9fbc43ab786d619
[ "Markdown", "Python" ]
7
Python
kkrawczyk5/Module-7-Functions
6487043b3a4f1977fa34a86ebdfbab96513adecb
a44bff4ea9effd4a5d3963a276654ae15179b1ee
refs/heads/master
<file_sep>#!/bin/bash cd $(dirname $0) exec ./jmeter.sh -Djava.rmi.server.hostname=127.0.0.1 \ -Jremote_hosts=127.0.0.1:55501 \ -Jclient.rmi.localport=55512 \ -Jmode=Batch \ -Jnum_sample_threshold=250 \ -server.rmi.ssl.disable=true \ "$@"<file_sep>--- page: https://idle.run/jmeter-remote title: "Remote JMeter over SSH" tags: jmeter ssh date: 2018-02-21 --- To control JMeter running on a remote server over SSH. Reference: https://blog.ionelmc.ro/2012/02/16/how-to-run-jmeter-over-ssh-tunnel/ ## Client Wrapper Automatically download JMeter client as required [jmeter wrapper](jmeter.sh) ``` #!/bin/bash cd $(dirname $0) if [[ ! -d .jmeter ]] || [[ ! -d .jmeter/apache-jmeter-4.0 ]]; then echo "Downloading jmeter.." mkdir -p .jmeter pushd .jmeter &>/dev/null curl -Ss http://muug.ca/mirror/apache-dist/jmeter/binaries/apache-jmeter-4.0.tgz | pv | tar x popd fi exec .jmeter/apache-jmeter-4.0/bin/jmeter "$@" ``` ## Client Command [jmeter-remote-client](jmeter-remote-client.sh) ``` ./jmeter.sh -Djava.rmi.server.hostname=127.0.0.1 \ -Jremote_hosts=127.0.0.1:55501 \ -Jclient.rmi.localport=55512 \ -Jmode=Batch \ -Jnum_sample_threshold=250 \ -Jserver.rmi.ssl.disable=true ``` ## Server Command [jmeter-remote-server](jmeter-remote-server.sh) ``` ./jmeter.sh -s -Djava.rmi.server.hostname=127.0.0.1 \ -Jserver_port=55501 \ -Jserver.rmi.localhostname=127.0.0.1 \ -Jserver.rmi.localport=55511 \ -Jserver.rmi.ssl.disable=true ``` ## SSH Command ``` ssh -L 55501:127.0.0.1:55501 -L 55511:127.0.0.1:55511 -R 55512:127.0.0.1:55512 user@hostname ``` <file_sep>#!/bin/bash cd $(dirname $0) if [[ ! -d .jmeter ]] || [[ ! -d .jmeter/apache-jmeter-4.0 ]]; then echo "Downloading jmeter.." mkdir -p .jmeter pushd .jmeter &>/dev/null curl -Ss http://muug.ca/mirror/apache-dist/jmeter/binaries/apache-jmeter-4.0.tgz | pv | tar x popd fi exec .jmeter/apache-jmeter-4.0/bin/jmeter "$@"<file_sep>#!/bin/bash cd $(dirname $0) exec ./jmeter.sh -s -Djava.rmi.server.hostname=127.0.0.1 \ -Jserver_port=55501 \ -Jserver.rmi.localhostname=127.0.0.1 \ -Jserver.rmi.localport=55511 \ -Jserver.rmi.ssl.disable=true \ "$@"
2129931ea88a9922516efe3dcc1de81a09e0bc9b
[ "Markdown", "Shell" ]
4
Shell
idlerun/jmeter-remote
8ad73e5e67bff3e9696b44f6504352e7c4dbee1a
b8545451ca12c8c622ef815f0ce8e0c55d262ae5
refs/heads/main
<repo_name>MCSeal/Rest<file_sep>/controller/feed.js const fs = require('fs') const path = require('path') const { validationResult } = require('express-validator/check'); const Post = require ('../models/post'); const User = require('../models/user') exports.getPosts = async (req, res, next) => { const currentPage = req.query.page || 1; const perPage = 2; let totalItems; try{ const totalItems = await Post.find().countDocuments() const posts = await Post.find() .skip((currentPage - 1) * perPage) .limit(perPage); res.status(200).json({ message: 'fetched posts', posts: posts, totalItems}); } catch(err) { if (err.status){ err.statusCode = 500; } next(err); } }; exports.createPost = async (req, res, next) => { //validation other part const errors = validationResult(req); //if errors is not empty then errors happoened if (!errors.isEmpty()){ const error = new Error('Validation Failed'); error.statusCode = 422; throw error; } //file upload.. if not set so error stuff if (!req.file) { const error = new Error('no image provided'); //validation error, and thorw error.statusCode = 422; throw error } //multer sets up path const imageUrl = req.file.path.replace("\\" ,"/"); const title = req.body.title; const content = req.body.content; //201 - tell client successfully created, 200 is just success //4tyh part of mongodb const post = new Post ({ title: title, content: content, imageUrl: imageUrl, creator: req.userId }); try{ await post.save() //add to list of posts of user const user = await User.findById(req.userId); user.posts.push(post); await user.save(); res.status(201).json({ message: 'Post successful', post: post, creator: {_id: user._id, name: user.name} }); } catch(err){ if (err.status){ err.statusCode = 500; } next(err); } }; exports.getPost= async (req, res, next) => { const postId= req.params.postId; try{ const post = await Post.findById(postId) if (!post){ const error = new Error('Could not find Post') error.statusCode = 404; throw error; } res.status(200).json({message: 'Post fetched.', post:post}) } catch (err) { if (err.status){ err.statusCode = 500; } next(err); } } exports.updatePost = async (req, res, next) => { const postId = req.params.postId; //validation other part const errors = validationResult(req); //if errors is not empty then errors happoened if (!errors.isEmpty()){ const error = new Error('Validation Failed'); error.statusCode = 422; throw error; } //validation other part const title = req.body.title; const content = req.body.content; let imageUrl = req.body.image; //if there is a file if (req.file){ imageUrl = req.file.path.replace("\\","/"); } //if no file throw error if (!imageUrl){ const error = new Error('No file picked.'); error.statusCode = 422; throw error; } try{ const post = await Post.findById(postId) if (!post){ const error = new Error('Could not find Post') error.statusCode = 404; throw error; } if (post.creator.toString() !== req.userId){ const error = new Error('Not authorized!') error.statusCode = 403 throw error; } if (imageUrl !== post.imageUrl){ clearImage(post.imageUrl); } post.title = title; post.imageUrl = imageUrl post.content = content; const result = await post.save(); res.status(200).json({ message: 'Post updated!', post: result}) } catch(err){ if (err.status){ err.statusCode = 500; } next(err); } }; exports.deletePost = async (req, res, next) => { const postId = req.params.postId; try{ const post = await Post.findById(postId) if (!post){ const error = new Error('Could not find Post') error.statusCode = 404; throw error; } //check logged in user if (post.creator.toString() !== req.userId){ const error = new Error('Not authorized!') error.statusCode = 403 throw error; } //delete image clearImage(post.imageUrl) await Post.findByIdAndRemove(postId); //deleting user connection to post const user = await User.findById(req.user.id) //deletes comparison user.posts.pull(postId) await user.save() res.status(200).json({message: 'Post Deleted!'}) } catch(err){ if (err.status){ err.statusCode = 500; } next(err); } } const clearImage = filePath => { filePath = path.join(__dirname, '..', filePath); //delete function fs.unlink(filePath, err => console.log(err)); }<file_sep>/app.js const express = require('express'); const bodyParser = require('body-parser'); const feedRoutes = require('./routes/feed'); const authRoutes = require('./routes/auth'); const path = require('path'); //database instructions 1, mongoose require, 2. mongoose connect downbelow //then make the model.... see model post const mongoose = require('mongoose'); //file upload multer.. const multer = require('multer'); const { v4: uuidv4 } = require('uuid'); const fileStorage = multer.diskStorage({ //destination of where files should be saved destination: function(req, file, cb) { cb(null, 'images'); }, //naming function filename: function(req, file, cb) { //callback, null as error, then filename cb(null, uuidv4()) } }); const fileFilter = (req, file, cb) => { //if file type is one of these if(file.mimetype === 'image/png' || file.mimetype === 'image/jpg' || file.mimetype === 'image/jpeg' ) { //if file is correct cb(null, true); } else { cb(null, false); } }; //start app with express functiion const app = express(); //initial body parser, parases incoming requests app.use(bodyParser.json()); //app/json //more multer for file image.... filestorage and filter set up above app.use( multer({ storage: fileStorage, fileFilter: fileFilter}).single('image') ); //image stuff, path.join allows to make the path to this folder and images adds that app.use('/images', express.static(path.join(__dirname, 'images'))); //middleware that stops CORS error (sharing info from server and browser) app.use((req, res, next) => { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', '*'); next(); }); app.use('/feed', feedRoutes); app.use('/auth', authRoutes); //error middleware app.use((error, req, res, next) => { console.log(error); const status = error.statusCode || 500; const message = error.message; const data = error.data; res.status(status).json({ message: message, data:data}); }); //2 conect to server mongoose.connect( 'mongodb+srv://Sealyoulater:Okayiguess!<EMAIL>/messages') .then(result =>{ //socket stuff: have to make server const and p[ass to io] const server = app.listen(8080); const io = require('./socket').init(server, { cors: { origin: "http://localhost:3000", methods: ["GET", "POST"] } }); io.on('connection', socket => { console.log('Client connected') }); }) .catch(err => console.log(err)); //listen to incoming requests
e67c7c35ab90466521e0372da9ab904133446876
[ "JavaScript" ]
2
JavaScript
MCSeal/Rest
2fe6b3f51c7930b5c5674032a647c17663d04f71
b6be34a085b701e2a4cf30aa5e54ea344a37785a
refs/heads/master
<file_sep>import React, { Component } from 'react'; import axios from 'axios'; export default class EmployeeTask extends Component { constructor() { super(); this.handleFormSubmit = this.handleFormSubmit.bind(this); this.state = { issue: [], user: [], spareparts: [], quantity: 1, damageSparepart: [], total: 0 }; } handleSparepartState() { let sparepart = localStorage.getItem('spareparts'); if (sparepart) { sparepart = JSON.parse(localStorage.getItem('spareparts')); let total = 0; sparepart.forEach((value) => { total += value.subTotal; }); this.setState({ damageSparepart: sparepart, total }); } } componentDidMount() { this.isAssigned(); this.handlePreviousData(); } handlePreviousData() { axios .get('/sparepart') .then((res) => { this.setState({ spareparts: res.data }); }) .catch((err) => console.log(err)); } handleAddSparepart(sparepart) { let lastSpareparts = JSON.parse(localStorage.getItem('spareparts')) || []; let currentId = sparepart._id; let isMatch = lastSpareparts.find(({ _id }) => _id === currentId); if (isMatch) { isMatch['quantity'] += parseInt(this.state.quantity); isMatch['subTotal'] += sparepart.price * parseInt(this.state.quantity); } else { let newSparepart = { image: sparepart.image, _id: sparepart._id, title: sparepart.title, price: sparepart.price, description: sparepart.description, quantity: parseInt(this.state.quantity), subTotal: sparepart.price * parseInt(this.state.quantity) }; lastSpareparts.push(newSparepart); } localStorage.setItem('spareparts', JSON.stringify(lastSpareparts)); } handleFormSubmit(e) { e.preventDefault(); let issueId = JSON.parse(localStorage.getItem('assignedTaskId')); console.log(this.state.total); axios .put('/issue/sparepart/' + issueId, { status: 'Resolved', damages: this.state.damageSparepart, total: this.state.total }) .then((res) => { alert('Congratulation you have completed the task!'); window.location.assign('/user-issues'); }) .catch((err) => console.log(err)); } isAssigned() { let assignedTaskId = localStorage.getItem('assignedTaskId'); if (assignedTaskId) { assignedTaskId = JSON.parse(assignedTaskId); axios .get('/issue/' + assignedTaskId) .then((res) => { this.setState({ issue: res.data }); console.log(this.state.issue); axios .get('/user/' + res.data.userId) .then((userResponse) => { this.setState({ user: userResponse.data }); console.log(this.state.user); }) .catch((err) => console.log(err)); }) .catch((err) => console.log(err)); } else { alert('Please choose task first!'); window.location.assign('/user-issues'); } } render() { return ( <div className='container'> <div className='row'> <div className='col-md-2'> <br /> <img src={`${process.env.PUBLIC_URL}/uploads/users/${this.state.user.image}`} className='img-thumbnail rounded-top' alt='user thumbnail' /> </div> <div className='col-md-4'> <div className='col-md-12 text-center'> <h5>Issue Details</h5> </div> <div className='row'> <div className='col-md-6'>Name:</div> <div className='col-md-6'>{`${this.state.issue.firstName} ${this.state.issue.lastName}`}</div> </div> <div className='row'> <div className='col-md-6'>Email:</div> <div className='col-md-6'>{this.state.issue.email}</div> </div> {this.state.user.phoneNumber && ( <div className='row'> <div className='col-md-6'>Phone:</div> <div className='col-md-6'>{this.state.user.phoneNumber}</div> </div> )} <div className='row'> <div className='col-md-6'>Address:</div> <div className='col-md-6'>{`${this.state.issue.address}, ${this.state.issue.country}`}</div> </div> <div className='row'> <div className='col-md-6'>Zip Code:</div> <div className='col-md-6'>{this.state.issue.zip}</div> </div> <div className='row'> <div className='col-md-6'>Description:</div> <div className='col-md-6'>{this.state.issue.description}</div> </div> <div className='row'> <div className='col-md-6'>Payment Method:</div> <div className='col-md-6'>{this.state.issue.paymentMethod}</div> </div> </div> <div className='col-md-6'> <h5 className='text-center'>Added Spareparts</h5> <div className='row'> <div className='col-md-3'>Title</div> <div className='col-md-3'>Quantity</div> <div className='col-md-3'>Price</div> <div className='col-md-3'>Sub Total</div> </div> {this.state.damageSparepart.map((sparepart) => { return ( <div className='row' key={sparepart._id}> <div className='col-md-3'>{sparepart.title}</div> <div className='col-md-3'>{sparepart.quantity}</div> <div className='col-md-3'>{sparepart.price}</div> <div className='col-md-3'>{sparepart.subTotal}</div> </div> ); })} <hr className='bg-info' /> <div className='row text-center'> <div className='col-md-6'>Total:</div> <div className='col-md-6'>{this.state.total}</div> </div> <form onSubmit={this.handleFormSubmit} className='d-inline'> <button className='btn btn-outline-primary btn-block'>Confirm Changes</button> </form> </div> </div> <div className='row'> <div className='col col-md-12 text-center'> <h4>Add Sparepart for the Damages</h4> </div> <button className='btn btn-outline-danger btn-block' onClick={() => { window.location.assign('/employee-task'); localStorage.removeItem('spareparts'); }} > Clear Selected Spareparts </button> <table className='table table-striped table-inverse'> <thead className='thead-inverse text-center'> <tr> <th>Sparepart</th> <th>Brand</th> <th>Description</th> <th>Image</th> <th>Price</th> <th>Available quantity</th> <th>Action</th> </tr> </thead> <tbody> {this.state.spareparts.map((sparepart) => { return ( <tr key={sparepart._id}> <td>{sparepart.title}</td> <td>{sparepart.brand}</td> <td>{sparepart.description}</td> <td className='text-center'> <img style={{ width: '100px', height: '100px' }} src={`${process.env.PUBLIC_URL}/uploads/spareparts/${sparepart.image}`} alt='sparepart hehe' /> </td> <td className='text-center'>{sparepart.price}</td> <td className='text-center'>{sparepart.quantity}</td> <td> <button className='btn btn-outline-primary' onClick={() => { this.handleAddSparepart(sparepart); this.handleSparepartState(); }} > Add </button> </td> </tr> ); })} </tbody> </table> </div> </div> ); } } <file_sep>import React, { Component } from 'react'; import Appointment from '../components/Appointment'; export default class Index extends Component { constructor() { super(); this.handleModalStatus = this.handleModalStatus.bind(this); this.state = { modalStatus: false, _id: '' }; } handleModalStatus() { this.setState(() => ({ modalStatus: !this.state.modalStatus })); } render() { return ( <div className='jumbotron animated bounce infinite'> <h1 className='display-3'>We are here to assist you</h1> <p className='lead'>This site created by <NAME></p> <hr className='my-2' /> <button disabled={!localStorage.getItem('_id')} onClick={this.handleModalStatus} className='btn btn-outline-primary' > Make an appointment </button> <Appointment modalStatus={this.state.modalStatus} handleModalStatus={this.handleModalStatus} /> </div> ); } } <file_sep>import React, { Component, Fragment } from 'react'; import axios from 'axios'; import PaymentForm from '../components/PaymentForm'; export default class IssueList extends Component { constructor() { super(); this.handleModalStatus = this.handleModalStatus.bind(this); this.handleAssignedEmployee = this.handleAssignedEmployee.bind(this); this.getTotal = this.getTotal.bind(this); this.state = { userId: '', issues: [], employee: '', modalStatus: false }; } componentDidMount() { this.handleUserIssues(); } handleModalStatus() { this.setState({ modalStatus: !this.state.modalStatus }); } handleUserIssues() { let _id = localStorage.getItem('_id'); if (_id) { _id = JSON.parse(_id); axios.get('/issue/user/' + _id).then((res) => { this.setState({ issues: res.data }); }); } } handleAssignedEmployee(id) { axios .get('/user/' + id) .then((res) => { alert(`Assigned Employee named ${res.data.firstName} ${res.data.firstName}`); }) .catch((err) => console.log(err)); } getTotal(res) { let total = 0; res.damages.forEach((subTotal) => { total += subTotal.price; }); return <span>{total}</span>; } isPaid(res) { if (res.status === 'Unresolved' && res.damages < 0) { return ( <td> <span className='text-danger'>Unresolved</span> </td> ); } else if (res.damages > 0 && res.status === 'Resolved') { return ( <td className='text-center'> <button className='btn btn-outline-warning' onClick={() => this.handleModalStatus()}> Pay Now </button> </td> ); } else if (res.status === 'Resolved' && res.image > 0) { return ( <td className='text-center'> <span className='text-danger'>Already Paid</span> </td> ); } else { return ( <td className='text-center'> <span className='text-danger'>F</span> </td> ); } } render() { return ( <Fragment> <div className='container'> <table className='table table-hover table-inverse'> <thead className='thead-inverse text-center'> <tr> <th>#</th> <th>Description</th> <th>Address</th> <th>Country</th> <th>Zip</th> <th>Assigned Employee</th> <th>List of Damages</th> <th>Status</th> </tr> </thead> <tbody> {this.state.issues.map((res) => { return ( <tr key={res._id}> <td>{res._id.substring(0, 5)}</td> <td>{res.description}</td> <td>{res.address}</td> <td>{res.country}</td> <td>{res.zip}</td> <td className='text-center'> <button disabled={!res.assignedEmployeeId} className='btn btn-outline-primary' onClick={() => this.handleAssignedEmployee(res.assignedEmployeeId)} > Reveal </button> </td> <td> <ul> {res.damages.map((data) => { return ( <li key={data._id}> {data.title} ${data.price} ${data.quantity} </li> ); })} </ul> <hr /> <div className='col-md-12'> <div className='row text-center'> <div className='col-md-4'>Total</div> <div className='col-md-8'>{this.getTotal(res)}</div> </div> </div> </td> <td className='text-center'> <button onClick={this.handleModalStatus} className='btn btn-outline-warning' disabled={res.damages <= 0 || res.status === 'Have Paid'} > {res.damages <= 0 ? <span className='text-danger'>Unresolved</span> : <span>Pay Now</span>} </button> </td> <PaymentForm modalStatus={this.state.modalStatus} handleModalStatus={this.handleModalStatus} _id={res._id} /> </tr> ); })} </tbody> </table> </div> </Fragment> ); } } <file_sep>import React, { Component } from 'react'; import axios from 'axios'; import Modal from 'react-modal'; export default class Appointment extends Component { constructor(props) { super(props); this.handleFormData = this.handleFormData.bind(this); this.handleChange = this.handleChange.bind(this); this.isLogged = this.isLogged.bind(this); this.state = { userId: '', firstName: '', lastName: '', description: '', email: '', address: '', country: '', zip: 0, paymentMethod: 'Manual payment', cardName: '', cardNumber: 0, cvv: '', status: 'Unresolved' }; } componentDidMount() { this.isLogged(); } isLogged() { let _id = localStorage.getItem('_id'); if (_id) { _id = JSON.parse(_id); this.setState(() => ({ userId: _id })); axios .get('/user/' + _id) .then((res) => this.setState(() => ({ firstName: res.data.firstName, lastName: res.data.lastName, email: res.data.email, address: res.data.address, country: res.data.country, zip: res.data.zip })) ) .catch((err) => console.log(err)); } } handleChange(e) { this.setState({ [e.target.name]: e.target.value }); } handleFormData(e) { e.preventDefault(); axios .post('/issue', { userId: this.state.userId, firstName: this.state.firstName, lastName: this.state.lastName, description: this.state.description, email: this.state.email, address: this.state.address, country: this.state.country, zip: this.state.zip, paymentMethod: this.state.paymentMethod, cardName: this.state.cardName, cardNumber: this.state.cardNumber, cvv: this.state.cvv, status: this.state.status }) .then((res) => { alert('Your issue has saved successfully'); window.location.assign('/'); }) .catch((err) => console.log(err)); } render() { return ( <Modal ariaHideApp={false} isOpen={this.props.modalStatus} onRequestClose={this.props.handleModalStatus}> <main className='page-content'> <section className='section-60 section-sm-bottom-90'> <div className='shell'> <div className='range'> <div className='cell-xs-12 text-center'> <h2>Make an Appointment</h2> <hr className='bg-primary' /> </div> <div> <div className=''> <form onSubmit={this.handleFormData} data-form-output='form-output-global' data-form-type='order' className='rd-mailform' > <div className='range'> <div className='cell-sm-6'> <div className='form-group'> <label htmlFor='appointment-name' className='form-label-outside'> First Name </label> <input id='appointment-name' type='text' name='firstName' value={this.state.firstName} onChange={this.handleChange} data-constraints='@Required' className='form-control' /> </div> </div> <div className='cell-sm-6'> <div className='form-group'> <label htmlFor='appointment-name' className='form-label-outside'> Last Name </label> <input id='appointment-name' type='text' name='lastName' value={this.state.lastName} onChange={this.handleChange} data-constraints='@Required' className='form-control' /> </div> </div> <div className='cell-sm-12 offset-top-18 offset-sm-top-0'> <div className='form-group'> <label htmlFor='appointment-email' className='form-label-outside'> E-mail </label> <input id='appointment-email' type='email' name='email' value={this.state.email} onChange={this.handleChange} data-constraints='@Email @Required' className='form-control' /> </div> </div> <div className='cell-sm-6'> <div className='form-group'> <label htmlFor='appointment-name' className='form-label-outside'> Address </label> <input id='appointment-name' type='text' name='address' value={this.state.address} onChange={this.handleChange} data-constraints='@Required' className='form-control' /> </div> </div> <div className='cell-sm-6'> <div className='form-group'> <label htmlFor='appointment-name' className='form-label-outside'> Country </label> <input id='appointment-name' type='text' name='country' value={this.state.country} onChange={this.handleChange} data-constraints='@Required' className='form-control' /> </div> </div> <div className='cell-xs-12 offset-top-18'> <div className='form-group'> <label htmlFor='appointment-message' className='form-label-outside'> Issue Description </label> <textarea id='appointment-message' name='description' value={this.state.description} onChange={this.handleChange} data-constraints='@Required' className='form-control' /> </div> </div> <div className='cell-sm-4'> <div className='form-group'> <label htmlFor='appointment-name' className='form-label-outside'> Zip </label> <input id='appointment-name' name='zip' value={this.state.zip} onChange={this.handleChange} data-constraints='@Required' className='form-control' /> </div> </div> <div className='cell-sm-4'> <div className='form-group'> <label htmlFor='appointment-name' className='form-label-outside'> Payment Method </label> <div className='d-block my-4'> <div className='custom-control custom-radio'> <input id='credit' name='paymentMethod' type='radio' onChange={this.handleChange} value='Manual payment' className='custom-control-input' defaultChecked /> <label className='custom-control-label' htmlFor='credit'> Manual payment </label> </div> <div className='custom-control custom-radio'> <input id='debit' name='paymentMethod' type='radio' onChange={this.handleChange} value='Credit card' className='custom-control-input' /> <label className='custom-control-label' htmlFor='debit'> Credit card </label> </div> <div className='custom-control custom-radio'> <input id='paypal' name='paymentMethod' type='radio' onChange={this.handleChange} value='PayPal' className='custom-control-input' /> <label className='custom-control-label' htmlFor='paypal'> PayPal </label> </div> </div> </div> </div> <div className='cell-sm-4'> <div className='form-group'> <label htmlFor='appointment-name' className='form-label-outside'> CVV </label> <input disabled={this.state.paymentMethod === 'Manual payment'} id='appointment-name' name='cvv' value={this.state.cvv} onChange={this.handleChange} data-constraints='@Required' className='form-control' /> </div> </div> <div className='cell-sm-6'> <div className='form-group'> <label htmlFor='appointment-name' className='form-label-outside'> Card Name </label> <input disabled={this.state.paymentMethod === 'Manual payment'} id='appointment-name' name='cardName' value={this.state.cardName} onChange={this.handleChange} data-constraints='@Required' className='form-control' /> </div> </div> <div className='cell-sm-6'> <div className='form-group'> <label htmlFor='appointment-name' className='form-label-outside'> Card Number </label> <input disabled={this.state.paymentMethod === 'Manual payment'} id='appointment-name' name='cardNumber' value={this.state.cardNumber} onChange={this.handleChange} data-constraints='@Required' className='form-control' /> </div> </div> <div className='d-flex justify-content-center'> <div className='col'> <button type='submit' className='btn btn-primary btn-block'> Make an appointment </button> </div> <div className='col'> <button type='button' className='btn btn-outline-danger btn-block' onClick={this.props.handleModalStatus}> Close </button> </div> </div> </div> </form> </div> </div> </div> </div> </section> </main> </Modal> ); } } <file_sep>import React from 'react'; import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; import Index from './client/Index'; import Login from './client/Login'; import UserRegister from './client/UserRegister'; import EmployeeRegister from './client/EmployeeRegister'; import Profile from './client/Profile'; import IssueList from './client/IssueList'; // ──────────────────────────────────────────────────────────────────────────────── import Dashboard from './delta/Dashboard'; import EmployeeAcceptance from './delta/EmployeeAcceptance'; import UserIssues from './delta/UserIssues'; import EmployeeTask from './delta/EmployeeTask'; import Sparepart from './delta/Sparepart'; // // ─── COMPONENTS ───────────────────────────────────────────────────────────────── import Navbar from './components/Navbar'; function App() { return ( <Router> <Navbar /> <Switch> <Route exact path='/' component={Index} /> <Route exact path='/login' component={Login} /> <Route exact path='/register' component={UserRegister} /> <Route exact path='/register-employee' component={EmployeeRegister} /> <Route exact path='/issue-list' component={IssueList} /> <Route exact path='/dashboard' component={Dashboard} /> <Route exact path='/sparepart' component={Sparepart} /> <Route exact path='/employee-acceptance' component={EmployeeAcceptance} /> <Route exact path='/user-issues' component={UserIssues} /> <Route exact path='/employee-task' component={EmployeeTask} /> <Route exact path='/profile' component={Profile} /> </Switch> </Router> ); } export default App; <file_sep># KryptoForce Online Services > Kryptoforce is an online service using MERN stack, we are building reliable specimens and ensure your maximum convenience in to our effort. ## Table of contents * [General info](#general-info) * [Screenshots](#screenshots) * [Front-End Technologies](#frontEndTechnologies) * [Back-End Technologies](#backEndTechnologies) * [Setup](#setup) * [Features](#features) * [Status](#status) * [Contact](#contact) * [Contributing](#contributing) ## General info This project is for additional purposes only, feel free to fork our project and modify into your own ## Screenshots ![Dashboard Preview](https://user-images.githubusercontent.com/58504115/78089880-d15c7a00-73f2-11ea-8bae-5429f684f302.png) ## Back-End Technologies * Express - version 4.17.1 * Mongoose - version 5.9.6 * Multer - version 1.4.2 ## Front-End Technologies * Bootstrap - version 4.17.1 * React Modal - version 5.9.6 * React- version 1.4.2 ## Setup 1. Make sure you already install MongoDB and Node technologies for more information please go to [here](https://www.learn2crack.com/2014/04/setup-node-js-and-mongodb.html) 2. Clone this project and put it in your folder. 3. change directory `cd` into your folder 4. type `npm run dev` for running both (server side + client side) 5. lock and load :sunglasses: ## Scripts for running server : `npm run nodemon` for running client : - navigate to client first - then type `npm start` to your terminal ## Features List of features ready and TODOs for future development * User appointment system To-do list: * Admin visual data analysis * Source code refactor * Switch login statement (currently using if statement) * Toast popup * Employee asigned task * Appointment bug handling (Require profile setup) ## Status Project is: ```diff ! in progress ``` ## Contact Created by [<NAME>](https://instagram/dummy) - feel free to contact me! ## Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate. ## License [MIT](https://choosealicense.com/licenses/mit/) <file_sep>import React, { Component } from 'react'; import axios from 'axios'; import Modal from 'react-modal'; export default class PaymentForm extends Component { constructor(props) { super(props); this.handleFileChange = this.handleFileChange.bind(this); this.handleFormSubmit = this.handleFormSubmit.bind(this); this.state = { image: null }; } handleFileChange(e) { this.setState({ image: e.target.files[0] }); } handleFormSubmit(e) { e.preventDefault(); const config = { headers: { 'content-type': 'multipart/form-data' } }; let formData = new FormData(); formData.append('image', this.state.image); formData.append('status', 'Have Paid'); axios .put('/issue/payment/' + this.props._id, formData, config) .then((res) => { console.log(res); alert('Your proof has been sent successfully!'); window.location.assign('/issue-list'); }) .catch((err) => console.log(err)); } render() { const customStyles = { content: { top: '50%', left: '50%', right: 'auto', bottom: 'auto', marginRight: '-50%', transform: 'translate(-50%, -50%)' } }; return ( <Modal style={customStyles} ariaHideApp={false} isOpen={this.props.modalStatus} onRequestClose={this.props.handleModalStatus} > <form onSubmit={this.handleFormSubmit}> <div className='form-group'> <label htmlFor='image'>Please Select Proof Image</label> <input onChange={this.handleFileChange} type='file' className='form-control-file' name='image' id='image' /> <div className='form-check'> <label className='form-check-label'> <input type='checkbox' className='form-check-input' value='checkedValue' required /> Confirm Payment </label> </div> </div> <button type='submit' className='btn btn-primary btn-block'> Submit </button> </form> </Modal> ); } } <file_sep>import React, { Fragment } from 'react'; const UserTable = (props) => { return ( <Fragment> <div className='card-body'> <div className='table-responsive'> <table className='table table-bordered' id='dataTable' width='100%' cellSpacing={0}> <tbody> <div className='card mb-3'> <div className='card-header'> <i className='fa fa-table' /> User Data Table </div> <div className='card-body'> <div className='table-responsive'> <table className='table table-bordered' id='dataTable' width='100%' cellSpacing={0}> <thead> <tr> <th>Name</th> <th>Email</th> <th>Role</th> <th>Age</th> <th>Phone Number</th> <th>Status</th> </tr> </thead> <tbody> {props.users.map((data) => { return ( <tr key={data._id}> <td>{data.username}</td> <td>{data.email}</td> <td>{data.role}</td> <td>{data.age ? <span>{data.age}</span> : <span className='text-danger'>Unknown</span>}</td> <td> {data.phoneNumber ? <span>{data.phoneNumber}</span> : <span className='text-danger'>Unknown</span>} </td> {data.status === 'Inactive' && ( <td> <span className='text-warning'>Inactive</span> </td> )} {data.status === 'Active' && ( <td> <span className='text-success'>Active</span> </td> )} {(data.status === 'User' || data.status === 'Admin') && ( <td> <span>{data.status}</span> </td> )} </tr> ); })} </tbody> </table> </div> </div> <div className='card-footer small text-muted'>Updated yesterday at 11:59 PM</div> </div> </tbody> </table> </div> </div> </Fragment> ); }; export default UserTable; <file_sep>import React, { Component, Fragment } from 'react'; import AddSparepartForm from '../components/AddSparepartForm'; import UpdateSparepartForm from '../components/UpdateSparepartForm'; import axios from 'axios'; export default class Sparepart extends Component { constructor() { super(); this.handleModalStatus = this.handleModalStatus.bind(this); this.handleSpareparts = this.handleSpareparts.bind(this); this.handleUpdateModalStatus = this.handleUpdateModalStatus.bind(this); this.state = { modalStatus: false, updateModalStatus: false, spareparts: [], updateDataId: '' }; } componentDidMount() { this.handleSpareparts(); } handleModalStatus() { this.setState({ modalStatus: !this.state.modalStatus }); } handleUpdateModalStatus(_id) { this.setState({ updateModalStatus: !this.state.updateModalStatus, updateDataId: _id }); } handleSpareparts() { axios .get('/sparepart') .then((res) => { this.setState({ spareparts: res.data }); }) .catch((err) => console.log(err)); } handleDeleteSparepart(_id) { axios .delete('/sparepart/' + _id) .then((res) => { window.location.assign('/sparepart'); }) .catch((err) => console.error(err)); } render() { return ( <Fragment> <button className='btn btn-outline-info btn-block' onClick={this.handleModalStatus}> Add New Sparepart </button> <table className='table table-striped table-inverse'> <thead className='thead-inverse'> <tr> <th>#</th> <th>Title</th> <th>Brand</th> <th>Price</th> <th>Description</th> <th>Quantity</th> <th>Image</th> <th>Action</th> </tr> </thead> <tbody> {this.state.spareparts.map((sparepart) => { return ( <tr key={sparepart._id}> <td>{sparepart._id.substring(0, 7)}</td> <td>{sparepart.title}</td> <td>{sparepart.brand}</td> <td>$ {sparepart.price}</td> <td>{sparepart.description}</td> <td>{sparepart.quantity}</td> <td> <img style={{ width: '50px', height: '50px' }} src={`${process.env.PUBLIC_URL}/uploads/spareparts/${sparepart.image}`} alt={`${sparepart._id} preview`} /> </td> <td> <button className='btn btn-outline-primary' onClick={() => this.handleUpdateModalStatus(sparepart._id)}> Edit </button> <button className='btn btn-outline-danger' onClick={() => this.handleDeleteSparepart(sparepart._id)}> Delete </button> </td> </tr> ); })} </tbody> </table> <AddSparepartForm modalStatus={this.state.modalStatus} handleModalStatus={this.handleModalStatus} /> <UpdateSparepartForm _id={this.state.updateDataId} updateModalStatus={this.state.updateModalStatus} handleUpdateModalStatus={this.handleUpdateModalStatus} /> </Fragment> ); } }
5c453b3b21f0911e9372a79df3ae5e72cd23b91e
[ "JavaScript", "Markdown" ]
9
JavaScript
tester-make/kryptonforce-service-online
9401518e6af52a5885ab55842144866b5936665f
364cb426fc2d13103d2e92d2934100f60ebd1979
refs/heads/master
<file_sep>import nltk from nltk.collocations import * from nltk.metrics import BigramAssocMeasures import operator import string import math measures = BigramAssocMeasures() l_ru = [] with open("text_ru.txt", 'r', encoding="utf-8") as f: for line in f: for w in nltk.word_tokenize(line.lower()): if w not in string.punctuation: l_ru.append(w) l_en = [] with open("text_en.txt", 'r', encoding="utf-8") as f: for line in f: for w in nltk.word_tokenize(line.lower()): if w not in string.punctuation: l_en.append(w) freq_ru = nltk.FreqDist(l_ru) sort_fr_ru = freq_ru.most_common() finder_ru = BigramCollocationFinder.from_words(l_ru) t_ru = finder_ru.nbest(measures.student_t, 100) freq_en = nltk.FreqDist(l_en) sort_fr_en = freq_en.most_common() finder_en = BigramCollocationFinder.from_words(l_en) t_en = finder_en.nbest(measures.student_t, 100) with open("collocations_ru.csv", 'w', encoding="utf-8") as coll: for i in t_ru: coll.write("{}; {}; {}\n".format("t", i[0]+" "+i[1], round(finder_ru.score_ngram(measures.student_t, i[0], i[1]),2))) for m in t_ru: coll.write("{}; {}; {}\n".format("chi^2", m[0]+" "+m[1], round(finder_ru.score_ngram(measures.chi_sq, m[0], m[1]),2))) for n in t_ru: coll.write("{}; {}; {}\n".format("log-likelihood", n[0]+" "+n[1], round(finder_ru.score_ngram(measures.likelihood_ratio, n[0], n[1]),2))) for q in t_ru: coll.write("{}; {}; {}\n".format("pmi", q[0]+" "+q[1], round(finder_ru.score_ngram(measures.pmi, q[0], q[1]),2))) with open("collocations_en.csv", 'w', encoding="utf-8") as coll: for i in t_en: coll.write("{}; {}; {}\n".format("t", i[0]+" "+i[1], round(finder_en.score_ngram(measures.student_t, i[0], i[1]),2))) for m in t_en: coll.write("{}; {}; {}\n".format("chi^2", m[0]+" "+m[1], round(finder_en.score_ngram(measures.chi_sq, m[0], m[1]),2))) for n in t_en: coll.write("{}; {}; {}\n".format("log-likelihood", n[0]+" "+n[1], round(finder_en.score_ngram(measures.likelihood_ratio, n[0], n[1]),2))) for q in t_en: coll.write("{}; {}; {}\n".format("pmi", q[0]+" "+q[1], round(finder_en.score_ngram(measures.pmi, q[0], q[1]),2)))
19c615ea43371444585cf2c2f72c71b503df91e5
[ "Python" ]
1
Python
frodion/SPIVT
a633445895aa8ce547441a84e9cff43049fa0b9b
9dd53a96f9891e0a4e29e24c7b4fa0cb4e186bbd
refs/heads/master
<file_sep>package com.aptitude.aptigame.AptiGame; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AptiGameApplication { private final static Logger log = LoggerFactory.getLogger(AptiGameApplication.class); public static void main(String[] args) { log.info("Booting up the application"); SpringApplication.run(AptiGameApplication.class, args); } } <file_sep>package com.aptitude.aptigame.AptiGame.controller; import com.aptitude.aptigame.AptiGame.model.SavedUser; import com.aptitude.aptigame.AptiGame.model.User; import com.aptitude.aptigame.AptiGame.service.UserService; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.tomcat.util.codec.binary.Base64; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; @RestController @Controller public class LoginController { private static Map<String, SavedUser> database = new HashMap<>(); @Autowired private UserService userService; @RequestMapping({"/", "/login"}) public ModelAndView login() { return new ModelAndView("login/login"); } @RequestMapping(value = "/login", method = RequestMethod.POST) @ResponseBody public ModelAndView getLogin( @RequestParam(value = "userEmail", required = true) String userEmail, @RequestParam(value = "password", required = true) String password, HttpServletRequest request) { byte[] messageBytes = password.getBytes(StandardCharsets.UTF_8); String secretKey = Base64.encodeBase64String(messageBytes); User user = userService.findByUserEmailAndSecretKey(userEmail, password); ModelAndView modelAndView = new ModelAndView(); if (user != null) { modelAndView.setViewName("index"); modelAndView.addObject("username", user.getUserName()); } else { modelAndView.setViewName("login/login"); modelAndView.addObject("showWarningMessage", true); modelAndView.addObject("warn_message", "Incorrect useremail / Password. Please try again with correct credentials"); } return modelAndView; } @RequestMapping(value = "/signUp", method = RequestMethod.POST) @ResponseBody public ModelAndView signUp( @RequestParam(value = "userEmail", required = true) String userEmail, @RequestParam(value = "username", required = true) String username, @RequestParam(value = "password", required = true) String password, @RequestParam(value = "firstName", required = true) String firstName, @RequestParam(value = "lastName", required = true) String lastName, HttpServletRequest request) { byte[] messageBytes = password.getBytes(StandardCharsets.UTF_8); String secretKey = Base64.encodeBase64String(messageBytes); User createdUser = userService.createUser( User.builder().userEmail(userEmail).firstName(firstName).lastName(lastName) .userName(username).secretKey(secretKey).build()); if (createdUser == null) { ModelAndView modelAndView = new ModelAndView("login/login"); modelAndView.addObject("showWarningMessage", true); modelAndView.addObject("warn_message", "User already Exists.Please choose another emailId Or Login with sameone"); return modelAndView; } else { ModelAndView modelAndView = new ModelAndView("/index"); modelAndView.addObject("username", createdUser.getUserName()); return modelAndView; } } @ResponseBody @RequestMapping("/test") public ModelAndView test() { ModelAndView modelAndView = new ModelAndView("test"); modelAndView.addObject("username", "aryan"); return modelAndView; } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.aptigame</groupId> <artifactId>AptiGame</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>AptiGame</name> <description>Demo project for Spring Boot for Aptitude Game Application</description> <!--Required for spring boot to run--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <start-class>com.aptitude.aptigame.AptiGame.AptiGameApplication</start-class> <java.version>1.8</java.version> </properties> <dependencies> <!-- Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--For Spring Rest Application--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!-- Tomcat Embed --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <!--For JSP --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> </dependency> <!-- To compile JSP files --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <!-- JSTL --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--Test --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.4</version> <scope>provided</scope> </dependency> <!--Dev Tools to Automatically build from intellij--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <!--Spring Data JPA--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!--PostGreSql--> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency> </dependencies> <build> <!--to run using ./mvnw , default goal is required--> <defaultGoal>spring-boot:run</defaultGoal> <finalName>${project.artifactId}</finalName> <pluginManagement> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <!--Plugin for Heroku to Run using war--> <!--war command to run is : mvn clean heroku:deploy-war and packaging should be war--> <plugin> <groupId>com.heroku.sdk</groupId> <artifactId>heroku-maven-plugin</artifactId> <version>2.0.6</version> <configuration> <processTypes> <web>java $JAVA_OPTS -cp target/classes:target/dependency/* AptiGameApplication</web> <executable>true</executable> <arguments> <argument>--spring.profiles.active=heroku</argument> </arguments> </processTypes> </configuration> </plugin> </plugins> </pluginManagement> </build> </project> <file_sep>package com.aptitude.aptigame.AptiGame.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Entity // This annotation allows entity manager to use this class and puts it in context. @Table(name = "customer") // associates a class with a table in the database. @Data @Builder @NoArgsConstructor @AllArgsConstructor public class User implements Serializable { private static final long serialVersionUID = -3009157732242241606L; @Column(name = "user_name") private String userName; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; @Id //says that this field is the primary key. @Column(name = "user_email") // @GeneratedValue(strategy = GenerationType.IDENTITY) // Defines the strategy for generating the primary key private String userEmail; @Column(name = "secret_key") private String secretKey; // secret key for auth and password for db sign ups. } <file_sep># aptiDemo Aptitude Game in Spring MVC architecture Deployed on Heroku. Can be seen here : https://aptiq.herokuapp.com/ Clone repo and Configure heroku. Send war to heroku using : mvn clean heroku:deploy-war it will run on your app <file_sep>$(document).ready(function() { function showAlert(message,type){ var alertElement = "#" + type + "-alert"; var alertMessageElement = "#" + type + "_message"; $(alertMessageElement).html(message); $(alertElement).fadeTo(10000, 500).slideUp(500, function() { $(alertElement).slideUp(500); }); } $('.deleteUser').bind('click', function(event) { var userEmail = this.id.replace("delete_", ""); var rowToBeDelete = $(this).parent().parent(); $.ajax({ type: "POST", url: "deleteUser", data: {"userEmail" : userEmail}, success: function(response) { if(response.success){ showAlert("Successfully Delete account with email : " + userEmail,"success"); rowToBeDelete.remove() } else { showAlert("Error Deleting account with email : " + userEmail , "warning"); } }, error: function() { showAlert("Error Deleting account with email : " + userEmail , "warning"); } }) }); });<file_sep>package com.aptitude.aptigame.AptiGame.config; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; public class AptiGameWebAppInitialiser implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(AptiGameConfiguration.class); rootContext.setServletContext(servletContext); ServletRegistration.Dynamic servlet = servletContext .addServlet("dispatcher", new DispatcherServlet(rootContext)); servlet.setLoadOnStartup(1); servlet.addMapping("/"); } } <file_sep>package com.aptitude.aptigame.AptiGame.interceptors; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Optional; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.lang.Nullable; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; @Component public class AuthenticationInterceptor implements HandlerInterceptor { private static final String aptiQCookieName = "aptiq-credentials"; private Optional<Cookie> getAptiqCookie(List<Cookie> cookies) { return cookies.stream() .filter(cookie -> aptiQCookieName.equals(cookie.getName()) && cookie.getMaxAge() < 12) .findFirst(); } private void authenticateUser(HttpServletRequest request, HttpServletResponse response) throws IOException { Optional<Cookie[]> cookies = Optional.ofNullable(request.getCookies()); Optional<Cookie> userCookie = Optional.empty(); if (cookies.isPresent()) { userCookie = getAptiqCookie(Arrays.asList(request.getCookies())); } if (!userCookie.isPresent() && !(request.getRequestURI().equals("/") || request.getRequestURI() .equals("/login"))) { response.sendRedirect("/"); } } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // authenticateUser(request, response); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { } } <file_sep>$('#attempt_login').submit(function(event) { event.preventDefault(); $.ajax({ type: "POST", url: "login", data: $(this).serialize(), success: function(response) { alert("success" + response); $("#warn-alert").fadeTo(10000, 500).slideUp(500, function(){ $("#warn-alert").slideUp(500); }); }, error: function() { alert("failure"); } }) }); $('#attempt_signUp').submit(function(event) { event.preventDefault(); $.ajax({ type: "POST", url: "signUp", data: $(this).serialize(), success: function(response) { alert("success resposne"); $("#warn-alert").fadeTo(10000, 500).slideUp(500, function(){ $("#warn-alert").slideUp(500); }); }, error: function() { $("#warn-alert").fadeTo(10000, 500).slideUp(500, function(){ $("#warn-alert").slideUp(500); }); } }) }); <file_sep>package com.aptitude.aptigame.AptiGame.database; import com.aptitude.aptigame.AptiGame.model.User; import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; public interface UserRepository<U> extends CrudRepository<User, String> { List<User> findByUserEmail(String useremail); /** * Finds a person by using the last name as a search criteria. * * @return A list of persons whose last name is an exact match with the given last name. If no * persons is found, this method returns an empty list. */ @Query(value = "select * FROM customer where user_email = ? and secret_key = ?", nativeQuery = true) public List<User> findByUserEmailAndSecretKey(String userEmail, String secretKey); } <file_sep>package com.aptitude.aptigame.AptiGame.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; @RestController @Controller public class HomeController { @RequestMapping("index") @ResponseBody public ModelAndView execute() { return new ModelAndView("index"); } // @RequestMapping({"/","login"}) // @ResponseBody // public ModelAndView login() { // return new ModelAndView("login/login"); // } @RequestMapping({"/blog"}) @ResponseBody public ModelAndView execute_blog() { return new ModelAndView("blog"); } @RequestMapping({"/about"}) @ResponseBody public ModelAndView execute_about() { return new ModelAndView("about"); } @RequestMapping({"/contact"}) @ResponseBody public ModelAndView execute_contact() { return new ModelAndView("contact"); } @RequestMapping({"proj1"}) @ResponseBody public ModelAndView execute_proj1() { return new ModelAndView("proj1"); } @RequestMapping({"projects"}) @ResponseBody public ModelAndView execute_projects() { return new ModelAndView("projects"); } @RequestMapping({"singlepost"}) @ResponseBody public ModelAndView execute_singlepost() { return new ModelAndView("singlepost"); } }
86c859565bdb83f3c103603ec86419c670c7c668
[ "Markdown", "Java", "JavaScript", "Maven POM" ]
11
Java
aryan000/springDemoProject
32ff8e33551a4eeb0db1b5db044fd623a3828a57
4d340f4ec28efd91fdddec70ac8411babf35f292
refs/heads/master
<repo_name>javgh/bridgewalker-site<file_sep>/js/onload.js $(document).ready(function() { // Configure the navigation tabs $('#content').tabs({ fxSlide: false, fxFade: true, fxSpeed: 'fast', onClick: function(newTab, content, oldTab) { if ($(newTab).hasClass('blog-redirect')){ window.location.href = '/blog'; return false; } } }); // Activate Tipsy tooltip effect //$('#buy, #phone a').tipsy({ // gravity: 's', // fade: true, // html: true, // // Text on the buy button tooltip: // fallback: "Get it on Google Play" //}); // Wrap the headers in the sidebar in span tags for styling purposes $('#sidebar h3').wrapInner('<span>'); // Form validation in the contact form $("#contactForm").validate({ errorElement: "em" }); // Form validation in the newsletter form $("#newsletter").validate({ errorElement: "em" }); // Clear every fourth screenshot to keep the layout intact $("ul.screenshots li:nth-child(3n)").addClass('last'); // Activate and configure the FancyBox lightbox plugin $(".fancybox").fancybox({ openEffect : 'elastic', closeEffect : 'elastic', helpers: { title : { type : 'inside' } } }); // FancyBox lightbox plugin for videos $(".video").fancybox({ maxWidth : 800, maxHeight : 600, fitToView : false, width : '70%', height : '70%', autoSize : false, closeClick : false, openEffect : 'none', closeEffect : 'none', padding : 10 }); });
ea62795b5a9ea157239e48f0426bf134bb1bd769
[ "JavaScript" ]
1
JavaScript
javgh/bridgewalker-site
a707aa8aefd8781a57ec072709fd2ee26f24f73a
efef42ec57d6806e4de6867d84aab1614b59d10f
refs/heads/master
<repo_name>albertolazari/CppProjCreator<file_sep>/README.md # C++ Project Creator A set of scripts and Makefiles to automate the process of creating and compiling a C++ project from either a Windows command prompt or a bash shell on GNU/Linux or macOS # Windows The Windows version provides an automated Makefile, written in cmd script commands, as well as two scripts: - setup-cpp-proj: configures a new project, with all the necessary directories and the Makefile - echolored: a simple script that allows you to print colored strings For both scripts more options are available. Use -? or --help to read the guide # Bash The Bash version also provides an automated Makefile written in bash commands, thus compatible with GNU/Linux and macOS systems, along with the \'mkproj\' script, which allows you to create the projects, with all the necessary directories and the Makefile. More options are available. Use -h or --help to read the guide <file_sep>/Bash/mkproj #!/bin/bash ########################## # Made by <NAME> # ########################## # This is a simple script to create a new C++ Project. It creates a new folder containing the folders # you will need and a Makefile that works out-of-the-box SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )" PROJ_NAME="" # Options HERE=false MAKEFILE=false NO_DIRS=false printHelp() { echo "Usage: mkproj [OPTION] PROJECT" echo "Create the C++ PROJECT, if it does not already exist." echo "" echo "Options:" echo " -h, --help display this help and exit" echo " -m, --makefile-only only create/update the Makefile" echo " --here set up the project in the current directory" echo " --no-dirs do not create src/ and include/ directories" } createDir() { if [ -e "$1" ]; then return 1 fi mkdir "$1" } setupDir() { cp "$SCRIPT_DIR"/Makefile "$1"/Makefile if [ $MAKEFILE = false ] && [ $NO_DIRS = false ]; then mkdir "$1"/{src,include} fi if [ $MAKEFILE = false ]; then cp -r "$SCRIPT_DIR"/../.vscode/ "$1"/.vscode/ fi } checkFlags() { if [ $# = 0 ] ; then return 1 fi while [ $# != 0 ] do case $1 in -h|--help) printHelp exit ;; -m|--makefile-only) MAKEFILE=true ;; --here) HERE=true ;; --no-dirs) NO_DIRS=true ;; -*) echo "mkproj: unrecognized option '$1'" echo "try 'mkproj -h' or 'mkproj --help' for more information." exit 1 ;; *) PROJ_NAME=$1 ;; esac shift done } if ! checkFlags "$@" || ( [ $HERE = false ] && [ "$PROJ_NAME" = "" ] ); then printHelp exit 1 fi if [ $HERE = false ] && ! createDir "$PROJ_NAME"; then echo "cannot create project '$PROJ_NAME': File already exists" exit 1 fi if [ $HERE = false ]; then setupDir "$PROJ_NAME" else setupDir "$PWD" fi <file_sep>/Bash/Makefile ########################## # Auto Makefile # # Made by <NAME> # ########################## # To learn how to use this Makefile just type "make help" in the root directory of your project # vvv Project and compilation parameters vvv # ############################################## # Directories containing the sources to compile (SRC) and build files (BUILD) SRC := . BUILD := build # Insert here the directories containing the header files # (Separate the paths with a space) INCLUDEPATHS := include # Insert here the path/to/executable file to build # (By default it's named after the root dir of the project and # will be placed in the (BUILD) directory) EXECUTABLE := $(BUILD)/$(shell basename "$$("pwd")") # File extensions SRCEXT := .cpp OBJEXT := .o DEPEXT := .d # Compiler to use (CXX) and its parameters CXX := g++ CXXFLAGS := -std=c++11 -Wall -Wextra -I$(INCLUDEPATHS) -g ####################################### # From now on everything is automated # ####################################### SRCTEMP := $(wildcard $(SRC)/**$(SRCEXT)) SOURCES := $(patsubst $(SRC)/%$(SRCEXT),$(SRC)/%$(SRCEXT), $(SRCTEMP)) OBJECTS := $(patsubst $(SRC)/%$(SRCEXT),$(BUILD)/%$(OBJEXT), $(SOURCES)) OBJ := $(patsubst $(BUILD)/%$(OBJEXT),%$(OBJEXT), $(OBJECTS)) DEPENDENCIES := $(patsubst $(SRC)/%$(SRCEXT),$(BUILD)/%$(DEPEXT), $(SOURCES)) # Colors: red :=  green :=  blue :=  yellow :=  end :=  # Targets: build: $(EXECUTABLE) all: $(OBJECTS) $(EXECUTABLE): $(OBJECTS) @$(CXX) $(CXXFLAGS) $(OBJECTS) -o "$(EXECUTABLE)" @echo "========== $(green)$(patsubst $(BUILD)/%,%, $(EXECUTABLE))$(end) compiled successfully ==========" run: build @echo "$(green)$(patsubst $(BUILD)/%,%, $(EXECUTABLE))$(end)>" @./$(EXECUTABLE) #linking: $(OBJECTS) # @if exist *.o if not $(OBJEXT) == ".o" $(CXX) $(CXXFLAGS) *$(OBJEXT) *.o -o $(EXECUTABLE) else \ $(CXX) $(CXXFLAGS) *.o -o $(EXECUTABLE) else \ $(CXX) $(CXXFLAGS) *$(OBJEXT) -o $(EXECUTABLE) # @echo "========== $(green)$(patsubst $(BUILD)/%,%, $(EXECUTABLE))$(end) compiled successfully ==========" # Includes dependency files in their relatives object target dependencies -include $(DEPENDENCIES) $(OBJECTS): $(BUILD)/%$(OBJEXT): $(SRC)/%$(SRCEXT) # Creates needed dirs if non-existent @test -d $(BUILD) || mkdir $(BUILD) > /dev/null @echo "building $(blue)$(patsubst $(BUILD)/%$(OBJEXT), %$(OBJEXT), $@)$(end)" @$(CXX) $(CXXFLAGS) -MMD -MF \ $(patsubst $(BUILD)/%$(OBJEXT), $(BUILD)/%$(DEPEXT), $@) -c $< -o $@ $(OBJ): %$(OBJEXT): $(BUILD)/%$(OBJEXT) clean_obj: @rm $(OBJECTS) 2> /dev/null || true clean_dep: @rm $(DEPENDENCIES) 2> /dev/null || true clean: @rm $(OBJECTS) 2> /dev/null || true @rm $(DEPENDENCIES) 2> /dev/null || true @rm "$(EXECUTABLE)" 2> /dev/null || true @echo "$(yellow)build$(end) directory cleaned" help: @echo "This $(yellow)Auto Makefile$(end) lets you compile a C++ project automatically, just type 'make' ;)" @echo "" @echo Actually, you can pass different parameters to make: @echo "" @echo "$(yellow)help$(end) shows this message" @echo "$(yellow)build$(end) compiles the project (default, gets called by only typing 'make')" @echo "$(yellow)all$(end) compiles all of the project's objects without linking them" @echo "$(yellow)linking$(end) links all of the (OBJEXT)* and .o files that are placed in the (BUILD)* directory," @echo " which means you can link the objects produced by the project (automatically," @echo " if not yet compiled) with external objects you need" @echo " *(OBJEXT) and (BUILD) are two variables you can set in the Makefile" @echo "$(yellow)run$(end) compiles and run the project" @echo "$(yellow)clean$(end) deletes each project file (dependencies, objects and the executable) placed in the" @echo " (BUILD) directory." @echo " You can also call clean_obj or clean_dep variants which only delete respectively" @echo " the objects or the dependencies" <file_sep>/Windows/Makefile ########################## # Auto Makefile # # Made by <NAME> # ########################## # To learn how to use this Makefile just type "make help" in the root dir of your project # vvv Project and compilation parameters vvv # ############################################## # Directories containing the sources to compile (SRC) and build files (BUILD) # If non-existing they will be automatically created SRC := src BUILD := build # Insert here the directories containing the header files # (Separate the paths with a space) INCLUDEPATHS := include # Insert here the path\to\.exe file to build # (By default it's named after the root dir of the project and # it will be placed in the (BUILD) directory) EXECUTABLE := $(BUILD)\$(shell for /F "delims==" %%i in ("%cd%") do echo %%~ni) # File extensions SRCEXT := .cpp OBJEXT := .obj DEPEXT := .dep # Compiler to use (CXX) and its parameters CXX := g++ CXXFLAGS := -std=c++11 -Wall -I $(INCLUDEPATHS) -g ####################################### # From now on everything is automated # ####################################### SRCTEMP := $(wildcard $(SRC)/*$(SRCEXT)) SOURCES := $(patsubst $(SRC)/%$(SRCEXT),$(SRC)\\%$(SRCEXT), $(SRCTEMP)) OBJECTS := $(patsubst $(SRC)\\%$(SRCEXT),$(BUILD)\\%$(OBJEXT), $(SOURCES)) OBJ := $(patsubst $(BUILD)\\%$(OBJEXT),%$(OBJEXT), $(OBJECTS)) DEPENDENCIES := $(patsubst $(SRC)\\%$(SRCEXT),$(BUILD)\\%$(DEPEXT), $(SOURCES)) # Colors: red :=  green :=  blue :=  yellow :=  end :=  # Targets: build: $(EXECUTABLE).exe @echo ========== $(green)$(patsubst $(BUILD)\\%,%, $(EXECUTABLE))$(end) compiled successfully ========== all: $(OBJECTS) $(EXECUTABLE).exe: $(OBJECTS) @$(CXX) $(CXXFLAGS) $(OBJECTS) -o "$(EXECUTABLE)" run: build @echo $(green)$(patsubst $(BUILD)\\%,%, $(EXECUTABLE))$(end)^> @echo. @$(EXECUTABLE) linking: $(OBJECTS) @if exist *.o if not $(OBJEXT) == ".o" $(CXX) $(CXXFLAGS) *$(OBJEXT) *.o -o $(EXECUTABLE) else \ $(CXX) $(CXXFLAGS) *.o -o $(EXECUTABLE) else \ $(CXX) $(CXXFLAGS) *$(OBJEXT) -o $(EXECUTABLE) @echo ========== $(green)$(patsubst $(BUILD)\\%,%, $(EXECUTABLE))$(end) compiled successfully ========== # Includes dependency files in their relatives object target dependencies -include $(DEPENDENCIES) $(OBJECTS): $(BUILD)\\%$(OBJEXT): $(SRC)\\%$(SRCEXT) # Creates needed dirs if non-existent @if not exist $(SRC) mkdir $(SRC) @if not exist $(BUILD) mkdir $(BUILD) @echo building $(blue)$(patsubst $(BUILD)\\%$(OBJEXT), %$(OBJEXT), $@)$(end) @$(CXX) $(CXXFLAGS) -fno-implicit-templates -MMD -MF \ $(patsubst $(BUILD)\\%$(OBJEXT), $(BUILD)\\%$(DEPEXT), $@) -c $< -o $@ $(OBJ): %$(OBJEXT): $(BUILD)\\%$(OBJEXT) clean_obj: @del 2>NUL $(OBJECTS) clean_dep: @del 2>NUL $(DEPENDENCIES) clean: @del 2>NUL $(OBJECTS) @del 2>NUL $(DEPENDENCIES) @del 2>NUL "$(EXECUTABLE).exe" @echo $(yellow)build$(end) directory cleaned help: @echo. @echo This $(yellow)Auto Makefile$(end) lets you compile a C++ project automatically, just type make ;) @echo. @echo Actually, you can pass different parameters to make: @echo. @echo $(yellow)help$(end) shows this message @echo $(yellow)build$(end) compiles the project (gets called by default, which means when you only call "make") @echo $(yellow)all$(end) compiles all of the project's objects without linking them @echo $(yellow)linking$(end) links all of the (OBJEXT)* and .o files that are placed in the (BUILD)* directory, @echo which means you can link the objects produced by the project (automatically, @echo if not yet compiled) with external objects you need @echo *(OBJEXT) and (BUILD) are two variables you can set in the Makefile @echo $(yellow)run$(end) compiles and run the project @echo $(yellow)clean$(end) deletes each project file (dependencies, objects and the executable) placed in the @echo (BUILD) directory. @echo You can also call clean_obj or clean_dep variants which only delete respectively @echo the objects or the dependencies
dac674ba94a3f9cae9f91c996fc04057aec6deb3
[ "Markdown", "Makefile", "Shell" ]
4
Markdown
albertolazari/CppProjCreator
932a07cde1611efd7f18618491b8d6df5218038e
da50d2b20f4ff1251d01f4d5a77bdfd00ed886af
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import '../assets/css/styles.css'; import 'rxjs/add/operator/switchMap'; @Component({ templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { constructor(private route: ActivatedRoute) { } ngOnInit() { const url: Observable<string> = this.route.url.map(segments => segments.join('')); url.subscribe((p) => { }); } }<file_sep>import { Component, OnInit } from '@angular/core'; import { Invoice } from './invoice'; import { Product } from './product' @Component({ selector: 'invoice-form', templateUrl: './invoice-form.component.html' }) export class InvoiceFormComponent implements OnInit { invoice = new Invoice('John', '1/1/2000', '1'); products: Product[] = [new Product('Cleaner', 100), new Product('Sweeper', 200), new Product('Shiner', 300)] filteredProducts: Product[]; lineItems: Product[] = []; product: Product; isHidden: boolean = true; ngOnInit() { } createInvoice(f: any) { this.isHidden = false; } newInvoice() { this.invoice = new Invoice('', '', ''); this.lineItems = []; this.isHidden = true; } searchProduct(v: string) { this.filteredProducts = this.products.filter(p => p.name.toLowerCase().indexOf(v) > -1); } addProduct(v: any) { if (this.lineItems.find(li => li.name === v.product.name)) return; if (!this.invoice.lineItems) { this.invoice.lineItems = this.lineItems; } v.product.qty = 1; this.lineItems.push(v.product) } removeProduct(v: any) { let i = this.lineItems.findIndex(li => li.name === v.name); this.lineItems.splice(i, 1); } displayFn(product: Product): any { return product ? product.name : product; } displayInvoice() { return JSON.stringify(this.invoice); } } <file_sep>import { Product } from './product' export class Invoice { constructor( public customerName: string, public date: string, public number: string, public lineItems?: Product[] ) { } }
3fc2f9ffd1f44e63520d9197eb3a5cb469006bfc
[ "TypeScript" ]
3
TypeScript
achristoph/invoice
2cea16a54928b2564c7b50e5e4815bc8941e5e82
92aaaead6b27c77fa85225716f49140dedf80d69
refs/heads/master
<repo_name>csmcdermott/whispersync<file_sep>/whispersync.rb #!/usr/bin/env ruby require 'rubygems' if RUBY_VERSION < '1.9.0' require 'optparse' options = {} optparse = OptionParser.new do|opts| opts.banner = 'asdf' opts.on('-s', '--source SOURCE', 'Source (file or directory).') do |source| options[:source] = source end opts.on('-d', '--destination DEST', 'Destination (file or directory).') do |dest| options[:dest] = dest end opts.on('-H', '--host HOST', 'Destination host.') do |host| options[:host] = host end options[:verbose] = false opts.on('-v', '--verbose', 'Verbose output.') do options[:verbose] = true end options[:noop] = false opts.on('-n', '--noop', 'Fake it, just print what *would* happen if it were for real.') do options[:verbose] = true end opts.on('-h', '--help', 'Display this help menu') do puts opts exit end end optparse.parse! if options[:verbose] puts "Arguments and options:" options.each do |k,v| puts " - #{k}: #{v}" end end unless options.has_key?(:source) && options.has_key?(:dest) puts "Source and destination arguments are required." exit 2 end unless File.exists?(options[:source]) puts "Source does not exist." exit 2 end source_path = '' dest_host = '' dest_path = '' dest_file = '' if /\.wsp/ =~ options[:dest] dest_path = File.dirname(options[:dest]) dest_file = File.basename(options[:dest]) else dest_path = options[:dest] end if options[:verbose] puts "dest_path: #{dest_path}" puts "dest_file: #{dest_file}" end if options[:host] dest_host = options[:host] end differences = 0 errors = 0 source_files = [] if File.file?(options[:source]) source_path = File.dirname(options[:source]) source_files << File.basename(options[:source]) else # If it's not a file, it must be a directory source_path = options[:source] Dir.chdir(options[:source]) Dir.glob('**/*.wsp') do |file| source_files << file end end if options[:verbose] puts "source_path: #{source_path}" end if options[:verbose] puts "List of source files to examine:" source_files.each do |file| puts " - #{source_path}/#{file}" end end source_files.each do |file| if options[:verbose] puts "Starting in on #{file}..." end source_cmd = "/usr/local/bin/whisper-dump.py #{source_path}/#{file}" source_output = `#{source_cmd}`.split("\n") dest_command = '/usr/local/bin/whisper-dump.py ' if dest_file == '' dest_arg = "#{dest_path}/#{file}" else dest_arg = "#{dest_path}/#{dest_file}" end dest_command = dest_command + dest_arg unless dest_host == '' dest_command = "ssh #{options[:host]} \"#{dest_command}\" 2> /dev/null" end if options[:verbose] puts " - source_cmd: #{source_cmd}" puts " - dest_command: #{dest_command}" end dest_output = `#{dest_command}`.split("\n") if source_output == dest_output puts " - no differences, proceeding to next file" next else changes = {} for c in 0..(source_output.length-1) unless source_output[c] == dest_output[c] #puts "###############" #puts source_output[c] #puts dest_output[c] #puts "###############" if /(\d+): (\d+),\s+(\S+)/ =~ source_output[c] changes[$2] = $3 end end end if options[:verbose] puts " - #{changes.length} differences found." end unless options[:noop] change_string = '' changes.each do |timestamp,value| change_string = change_string + "#{timestamp}:#{value} " if options[:verbose] puts "#{timestamp}:#{value}" end end #puts "whisper-update.py #{dest_arg} #{change_string}" end end end
a8fff11fc1e5d3725d67ea09936201f0933b00ae
[ "Ruby" ]
1
Ruby
csmcdermott/whispersync
f91f446ec011894a5dba8e9d7dc2552b4a669893
ab56b0caf36dde178802b4b8754f894d6b761f79
refs/heads/master
<file_sep>import os, sys try: from setuptools import setup from setuptools.command.install import install as _install from setuptools.command.sdist import sdist as _sdist except ImportError: from distutils.core import setup from distutils.command.install import install as _install from distutils.command.sdist import sdist as _sdist def _run_build_tables(dir): from subprocess import call call([sys.executable, '_build_tables.py'], cwd=os.path.join(dir, 'py010parser')) class install(_install): def run(self): _install.run(self) self.execute(_run_build_tables, (self.install_lib,), msg="Build the lexing/parsing tables") class sdist(_sdist): def make_release_tree(self, basedir, files): _sdist.make_release_tree(self, basedir, files) self.execute(_run_build_tables, (basedir,), msg="Build the lexing/parsing tables") setup( # metadata name='py010parser', description='010 template parser in Python', long_description=""" py010parser is a modified fork of the pycparser project. It is pure Python using the PLY parsing library. It parses 010 templates into an AST. """, license='BSD', version='0.1.5', author='<NAME>', maintainer='<NAME>', author_email='<EMAIL>', url='https://github.com/d0c-s4vage/py010parser', platforms='Cross Platform', classifiers = [ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3',], packages=['py010parser', 'py010parser.ply'], download_url="https://github.com/d0c-s4vage/py010parser/tarball/v0.1.5", keywords=["010", "template", "parser"], package_data={'py010parser': ['*.cfg']}, cmdclass={'install': install, 'sdist': sdist}, ) <file_sep>[![master Build Status](https://travis-ci.org/d0c-s4vage/py010parser.svg?branch=master)](https://travis-ci.org/d0c-s4vage/py010parser) - master [![develop Build Status](https://travis-ci.org/d0c-s4vage/py010parser.svg?branch=develop)](https://travis-ci.org/d0c-s4vage/py010parser) - develop # py010parser py010parser is a python library that can parse 010 templates. It is a modified fork of [<NAME>'s pycparser](https://github.com/eliben/pycparser) project. ## introduction Sweetscape's [010 editor](http://www.sweetscape.com/) is a binary-format editor and parser. [Many](https://www.google.com/search?q=github+010+templates&oq=github+010+templates) [templates](http://www.sweetscape.com/010editor/templates/) can be found online for most binary formats. This project (py010parser) is an effort to make 010 scripts parseable from python, with the intent to build additional tools using py010parser, such as [pfp](http://github.com/d0c-s4vage/pfp), an 010 template interpreter. <file_sep>#!/usr/bin/env python # encoding: utf-8 import glob import os import sys import unittest sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) def run_tests(): files = [] for filename in glob.glob(os.path.join(os.path.dirname(__file__), "*.py")): basename = os.path.basename(filename) if basename.startswith("test_") and basename.endswith(".py"): files.append(basename.replace(".py", "")) suite = unittest.TestLoader().loadTestsFromNames(files) testresult = unittest.TextTestRunner(verbosity=1).run(suite) sys.exit(0 if testresult.wasSuccessful() else 1) if __name__ == "__main__": run_tests() <file_sep>#!/usr/bin/env python import os import sys import unittest sys.path.insert(0, "..") from py010parser import parse_file, parse_string, c_ast def template_path(template_name): return os.path.join(os.path.dirname(__file__), "templates", template_name) class TestBasicParse(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_basic_struct(self): res = parse_string(""" struct NAME { int blah; } name; """, optimize=True, predefine_types=False) def test_basic_struct_with_args(self): res = parse_string(""" struct NAME (int a) { int blah; } name; """, optimize=True, predefine_types=False) def test_basic_struct_with_args2(self): res = parse_string(""" typedef struct (int a) { int blah; } SPECIAL_STRUCT; """, optimize=True, predefine_types=False) def test_basic_struct_with_args_calling(self): res = parse_string(""" typedef struct (int a) { int blah; } SPECIAL_STRUCT; SPECIAL_STRUCT test(10); int blah() { return 10; } """, optimize=True, predefine_types=False) decl = res.children()[1][1] self.assertTrue(isinstance(decl.type, c_ast.StructCallTypeDecl)) decl_args = decl.type.args.children() self.assertEqual(decl_args[0][1].value, "10") self.assertEqual(len(decl_args), 1) def test_struct_with_args_calling_not_func_decl(self): res = parse_string(""" typedef struct(int a) { char chars[a]; } test_structure; local int size = 4; test_structure test(size); // this SHOULD NOT be a function declaration """, predefine_types=False) decl = res.children()[2][1] self.assertEqual(decl.type.__class__, c_ast.StructCallTypeDecl) self.assertEqual(decl.type.args.__class__, c_ast.ExprList) def test_struct_with_args_calling_not_func_decl2(self): res = parse_string(""" typedef struct(int a) { char chars[a]; } test_structure; local int size = 4; test_structure test(size); // this SHOULD NOT be a function declaration """, predefine_types=False) decl = res.children()[2][1] self.assertEqual(decl.type.__class__, c_ast.StructCallTypeDecl) self.assertEqual(decl.type.args.__class__, c_ast.ExprList) def test_struct_with_args_calling_not_func_decl3(self): res = parse_string(""" typedef struct(int a, int b) { char chars1[a]; char chars2[b]; } test_structure; local int size = 4; test_structure test(size, 5); // this SHOULD NOT be a function declaration """, predefine_types=False) decl = res.children()[2][1] self.assertEqual(decl.type.__class__, c_ast.StructCallTypeDecl) self.assertEqual(decl.type.args.__class__, c_ast.ExprList) def test_sizeof_unary(self): res = parse_string(""" sizeof(this); """) def test_exists_unary(self): res = parse_string(""" exists(this); """) def test_parentof_unary(self): res = parse_string(""" parentof(this); """) def test_function_exists_unary(self): res = parse_string(""" function_exists(this); """) def test_startof_unary(self): res = parse_string(""" startof(this); """) def test_bitfield_in_if(self): res = parse_string(""" struct { if(1) { int field1:16; //int field1; } } blah; """, optimize=True, predefine_types=False) bitfield_decl = res.children()[0][1].type.type.children()[0][1].iftrue.children()[0][1] self.assertNotEqual(type(bitfield_decl), dict) def test_bitfield_outside_of_struct(self): res = parse_string(""" uint blah1:4; uint blah2:8; uint blah3:4; """, optimize=True, predefine_types=True) def test_basic(self): res = parse_string(""" struct NAME { int stringLength; char name[stringLength]; } name; """, optimize=True) def test_if_in_struct(self): res = parse_string(""" struct BLAH { int a:1; int b:2; int c:29; if(hello) { b = 10; } } blah; """, optimize=True) def test_declaration_in_struct(self): res = parse_string(""" int c; switch(c) { case 1: c++; case 2: int c; } """, optimize=True) def test_declaration_in_if(self): res = parse_string(""" if(1) { int c; } else { int b; } """, optimize=True) def test_switch_in_struct(self): res = parse_string(""" struct BLAH { int c; switch(c) { case 1: int aa; case 2: int bb; default: int cc; } } blah; """, optimize=True) def test_nested_structs(self): res = parse_string(""" struct FILE { struct HEADER { char type[4]; int version; int numRecords; } header; struct RECORD { int employeeId; char name[40]; float salary; } record[ header.numRecords ]; } file; """, optimize=True) # http://www.sweetscape.com/010editor/manual/TemplateVariables.htm def test_local_keyword(self): res = parse_string(""" local int a; local int b; """, optimize=True) def test_metadata(self): res = parse_string(""" local int a <hidden=true>; """, optimize=True) def test_typedef(self): res = parse_string(""" typedef unsigned int UINT2; UINT2 blah; """, optimize=True) def test_value_types(self): res = parse_string(""" time_t var1; OLETIME var2; FILETIME var3; DOSTIME var4; DOSDATE var5; HFLOAT var6; hfloat var7; DOUBLE var8; double var9; FLOAT var10; float var11; __uint64 var12; QWORD var13; UINT64 var14; UQUAD var15; uquad var16; uint64 var17; __int64 var18; INT64 var19; QUAD var20; quad var21; int64 var22; DWORD var23; ULONG var24; UINT32 var25; UINT var26; ulong var27; uint32 var28; uint var29; LONG var30; INT32 var31; INT var32; long var33; int32 var34; int var35; WORD var36; UINT16 var37; USHORT var38; uint16 var39; ushort var40; INT16 var41; SHORT var42; int16 var43; short var44; UBYTE var45; UCHAR var46; ubyte var47; uchar var48; BYTE var49; CHAR var50; byte var51; char var52; string var53; wstring var54; wchar_t var55; """, optimize=True) def test_block_item_at_root(self): # had to get rid of the default int ret val on functions # from pycparser res = parse_string(""" int a = 10; void some_function(int num) { some_function(); } a++; some_function(); """, optimize=True) def test_pass_by_reference(self): res = parse_string(""" void some_function(int &num, int &num2) { } void some_function(int &num2) { } """, optimize=True) def test_enum_types(self): # note that there have been problems using a built-in # type (int/float/etc) vs the typedefd ones, TYPEID vs res = parse_string(""" enum <ulong> COLORS { WHITE = 1 } var1; enum <int> COLORS { WHITE = 1 } var1; enum IFD_dirtype { IFD_TYPE_EXIF = 1, IFD_TYPE_GEOTAG, IFD_TYPE_CASIO_QV_R62, }; enum { TEST, TEST2 } blah; """, optimize=True) def test_struct_bitfield_with_metadata(self): res = parse_string(""" typedef struct tgCifDirEntry { uint16 storage_method : 2; uint16 data_type : 3; uint16 id_code : 11 <format=hex>; } CifDirEntry <read=ReadCifDirEntry>; """, optimize=True) def test_untypedefd_enum_as_typeid(self): res = parse_string(""" enum <ulong> BLAH { BLAH1, BLAH2, BLAH3 }; local BLAH x; """, optimize=True) def test_initializer_in_struct(self): res = parse_string(""" local int b = 11; typedef struct BLAH { local int a = 10; int a:10; } blah; """, optimize=True) def test_nested_bitfield_in_struct(self): res = parse_string(""" typedef struct BLAH { int a; switch(a) { case 10: int b:10; default: int c:10; } } blah; """, optimize=True) def test_single_decl_in_for_loop(self): res = parse_string(""" for(j = 0; j < 10; j++) ushort blah; """, optimize=True) def test_single_decl_in_while_loop(self): res = parse_string(""" while(1) ushort blah; """, optimize=True) def test_single_decl_in_do_while_loop(self): res = parse_string(""" while(1) ushort blah; """, optimize=True) def test_single_decl_in_do_while_loop(self): res = parse_string(""" do ushort blah; while(1); """, optimize=True) def test_single_decl_in_if(self): res = parse_string(""" if(1) ushort blah; """, optimize=True) def test_single_decl_in_if_else(self): res = parse_string(""" if(1) ushort blah; else ushort blah; if(1) { ushort blah; } else ushort blah; if(1) ushort blah; else { ushort blah; } if(1) { ushort blah; } else { ushort blah; } """, optimize=True) def test_implicit_struct_typedef(self): res = parse_string(""" struct Blah { int a; } blah; Blah b; """, optimize=True) # I think we'll make a break from 010 syntax here... # it's too ridiculous to me to allow types that have # not yet been defined def test_runtime_declared_type(self): res = parse_string(""" void ReadAscString1(StrAscii1 &s) { ; } """, optimize=True, predefine_types=False) def test_metadata_with_string_value(self): res = parse_string(""" int a <comment="this is a comment", key=val>; int a <comment="this is a comment">; """, optimize=True) def test_large_template(self): res = parse_file(template_path("JPGTemplate.bt")) def test_png_template(self): res = parse_file(template_path("PNGTemplate.bt")) def test_preprocessor_with_string(self): res = parse_string(""" //this shouldn't cause any problems int a; """, optimize=True) def test_metadata_with_space1(self): res = parse_string(""" int a < key1 = value1 >; """, optimize=True) def test_metadata_with_space2(self): res = parse_string(""" int a < key1 = value1 , key2 = value2 >; """, optimize=True) def test_two_part_struct_decl(self): res = parse_string(""" struct StructTest; StructTest testing; """, optimize=True) if __name__ == "__main__": unittest.main()
838dd135891ba1d50f68024b36e8c382e7838a3d
[ "Markdown", "Python" ]
4
Python
strazzere/py010parser
cc2ee35119080105cfe1b13e8d192f9798410155
24dcf026455ab48a4fe3e29b94919c6ecfe846b8
refs/heads/master
<file_sep>/* * ajax动态弹出层 * */ ;(function( window, $ ) { var _ajax_modal = { //打开modal openModal : function( targetDivId , url , isModal, dataArray){ $.ajax({ type: "POST", url: url, data: dataArray, dataType:"html", success: function(html){ $( "#" + targetDivId ).empty().append(html); if (isModal) { $( '#' + targetDivId ).modal({ keyboard: false }) } } }); } } window.AjaxModal = _ajax_modal; })( window, window[ "jQuery" ] );<file_sep>package com.xiongzhaozhao.core.service; import com.xiongzhaozhao.core.api.service.LoginService; /** * @author zxm * @date 2018/6/28 14:16 * @name LoginServiceImpl * @description description */ public class LoginServiceImpl implements LoginService { } <file_sep>/** * @author zxm * @date 2018/5/16 10:38 * @name package-info * @description description */<file_sep>package com.xiongzhaozhao.core.utils; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.Properties; /** * @author zxm * @date 2018/6/28 17:20 * @name PropertyUtils * @description description */ public class PropertyUtils { private static final Map<String, String> props = Maps.newHashMap(); public PropertyUtils(List<Properties> propList) { Preconditions.checkNotNull(propList, "属性文件不能为空"); for (Properties prop : propList) { Enumeration enumeration = prop.propertyNames(); while (enumeration.hasMoreElements()) { String name = (String) enumeration.nextElement(); props.put(name, prop.getProperty(name)); } } } public static String get(String key, Object... params) { return props.get(key); } public static Integer getInteger(String key) { return Integer.parseInt(get(key)); } public static Long getLong(String key) { return Long.parseLong(get(key)); } public static Double getDouble(String key) { return Double.parseDouble(get(key)); } } <file_sep>(function(){ if(!window.PageUtil) { var PageUtil = window.PageUtil = { pageSearch : function(formId, pageNo) { var formObj = $("#" + formId); $("#" + formId + "__pagingNo").val(pageNo); formObj.submit(); }, ajaxPageSearch : function(callback, pageNo) { $("#ajax__pagingNo").val(pageNo); callback(); }, jumpPageSearch : function(formId, searchButton) { var pageNo = $(searchButton).prev("input").val(); this.pageSearch(formId, pageNo); }, pageSizeChange : function(formId,dom){ BlockWin.block(); var formObj = $("#" + formId); $("#" + formId + "__pageSize").val($(dom).val()); $("#" + formId + "__pagingNo").val(1); formObj.submit(); } }; } })();<file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>xiongzhaozhao</artifactId> <groupId>com.xunzhaozhao</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>com.xunzhaozhao</groupId> <artifactId>xzz_job</artifactId> <version>${xiongzhaozho.version}</version> <packaging>war</packaging> <name>xzz_job</name> <dependencies> <!-- quartz start --> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.3</version> <exclusions> <exclusion> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> </exclusion> </exclusions> </dependency> <!-- quartz end --> </dependencies> <profiles> <profile> <id>release</id> <activation> <activeByDefault>true</activeByDefault> </activation> <build> <resources> <resource> <directory>${basedir}/src/main/resources</directory> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> </resource> </resources> </build> </profile> </profiles> </project><file_sep>package com.xiongzhaozhao.core.api.service; /** * @author zxm * @date 2018/6/28 14:35 * @name LoginService * @description description */ public interface LoginService { } <file_sep>/* * 菜单显示 */ $(function() { var active = 0; //设置选中的菜单 $("#accordion > div").each(function(index){ if($(this).has("a[class=selected]").length>0){ active = index; return false; } }); //取得窗口高度 var pageHeight = $(window).innerHeight(); //实例化抽屉菜单 $( "#accordion" ).accordion({active: active,autoHeight: false , fillSpace: true ,navigation: true}); $(".ui-accordion-content").css("height",pageHeight*0.6); //显示菜单,刚开始菜单隐藏,防止菜单样式没有完全生成造成页面抖动严重 $( "#accordion" ).show(); $( "#left_menu_context" ).remove(); //设置窗口改变时执行方法 $(window).resize(function() { $( "#accordion" ).accordion( "resize" ); $(".ui-accordion-content").css("height",pageHeight*0.6); }); });<file_sep>package com.xiongzhaozhao.job; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Date; /** * @author zxm * @date 2018/8/6 16:56 * @name com.xiongzhaozhao.job.TestJob * @description description */ @Component public class TestJob { //五分钟调用一次 测试solr 虚拟机 @Scheduled(cron = "0/10 * * * * ?") public void runFunction(){ System.out.println("Method executed at every 10 seconds. Current time is :: " + (new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date())); } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>xiongzhaozhao</artifactId> <groupId>com.xunzhaozhao</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>com.xunzhaozhao</groupId> <artifactId>xzz_core</artifactId> <version>${xiongzhaozho.version}</version> <name>xzz_core</name> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>dubbo</artifactId> <version>2.4.10</version> <exclusions> <exclusion> <artifactId>spring</artifactId> <groupId>org.springframework</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.6</version> <exclusions> <exclusion> <artifactId>slf4j-log4j12</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.github.sgroschupf</groupId> <artifactId>zkclient</artifactId> <version>0.1</version> </dependency> <!-- ZXing Core --> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20090211</version> </dependency> <!-- aliyun --> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>2.8.2</version> </dependency> <!-- message --> <dependency> <groupId>net.sf.ezmorph</groupId> <artifactId>ezmorph</artifactId> <version>1.0.3</version> </dependency> <!-- json --> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.2.3</version> <classifier>jdk15</classifier> </dependency> <!-- httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.4</version> </dependency> <!-- message end --> <!-- antisamy --> <dependency> <groupId>org.owasp.antisamy</groupId> <artifactId>antisamy</artifactId> <version>1.5.3</version> </dependency> <!-- jsoup --> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.10.2</version> </dependency> <!-- cors --> <dependency> <groupId>com.thetransactioncompany</groupId> <artifactId>cors-filter</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>com.thetransactioncompany</groupId> <artifactId>java-property-utils</artifactId> <version>1.10</version> </dependency> <!-- orika-filter --> <dependency> <groupId>ma.glasnost.orika</groupId> <artifactId>orika-core</artifactId> <version>1.4.5</version> </dependency> <!-- dozer --> <dependency> <groupId>net.sf.dozer</groupId> <artifactId>dozer</artifactId> <version>5.5.1</version> </dependency> <!-- commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <!-- commons-collections --> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <!-- junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> <version>4.12</version> </dependency> <!-- http request --> <dependency> <groupId>com.github.kevinsawicki</groupId> <artifactId>http-request</artifactId> <version>6.0</version> </dependency> <!-- validator --> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.4.Final</version> </dependency> <dependency> <groupId>org.jboss.logging</groupId> <artifactId>jboss-logging</artifactId> <version>3.3.0.Final</version> </dependency> <dependency> <groupId>com.fasterxml</groupId> <artifactId>classmate</artifactId> <version>1.3.2</version> </dependency> <!-- velocity extends --> <dependency> <groupId>com.googlecode.rapid-framework</groupId> <artifactId>rapid-core</artifactId> <version>4.0.5</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-tools</artifactId> <version>2.0</version> <exclusions> <exclusion> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> </exclusion> <exclusion> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> </exclusion> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> <exclusion> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>oro</groupId> <artifactId>oro</artifactId> <version>2.0.8</version> </dependency> <dependency> <groupId>xml-apis</groupId> <artifactId>xml-apis</artifactId> <version>1.4.01</version> </dependency> <!-- kaptcha --> <dependency> <groupId>com.google.code.kaptcha</groupId> <artifactId>kaptcha</artifactId> <version>2.3</version> </dependency> <!-- poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.xmlbeans</groupId> <artifactId>xmlbeans</artifactId> <version>2.6.0</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.1</version> </dependency> <!-- file upload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.1</version> </dependency> <!-- simpleimage --> <dependency> <groupId>com.alibaba</groupId> <artifactId>simpleimage</artifactId> <version>1.2.3</version> </dependency> <!-- jai-filter --> <dependency> <groupId>javax.media</groupId> <artifactId>jai-core</artifactId> <version>1.1.3</version> </dependency> <!-- jai-codec --> <dependency> <groupId>com.sun.media</groupId> <artifactId>jai-codec</artifactId> <version>1.1.3</version> </dependency> <!-- jsqlparser --> <dependency> <groupId>com.github.jsqlparser</groupId> <artifactId>jsqlparser</artifactId> <version>1.1</version> </dependency> <!-- zt-zip --> <dependency> <groupId>org.zeroturnaround</groupId> <artifactId>zt-zip</artifactId> <version>1.12</version> </dependency> <!-- dom4j --> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <!-- xstream --> <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.7</version> </dependency> <!-- servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> </dependency> </dependencies> </project><file_sep>/* * ajax动态弹出层 * */ ;(function( window, $ ) { var _common_form = { //form提交 submit : function( formId , url ){ BlockWin.block(); $( "#" + formId ).attr("action",url); $( "#" + formId ).submit(); } } window.CommonForm = _common_form; })( window, window[ "jQuery" ] );<file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.xunzhaozhao</groupId> <artifactId>xiongzhaozhao</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <name>xiongzhaozhao</name> <modules> <module>xzz_user</module> <module>xzz_user_api</module> <module>xzz_task</module> <module>xzz_task_api</module> <module>xzz_shop</module> <module>xzz_shop_api</module> <module>xzz_pay</module> <module>xzz_pay_api</module> <module>xzz_web_common</module> <module>xzz_core</module> <module>xzz_service_common</module> <module>xzz_job</module> <module>xzz_app_portal</module> <module>xzz_config</module> <module>xzz_web_manager</module> <module>xzz_web</module> <module>xzz_content</module> <module>xzz_content_api</module> </modules> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.3.RELEASE</version> <relativePath /> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>dubbo</artifactId> <version>2.4.10</version> <exclusions> <exclusion> <artifactId>spring</artifactId> <groupId>org.springframework</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.6</version> <exclusions> <exclusion> <artifactId>slf4j-log4j12</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.github.sgroschupf</groupId> <artifactId>zkclient</artifactId> <version>0.1</version> </dependency> <!-- ZXing Core --> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20090211</version> </dependency> <!-- aliyun --> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>2.8.2</version> </dependency> <!-- message --> <dependency> <groupId>net.sf.ezmorph</groupId> <artifactId>ezmorph</artifactId> <version>1.0.3</version> </dependency> <!-- json --> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.2.3</version> <classifier>jdk15</classifier> </dependency> <!-- httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.4</version> </dependency> <!-- message end --> <!-- antisamy --> <dependency> <groupId>org.owasp.antisamy</groupId> <artifactId>antisamy</artifactId> <version>1.5.3</version> </dependency> <!-- jsoup --> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.10.2</version> </dependency> <!-- cors --> <dependency> <groupId>com.thetransactioncompany</groupId> <artifactId>cors-filter</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>com.thetransactioncompany</groupId> <artifactId>java-property-utils</artifactId> <version>1.10</version> </dependency> <!-- orika-filter --> <dependency> <groupId>ma.glasnost.orika</groupId> <artifactId>orika-core</artifactId> <version>1.4.5</version> </dependency> <!-- dozer --> <dependency> <groupId>net.sf.dozer</groupId> <artifactId>dozer</artifactId> <version>5.5.1</version> </dependency> <!-- commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <!-- commons-collections --> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <!-- junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> <version>4.12</version> </dependency> <!-- http request --> <dependency> <groupId>com.github.kevinsawicki</groupId> <artifactId>http-request</artifactId> <version>6.0</version> </dependency> <!-- validator --> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.4.Final</version> </dependency> <dependency> <groupId>org.jboss.logging</groupId> <artifactId>jboss-logging</artifactId> <version>3.3.0.Final</version> </dependency> <dependency> <groupId>com.fasterxml</groupId> <artifactId>classmate</artifactId> <version>1.3.2</version> </dependency> <!-- velocity extends --> <dependency> <groupId>com.googlecode.rapid-framework</groupId> <artifactId>rapid-core</artifactId> <version>4.0.5</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-tools</artifactId> <version>2.0</version> <exclusions> <exclusion> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> </exclusion> <exclusion> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> </exclusion> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> <exclusion> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>oro</groupId> <artifactId>oro</artifactId> <version>2.0.8</version> </dependency> <dependency> <groupId>xml-apis</groupId> <artifactId>xml-apis</artifactId> <version>1.4.01</version> </dependency> <!-- kaptcha --> <dependency> <groupId>com.google.code.kaptcha</groupId> <artifactId>kaptcha</artifactId> <version>2.3</version> </dependency> <!-- poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.xmlbeans</groupId> <artifactId>xmlbeans</artifactId> <version>2.6.0</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.1</version> </dependency> <!-- file upload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.1</version> </dependency> <!-- simpleimage --> <dependency> <groupId>com.alibaba</groupId> <artifactId>simpleimage</artifactId> <version>1.2.3</version> </dependency> <!-- jai-filter --> <dependency> <groupId>javax.media</groupId> <artifactId>jai-core</artifactId> <version>1.1.3</version> </dependency> <!-- jai-codec --> <dependency> <groupId>com.sun.media</groupId> <artifactId>jai-codec</artifactId> <version>1.1.3</version> </dependency> <!-- jsqlparser --> <dependency> <groupId>com.github.jsqlparser</groupId> <artifactId>jsqlparser</artifactId> <version>1.1</version> </dependency> <!-- zt-zip --> <dependency> <groupId>org.zeroturnaround</groupId> <artifactId>zt-zip</artifactId> <version>1.12</version> </dependency> <!-- dom4j --> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <!-- xstream --> <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.7</version> </dependency> <!-- servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> </dependency> <!--alibaba.fastjson--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.4</version> </dependency> <!--guava--> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-all --> <!--shiro--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-all</artifactId> <version>1.1.0</version> </dependency> <!-- quartz start --> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.3</version> <exclusions> <exclusion> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> </exclusion> </exclusions> </dependency> <!-- quartz end --> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
f5c1f0713ff9ee009ccf3430c119433aaa8b857d
[ "JavaScript", "Java", "Maven POM" ]
12
JavaScript
zhaoxumin/xiongzhaozhao
bf01a060e91594e698572d44082d5211b28efb34
a72562ad21b60dd51f76775bc04f9439d5747dcd
refs/heads/master
<repo_name>ImQdf/wxDemo<file_sep>/Controllers/README.txt  //此层作为控制器入口,数据验证,权限验证等,尽量少做业务逻辑处理;逻辑处理代码写入logic层 可以建立xxBaseController继承Controller基类作为扩展基类编写自定义代码 DefaultController.cs做为全局拦截类,若编写具体的业务请在对应的控制器中编写 控制器命名规范;控制目录最多3层{域名}/{控制器}/{方法} 要避免控制器层类名一致,虽然命名空间不同,但获取是程序集的全部类所有会导致冲突 xx业务AdminController xx业务AdminApiController xx业务Controller xx业务ApiController xx控制器.cs与View层Views文件夹 -> xx文件夹对应 例如view/Views/xx/ 则建立xxController.cs类 若需要使用ajax异步请求API,则建立xxApiController.cs类 方法名规范渲染html;重载方法只取第一个方法 xx.cs->index()与View层 -> Views文件夹 -> xx文件夹名称 -> index.html对应 例如view/Views/xx/index 则在xxController.cs类中添加index方法 /// <summary> /// 作为API使用时,CancelLoadHtml=true; /// </summary> /// <param name="methodName"></param> /// <returns></returns> public override bool BeforeInvoke(string methodName) { CancelLoadHtml = true;//使用API时取消读取html return true; } //特殊;避免这种情况下;最好只有3层目录 又分文件夹情况下:view/Views/AdminWeb/xx 那么控制器建立在:Controllers/Admin/xxAdminController.cs 方法中使用: path = "Views/AdminWeb/user/" + Action + ".html"; View = ViewEngine.Create(path);//创建视图 渲染html的加载 <file_sep>/View/obj/Release/AspnetCompileMerge/Source/Views/Admin/page/order/orderList.js layui.use("table", function () { var table = layui.table; table.render({ elem: "#tableData" , url: "/OrderAdmin/GetOrderList" , page: true , cellMinWidth: 60 , cols: [[ { type: "checkbox" } , { field: "OrderId", title: "ID" } , { field: "OrderMarking", title: "订单号" } , { field: "OrderDate", title: "下单时间" } , { field: "UserName", title: "下单人昵称" } , { field: "Consignee", title: "收货人昵称" } , { field: "ConsigneeTel", title: "收货人电话" } , { field: "PaymentType", title: "支付方式" } , { field: "OrderTotal", title: "订单金额" } , { field: "OrderStatus", title: "订单状态", templet: function (d) { if (d.OrderStatus === 0) { return '待付款'; } if (d.OrderStatus === 1) { return '待发货'; } return '未知'; } } , { width: 300, title: "操作", align: "center", toolbar: "#barProduct" } ]], id: "tableDataDT" }); function deleteAjax(ids) { console.info(ids); if (ids.length <= 0) { layer.alert("请选择要删除的数据", { icon: 0, title: "提示信息" }); return; } layer.confirm("确定删除选中的信息?", { icon: 3, title: "提示信息" }, function (index) { index = layer.msg("删除中,请稍候", { icon: 16, time: 60000, shade: 0.8 }); $.ajax({ url: "/OrderAdmin/DeleteAPI", type: "post", dataType: "json", data: { ids: ids }, //async: false, success: function (data) { layer.close(index); if (data.success) { table.reload("tableDataDT"); } else { layer.alert(data.msg); } }, error: function (data) { console.info("fail"); } }); }); } table.on("tool(tableData)", function (obj) { var data = obj.data, layEvent = obj.event; var index; if (layEvent === "detail") { index = layui.layer.open({ title: "查看用户", type: 2, content: "userDetail.html?id=" + data.OrderId, success: function (layero, index) { var body = layer.getChildFrame("body", index); } }); layui.layer.full(index); } else if (layEvent === "del") { var ids = []; ids.push(data.OrderId); deleteAjax(ids); } else if (layEvent === "edit") { index = layui.layer.open({ title: "编辑用户", type: 2, content: "updateUser.html?id=" + data.OrderId, success: function (layero, index) { var body = layer.getChildFrame("body", index); } }); layui.layer.full(index); } }); var $ = layui.$, active = { reload: function () { var txtOrderId = $("#txtOrderId"); table.reload("tableDataDT", { page: { curr: 1 }, where: { key: { OrderId: txtOrderId.val() } } }); } , getCheckData: function () { var checkStatus = table.checkStatus("tableDataDT"); var data = checkStatus.data; var ids = []; for (var i in data) { if (data.hasOwnProperty(i)) { ids.push(data[i].OrderId); } } deleteAjax(ids); } }; $("#searchbtn,#batchdel").on("click", function () { var type = $(this).data("type"); active[type] ? active[type].call(this) : ""; }); }); <file_sep>/View/Global.asax.cs #define 使用RegisterServices方式注册 using System; using System.Collections.Specialized; using System.Web; using Logic.WxSenparc; namespace View { public class Global : HttpApplication { protected void Application_Start(object sender, EventArgs e) { #if 使用RegisterServices方式注册 new WxHelper().RegisterV5(); #else new WxHelper().RegisterWeixinThreads(); #endif } protected void Session_Start(object sender, EventArgs e) { } protected void Application_BeginRequest(object sender, EventArgs e) { } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } protected void Application_Error(object sender, EventArgs e) { } protected void Session_End(object sender, EventArgs e) { } protected void Application_End(object sender, EventArgs e) { } } }<file_sep>/README.md # wxDemo 利用cyq.data 金牛框架+盛派开源框架实现的微信对接demo <file_sep>/View/obj/Release/AspnetCompileMerge/Source/Views/Admin/js/nav.js var navs = [{ "title" : "用户管理", "icon" : "&#xe612;", "href" : "", "spread" : false, "children" : [ { "title" : "会员列表", "icon" : "&#xe623;", "href" : "page/user/allUsers.html", "spread" : false } ] }, { "title": "商品管理", "icon": "&#xe63c;", "href": "", "spread": false, "children": [ { "title": "商品列表", "icon": "&#xe623;", "href": "page/product/allProduct.html", "spread": false } ] }, { "title": "订单管理", "icon": "&#xe63c;", "href": "", "spread": false, "children": [ { "title": "订单列表", "icon": "&#xe623;", "href": "page/order/orderList.html", "spread": false } ] }, { "title" : "财务管理", "icon" : "&#xe62c;", "href" : "", "spread" : false, "children" : [ { "title" : "退换货管理", "icon" : "&#xe623;", "href" : "page/financialManagement/returns.html", "spread" : false }, { "title" : "提现管理", "icon" : "&#xe623;", "href" : "page/financialManagement/withdrawCash.html", "spread" : false }, { "title":"有贝明细", "icon":"&#xe623;", "href":"page/financialManagement/youbeiDetail.html", "spread":false } ] },{ "title" : "系统管理", "icon" : "&#xe614;", "href" : "", "spread" : false, "children":[ { "title":"管理员列表", "icon":"&#xe623;", "href":"page/administrator/allAdministrator.html", "spread":false } ] }]<file_sep>/Controllers/DefaultController.cs using System; using System.Text; using System.Web; using CYQ.Data; using CYQ.Data.Cache; using Taurus.Core; namespace Controllers { public class DefaultController : Controller { /// <summary> /// 权限验证 /// </summary> /// <param name="controller"></param> /// <param name="methodName"></param> /// <returns></returns> public static bool CheckToken(IController controller, string methodName) { //string token2 = controller.Context.Request.Headers.Get("sign"); //说明:若需验证,请在具体类中重写此方法 return true; } /// <summary> /// /// </summary> /// <param name="controller"></param> /// <param name="methodName"></param> /// <returns></returns> public static bool BeforeInvoke(IController controller, string methodName) { return true; //if (controller.IsHttpPost) //{ // //拦截全局处理 // controller.Write(methodName + " NoACK"); //} } } } <file_sep>/Controllers/WeiXinApiController.cs using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Web; using CYQ.Data; using CYQ.Data.Table; using CYQ.Data.Tool; using Logic; using Logic.WxSenparc; using Taurus.Core; namespace Controllers { public class WeiXinApiController : Controller { public WeiXinApiController() { } /// <summary> /// 作为API使用时,CancelLoadHtml=true; /// </summary> /// <param name="methodName"></param> /// <returns></returns> public override bool BeforeInvoke(string methodName) { CancelLoadHtml = true;//使用API时取消读取html return true; } #region [变量] /// <summary> /// API域名 /// </summary> private readonly string _domianName = AppConfig.GetApp("DomianName"); #endregion /// <summary> /// 微信消息接口对接;wxinxinapi/WxRequest /// </summary> public void WxRequest() { if (IsHttpPost) { try { Stream s = Context.Request.InputStream; string responseDoc = WxHelper.WxRequest(s); Write(responseDoc); } catch (Exception ex) { Log.WriteLogToTxt("异常微信接口对接:" + ex.Message, LogType.Error); } } else { string signature = Query<string>("signature"); string nonce = Query<string>("nonce"); string timestamp = Query<string>("timestamp"); string echostr = Query<string>("echostr"); Write(WxHelper.Check(signature, timestamp, nonce, echostr)); } } /// <summary> /// 获取微信授权登录地址 /// </summary> public void GetOAuthUrl() { string returnurl = Query<string>("returnurl"); string redirectUri = _domianName + "/WeiXinApi/WxOAuth?returnurl=" + returnurl;//你的回调地址,通过returnurl参数携带其他参数 string url = WxHelper.GetAuthorizeUrl(redirectUri);//微信授权登录地址,会携带code跳转到回调 Write(url, true); } /// <summary> /// 根据code拉取授权信息 /// </summary> public void WxOAuth() { try { string userAgent = Context.Request.UserAgent; if (userAgent != null && userAgent.ToLower().Contains("micromessenger")) { string code = Query<string>("code"); string returnurl = Query<string>("returnurl"); Log.WriteLogToTxt("returnurl:" + returnurl); var result = WxHelper.GetAccessToken(code);//通过code拉取 Log.WriteLogToTxt(JsonHelper.ToJson(result)); if (result.errcode == Senparc.Weixin.ReturnCode.请求成功) { var unionId = result.unionid; var openId = result.openid; var accessToken = result.access_token; //具体的业务逻辑了... if (WxRegistere(accessToken, openId, unionId)) { //注册成功后的逻辑 Context.Response.Redirect(returnurl); } } } else { //不是微信浏览器 Log.WriteLogToTxt("not micromessenger !"); } } catch (Exception) { } } /// <summary> /// 微信授权用户注册 /// 根据自己的业务重写即可 /// </summary> /// <returns></returns> public bool WxRegistere(string accessToken, string openId, string unionId) { using (MAction m = new MAction("WXUser")) { #region [OpenId/UnionId是否存在] var fill = !string.IsNullOrEmpty(unionId) ? m.Fill("UnionId='" + unionId + "'") : m.Fill("OpenId='" + openId + "'"); #endregion #region 微信用户拉取信息拉取 var UserInfo = WxHelper.GetUserInfo(accessToken, openId);//拉取用户微信信息 Log.WriteLogToTxt("通过accessToken+openid拉取用户信息:" + JsonHelper.ToJson(UserInfo)); var IsUserInfo = WxHelper.GetUserInfo(openId);//用于判断是否关注了公众号的用户信息 Log.WriteLogToTxt("通过openId拉取的用户信息:" + JsonHelper.ToJson(IsUserInfo)); #endregion //下面是你的具体业务,我就不写了哈。 long userId; if (fill) { //用户已存在,你可以根据你的业务需求重写编写 return true; } else { //注册方法 //m.Set("字段名",vaule); var result = m.Insert(); return result; } } } } } <file_sep>/View/obj/Release/AspnetCompileMerge/Source/Views/Admin/page/user/allUsers.js layui.use("table", function () { var table = layui.table; table.render({ elem: "#tableData" , url: "/UserAdmin/GetUserList" , page: true , cellMinWidth: 60 , cols: [[ { type: "checkbox" } , { field: "UserId", title: "用户ID" } , { field: "UserHead", title: "用户头像", templet: "#headimg" } , { field: "UserName", title: "用户昵称" } , { field: "RealName", title: "真实姓名" } , { field: "Sex", title: "性别", templet: function (d) { if (d.Sex === 1) { return '男'; } if (d.Sex === 2) { return '女'; } return '未知'; } } , { field: "Phone", title: "手机" } , { field: "IsAmbassador", title: "等级", templet: function (d) { if (d.IsAmbassador === 1) { return '推广大使'; } return '普通会员'; } } , { width: 300, fixed: "right", title: "操作", align: "center", toolbar: "#barUser" } ]], id: "tableDataDT" }); function deleteAjax(ids) { if (ids.length <= 0) { layer.alert("请选择要删除的数据", { icon: 0, title: "提示信息" }); return; } layer.confirm("确定删除选中的信息?", { icon: 3, title: "提示信息" }, function (index) { index = layer.msg("删除中,请稍候", { icon: 16, time: 60000, shade: 0.8 }); $.ajax({ url: "/UserAdmin/DeleteAPI", type: "post", dataType: "json", data: { ids: ids }, //async: false, success: function (data) { layer.close(index); if (data.success) { table.reload("tableDataDT"); } else { layer.alert(data.msg); } }, error: function (data) { console.info("fail"); } }); }); } table.on("tool(tableData)", function (obj) { var data = obj.data, layEvent = obj.event; var index; if (layEvent === "detail") { index = layui.layer.open({ title: "查看用户", type: 2, content: "userDetail.html?id=" + data.UserId, success: function (layero, index) { var body = layer.getChildFrame("body", index); } }); layui.layer.full(index); } else if (layEvent === "del") { var ids = []; ids.push(data.UserId); deleteAjax(ids); } else if (layEvent === "edit") { index = layui.layer.open({ title: "编辑用户", type: 2, content: "updateUser.html?id=" + data.UserId, success: function (layero, index) { var body = layer.getChildFrame("body", index); } }); layui.layer.full(index); } }); var $ = layui.$, active = { reload: function () { var txtUserName = $("#txtUserName"); var txtRealName = $("#txtRealName"); table.reload("tableDataDT", { page: { curr: 1 }, where: { key: { UserName: txtUserName.val(), RealName: txtRealName.val() } } }); } , getCheckData: function () { var checkStatus = table.checkStatus("tableDataDT"); var data = checkStatus.data; var ids = []; for (var i in data) { if (data.hasOwnProperty(i)) { ids.push(data[i].UserId); } } deleteAjax(ids); } }; $("#searchbtn,#batchdel").on("click", function () { var type = $(this).data("type"); active[type] ? active[type].call(this) : ""; }); }); <file_sep>/Controllers/Senparc/WxHelper.cs using System; using System.Collections.Generic; using System.IO; using System.Web; using System.Xml.Linq; using CYQ.Data; using CYQ.Data.Tool; using Senparc.CO2NET; using Senparc.CO2NET.Cache; using Senparc.CO2NET.RegisterServices; using Senparc.CO2NET.Threads; using Senparc.Weixin; using Senparc.Weixin.Entities; using Senparc.Weixin.Entities.TemplateMessage; using Senparc.Weixin.Exceptions; using Senparc.Weixin.MP; using Senparc.Weixin.MP.AdvancedAPIs; using Senparc.Weixin.MP.AdvancedAPIs.Media; using Senparc.Weixin.MP.AdvancedAPIs.OAuth; using Senparc.Weixin.MP.AdvancedAPIs.User; using Senparc.Weixin.MP.CommonAPIs; using Senparc.Weixin.MP.Containers; using Senparc.Weixin.MP.Entities; using Senparc.Weixin.MP.Entities.Menu; using Senparc.Weixin.MP.Entities.Request; using Senparc.Weixin.MP.Helpers; using Senparc.Weixin.MP.TenPayLibV3; //using Senparc.Weixin.Threads; namespace Logic.WxSenparc { /// <summary> /// 微信帮助类 /// </summary> public partial class WxHelper : ApplicationException { public WxHelper() { } #region //内部变量 private static readonly string AppId = AppConfig.GetApp("AppId"); private static readonly string Secret = AppConfig.GetApp("AppSecret"); private static readonly string MchId = AppConfig.GetApp("mch_id"); private static readonly string MchIdkey = AppConfig.GetApp("mch_idkey"); private static readonly string CertPath = AppDomain.CurrentDomain.BaseDirectory + AppConfig.GetApp("certPath"); private static readonly string CertPassword = AppConfig.GetApp("certPwd"); #endregion #region [建立连接,POST被动回复] /// <summary> /// 建立链接 /// </summary> /// <param name="signature"></param> /// <param name="timestamp"></param> /// <param name="nonce"></param> /// <param name="echostr"></param> /// <returns></returns> public static string Check(string signature, string timestamp, string nonce, string echostr) { PostModel postModel = new PostModel() { Signature = signature, Timestamp = timestamp, Nonce = nonce }; return CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, AppConfig.GetApp("token")) ? echostr : "验证未通过"; } /// <summary> /// 接收微信post消息 /// </summary> /// <param name="inputStream"></param> /// <param name="maxRecordCount"></param> /// <returns></returns> public static string WxRequest(Stream inputStream, int maxRecordCount = 10) { //验证字符串... var messageHandler = new CustomMessageHandler(inputStream, null, maxRecordCount); try { messageHandler.Execute(); } catch (Exception ex) { // ignored } return messageHandler.ResponseDocument.ToString(); } #endregion #region[微信授权登录相关] /// <summary> /// 获取授权登录地址 /// </summary> /// <param name="redirectUrl">回调地址</param> /// <param name="state">携带参数</param> /// <returns></returns> public static string GetAuthorizeUrl(string redirectUrl, string state = "") { try { return OAuthApi.GetAuthorizeUrl(AppId, redirectUrl, state, OAuthScope.snsapi_userinfo); } catch (Exception ex) { return null; } } /// <summary> /// 根据code获取AccessToken /// </summary> /// <param name="code"></param> /// <returns></returns> public static OAuthAccessTokenResult GetAccessToken(string code) { try { OAuthAccessTokenResult result = OAuthApi.GetAccessToken(AppId, Secret, code); return result; } catch (Exception ex) { return null; } } /// <summary> /// 根据OpenId拉取用户信息 /// </summary> /// <param name="OpenId"></param> /// <returns></returns> public static UserInfoJson GetUserInfo(string OpenId) { try { var UserInfo = UserApi.Info(AppId, OpenId); return UserInfo; } catch (Exception ex) { return null; } } /// <summary> /// 根据AccessToken和openid拉取用户信息 /// </summary> /// <returns></returns> public static OAuthUserInfo GetUserInfo(string accessToken, string openId) { try { OAuthUserInfo userInfo = OAuthApi.GetUserInfo(accessToken, openId); return userInfo; } catch (ErrorJsonResultException ex) { return null; } } #endregion } /// <summary> /// /// </summary> public partial class WxHelper { #region 全局配置信息 /// <summary> /// 激活微信缓存 v5.0版本以下 /// </summary> public void RegisterWeixinThreads() { try { ThreadUtility.Register();//如果不注册此线程,则AccessToken、JsTicket等都无法使用SDK自动储存和管理。 AccessTokenContainer.Register(AppId, Secret); } catch (Exception ex) { } } /// <summary> /// v5.0版本注册 /// </summary> public void RegisterV5() { //设置全局 Debug 状态 var isGLobalDebug = true; //全局设置参数,将被储存到 Senparc.CO2NET.Config.SenparcSetting var senparcSetting = SenparcSetting.BuildFromWebConfig(isGLobalDebug); IRegisterService register = RegisterService.Start(senparcSetting) .UseSenparcGlobal(false, () => GetExCacheStrategies(senparcSetting)) .RegisterThreads(); var isWeixinDebug = true; //全局设置参数,将被储存到 Senparc.Weixin.Config.SenparcWeixinSetting var senparcWeixinSetting = SenparcWeixinSetting.BuildFromWebConfig(isWeixinDebug); register.UseSenparcWeixin(senparcWeixinSetting, senparcSetting) .RegisterMpAccount(AppId, Secret, "【xx】公众号"); } /// <summary> /// 获取Container扩展缓存策略 /// </summary> /// <returns></returns> private IList<IDomainExtensionCacheStrategy> GetExCacheStrategies(SenparcSetting senparcSetting) { var exContainerCacheStrategies = new List<IDomainExtensionCacheStrategy>(); senparcSetting = senparcSetting ?? new SenparcSetting(); //判断Redis是否可用 //var redisConfiguration = ConfigurationManager.AppSettings["Cache_Redis_Configuration"]; //if ((!string.IsNullOrEmpty(redisConfiguration) && redisConfiguration != "Redis配置")) //{ // exContainerCacheStrategies.Add(RedisContainerCacheStrategy.Instance); //} //判断Memcached是否可用 //var memcachedConfiguration = ConfigurationManager.AppSettings["Cache_Memcached_Configuration"]; //if ((!string.IsNullOrEmpty(memcachedConfiguration) && redisConfiguration != "Memcached配置")) //{ // exContainerCacheStrategies.Add(MemcachedContainerCacheStrategy.Instance); //} //也可扩展自定义的缓存策略 return exContainerCacheStrategies; } #endregion } } <file_sep>/View/obj/Release/AspnetCompileMerge/TempBuildDir/Views/Admin/page/product/allProduct.js layui.use("table", function () { var table = layui.table; table.render({ elem: "#tableData" , url: "/ProductAdmin/GetProductList" , page: true , cellMinWidth: 60 , cols: [[ { type: "checkbox" } , { field: "ProductId", title: "ID" } , { field: "ProductName", title: "商品图片", templet: "#headimg" } , { field: "ProductName", title: "商品名称" } , { field: "SKU", title: "商品SKU" } , { field: "MarketPrice", title: "市场价" } , { field: "SalePrice", title: "销售价" } , { field: "StockNum", title: "库存数量" } , { field: "IsProps", title: "类型", templet: function (d) { if (d.IsProps) { return '虚拟道具'; } return '普通产品'; } } , { width: 300, title: "操作", align: "center", toolbar: "#barProduct" } ]], id: "tableDataDT" }); function deleteAjax(ids) { if (ids.length <= 0) { layer.alert("请选择要删除的数据", { icon: 0, title: "提示信息" }); return; } layer.confirm("确定删除选中的信息?", { icon: 3, title: "提示信息" }, function (index) { index = layer.msg("删除中,请稍候", { icon: 16, time: 60000, shade: 0.8 }); $.ajax({ url: "/ProductAdmin/DeleteAPI", type: "post", dataType: "json", data: { ids: ids }, //async: false, success: function (data) { layer.close(index); if (data.success) { table.reload("tableDataDT"); } else { layer.alert(data.msg); } }, error: function (data) { console.info("fail"); } }); }); } table.on("tool(tableData)", function (obj) { var data = obj.data, layEvent = obj.event; var index; if (layEvent === "detail") { index = layui.layer.open({ title: "查看用户", type: 2, content: "userDetail.html?id=" + data.ProductId, success: function (layero, index) { var body = layer.getChildFrame("body", index); } }); layui.layer.full(index); } else if (layEvent === "del") { var ids = []; ids.push(data.ProductId); deleteAjax(ids); } else if (layEvent === "edit") { index = layui.layer.open({ title: "编辑用户", type: 2, content: "updateUser.html?id=" + data.ProductId, success: function (layero, index) { var body = layer.getChildFrame("body", index); } }); layui.layer.full(index); } }); var $ = layui.$, active = { reload: function () { var txtProductName = $("#txtProductName"); table.reload("tableDataDT", { page: { curr: 1 }, where: { key: { ProductName: txtProductName.val() } } }); } , getCheckData: function () { var checkStatus = table.checkStatus("tableDataDT"); var data = checkStatus.data; var ids = []; for (var i in data) { if (data.hasOwnProperty(i)) { ids.push(data[i].ProductId); } } deleteAjax(ids); } }; $("#searchbtn,#batchdel").on("click", function () { var type = $(this).data("type"); active[type] ? active[type].call(this) : ""; }); }); <file_sep>/View/obj/Release/AspnetCompileMerge/Source/Views/Admin/page/user/userDetail.js var areaData = address; var $form; var form; var $; layui.config({ base : "../../js/" }).use(['form','layer','upload','laydate'],function(){ form = layui.form; var layer = parent.layer === undefined ? layui.layer : parent.layer; $ = layui.jquery; $form = $('form'); laydate = layui.laydate; $(function () { var userid = $('.userId').val(); console.log(userid) $.ajax({ url: "/AdminServiceUser/GetServiceUserByUserId", type: "post", dataType: "json", data: { userId: userid }, async: false, success: function (data) { console.log(data) console.log('success') }, error: function (data) { console.info('fail'); } }); }) }) <file_sep>/Controllers/Senparc/CustomMessageHandler.cs using System.IO; using System.Linq; using CYQ.Data; using Senparc.NeuChar.Context; using Senparc.NeuChar.Entities; using Senparc.NeuChar.Helpers; using Senparc.Weixin.MP.AdvancedAPIs; using Senparc.Weixin.MP.Entities; using Senparc.Weixin.MP.Entities.Request; using Senparc.Weixin.MP.Helpers; using Senparc.Weixin.MP.MessageHandlers; /*此类参照盛派官方demo,只要找到对应方法编写具体业务即可[直接把demo的源码拿过来]*/ namespace Logic.WxSenparc { /// <summary> /// 自定义MessageHandler /// 把MessageHandler作为基类,重写对应请求的处理方法 /// </summary> public partial class CustomMessageHandler : MessageHandler<CustomMessageContext> { private readonly string appId = AppConfig.GetApp("AppId"); public CustomMessageHandler(Stream inputStream, PostModel postModel, int maxRecordCount = 0) : base(inputStream, postModel, maxRecordCount) { //这里设置仅用于测试,实际开发可以在外部更全局的地方设置, //比如MessageHandler<MessageContext>.GlobalWeixinContext.ExpireMinutes = 3。 WeixinContext.ExpireMinutes = 3; //在指定条件下,不使用消息去重 base.OmitRepeatedMessageFunc = requestMessage => { var textRequestMessage = requestMessage as RequestMessageText; if (textRequestMessage != null && textRequestMessage.Content == "容错") { return false; } return true; }; } public CustomMessageHandler(RequestMessageBase requestMessage) : base(requestMessage) { } public override void OnExecuting() { //测试MessageContext.StorageData if (CurrentMessageContext.StorageData == null) { CurrentMessageContext.StorageData = 0; } base.OnExecuting(); } public override void OnExecuted() { base.OnExecuted(); CurrentMessageContext.StorageData = ((int)CurrentMessageContext.StorageData) + 1; } /// <summary> /// 处理文字请求 /// </summary> /// <param name="requestMessage"></param> /// <returns></returns> public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage) { var responseMessage = base.CreateResponseMessage<ResponseMessageText>(); responseMessage.Content = "111"; return responseMessage; } /// <summary> /// 处理位置请求 /// </summary> /// <param name="requestMessage"></param> /// <returns></returns> public override IResponseMessageBase OnLocationRequest(RequestMessageLocation requestMessage) { var locationService = new LocationService(); var responseMessage = locationService.GetResponseMessage(requestMessage as RequestMessageLocation); return responseMessage; } public override IResponseMessageBase OnShortVideoRequest(RequestMessageShortVideo requestMessage) { var responseMessage = this.CreateResponseMessage<ResponseMessageText>(); responseMessage.Content = "您刚才发送的是小视频"; return responseMessage; } /// <summary> /// 处理图片请求 /// </summary> /// <param name="requestMessage"></param> /// <returns></returns> public override IResponseMessageBase OnImageRequest(RequestMessageImage requestMessage) { //一隔一返回News或Image格式 if (base.WeixinContext.GetMessageContext(requestMessage).RequestMessages.Count() % 2 == 0) { var responseMessage = CreateResponseMessage<ResponseMessageNews>(); responseMessage.Articles.Add(new Article() { Title = "您刚才发送了图片信息", Description = "您发送的图片将会显示在边上", PicUrl = requestMessage.PicUrl, Url = "http://sdk.weixin.senparc.com" }); responseMessage.Articles.Add(new Article() { Title = "第二条", Description = "第二条带连接的内容", PicUrl = requestMessage.PicUrl, Url = "http://sdk.weixin.senparc.com" }); return responseMessage; } else { var responseMessage = CreateResponseMessage<ResponseMessageImage>(); responseMessage.Image.MediaId = requestMessage.MediaId; return responseMessage; } } /// <summary> /// 处理语音请求 /// </summary> /// <param name="requestMessage"></param> /// <returns></returns> public override IResponseMessageBase OnVoiceRequest(RequestMessageVoice requestMessage) { var responseMessage = CreateResponseMessage<ResponseMessageMusic>(); //上传缩略图 //var accessToken = Containers.AccessTokenContainer.TryGetAccessToken(appId, appSecret); //var uploadResult = Senparc.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryMedia(appId, UploadMediaFileType.image, // GetMapPath("~/Images/Logo.jpg")); //设置音乐信息 responseMessage.Music.Title = "天籁之音"; responseMessage.Music.Description = "播放您上传的语音"; responseMessage.Music.MusicUrl = "http://sdk.weixin.senparc.com/Media/GetVoice?mediaId=" + requestMessage.MediaId; responseMessage.Music.HQMusicUrl = "http://sdk.weixin.senparc.com/Media/GetVoice?mediaId=" + requestMessage.MediaId; //responseMessage.Music.ThumbMediaId = uploadResult.media_id; //推送一条客服消息 try { CustomApi.SendText(appId, WeixinOpenId, "本次上传的音频MediaId:" + requestMessage.MediaId); } catch { } return responseMessage; } /// <summary> /// 处理视频请求 /// </summary> /// <param name="requestMessage"></param> /// <returns></returns> public override IResponseMessageBase OnVideoRequest(RequestMessageVideo requestMessage) { var responseMessage = CreateResponseMessage<ResponseMessageText>(); responseMessage.Content = "您发送了一条视频信息,ID:" + requestMessage.MediaId; return responseMessage; } /// <summary> /// 处理链接消息请求 /// </summary> /// <param name="requestMessage"></param> /// <returns></returns> public override IResponseMessageBase OnLinkRequest(RequestMessageLink requestMessage) { var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage); responseMessage.Content = string.Format(@"您发送了一条连接信息: Title:{0} Description:{1} Url:{2}", requestMessage.Title, requestMessage.Description, requestMessage.Url); return responseMessage; } public override IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage) { /* 所有没有被处理的消息会默认返回这里的结果, * 因此,如果想把整个微信请求委托出去(例如需要使用分布式或从其他服务器获取请求), * 只需要在这里统一发出委托请求,如: * var responseMessage = MessageAgent.RequestResponseMessage(agentUrl, agentToken, RequestDocument.ToString()); * return responseMessage; */ var responseMessage = this.CreateResponseMessage<ResponseMessageText>(); responseMessage.Content = "这条消息来自DefaultResponseMessage。"; return responseMessage; } public override IResponseMessageBase OnUnknownTypeRequest(RequestMessageUnknownType requestMessage) { /* * 此方法用于应急处理SDK没有提供的消息类型, * 原始XML可以通过requestMessage.RequestDocument(或this.RequestDocument)获取到。 * 如果不重写此方法,遇到未知的请求类型将会抛出异常(v14.8.3 之前的版本就是这么做的) */ var msgType = MsgTypeHelper.GetRequestMsgTypeString(requestMessage.RequestDocument); var responseMessage = this.CreateResponseMessage<ResponseMessageText>(); responseMessage.Content = "未知消息类型:" + msgType; global::Senparc.Weixin.WeixinTrace.SendCustomLog("未知请求消息类型", requestMessage.RequestDocument.ToString());//记录到日志中 return responseMessage; } } public class CustomMessageContext : MessageContext<IRequestMessageBase, IResponseMessageBase> { public CustomMessageContext() { base.MessageContextRemoved += CustomMessageContext_MessageContextRemoved; } /// <summary> /// 当上下文过期,被移除时触发的时间 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void CustomMessageContext_MessageContextRemoved(object sender, global::Senparc.NeuChar.Context.WeixinContextRemovedEventArgs<IRequestMessageBase, IResponseMessageBase> e) { /* 注意,这个事件不是实时触发的(当然你也可以专门写一个线程监控) * 为了提高效率,根据WeixinContext中的算法,这里的过期消息会在过期后下一条请求执行之前被清除 */ var messageContext = e.MessageContext as CustomMessageContext; if (messageContext == null) { return;//如果是正常的调用,messageContext不会为null } //TODO:这里根据需要执行消息过期时候的逻辑,下面的代码仅供参考 //Log.InfoFormat("{0}的消息上下文已过期",e.OpenId); //api.SendMessage(e.OpenId, "由于长时间未搭理客服,您的客服状态已退出!"); } } }
2779523ed646652571b02be5bf2056bf5a8363c1
[ "JavaScript", "C#", "Text", "Markdown" ]
12
Text
ImQdf/wxDemo
864ca7de6b723a9ea3ff5b53cd382396546ad5ba
790dbad0e3df8e93929b4e9e5c6c928cbdad5612
refs/heads/master
<file_sep># TicTacToe A simple game of tictactoe made using JavaFX <file_sep>module com.example.tictactoe { requires javafx.controls; requires javafx.fxml; opens com.example.tictactoe to javafx.fxml; exports com.example.tictactoe; }
0f009f1270cc7ac1ba8699fc9fbdd8590f6c9eb9
[ "Markdown", "Java" ]
2
Markdown
LukasH0lm/TicTacToe
8da784390eca06b0a9e27e174883dfeb3fb5d0d8
e67cae6b994430cd3658c4f82b616ca625d9852a
refs/heads/master
<repo_name>saumya0303/audio_adversarial_examples<file_sep>/xdg.py # Even more hacks. class BaseDirectory: def save_data_path(*args, **kwargs): return def save_data_path(*args, **kwargs): return <file_sep>/tf_logits.py ## tf_logits.py -- end-to-end differentable text-to-speech ## ## Copyright (C) 2017, <NAME> <<EMAIL>>. ## ## This program is licenced under the BSD 2-Clause licence, ## contained in the LICENCE file in this directory. import numpy as np import tensorflow as tf import argparse import scipy.io.wavfile as wav import time import os import sys sys.path.append("DeepSpeech") import DeepSpeech def compute_mfcc(audio, **kwargs): """ Compute the MFCC for a given audio waveform. This is identical to how DeepSpeech does it, but does it all in TensorFlow so that we can differentiate through it. """ batch_size, size = audio.get_shape().as_list() audio = tf.cast(audio, tf.float32) # 1. Pre-emphasizer, a high-pass filter audio = tf.concat((audio[:, :1], audio[:, 1:] - 0.97*audio[:, :-1], np.zeros((batch_size,512),dtype=np.float32)), 1) # 2. windowing into frames of 512 samples, overlapping windowed = tf.stack([audio[:, i:i+512] for i in range(0,size-320,320)],1) window = np.hamming(512) windowed = windowed * window # 3. Take the FFT to convert to frequency space ffted = tf.spectral.rfft(windowed, [512]) ffted = 1.0 / 512 * tf.square(tf.abs(ffted)) # 4. Compute the Mel windowing of the FFT energy = tf.reduce_sum(ffted,axis=2)+np.finfo(float).eps filters = np.load("filterbanks.npy").T feat = tf.matmul(ffted, np.array([filters]*batch_size,dtype=np.float32))+np.finfo(float).eps # 5. Take the DCT again, because why not feat = tf.log(feat) feat = tf.spectral.dct(feat, type=2, norm='ortho')[:,:,:26] # 6. Amplify high frequencies for some reason _,nframes,ncoeff = feat.get_shape().as_list() n = np.arange(ncoeff) lift = 1 + (22/2.)*np.sin(np.pi*n/22) feat = lift*feat width = feat.get_shape().as_list()[1] # 7. And now stick the energy next to the features feat = tf.concat((tf.reshape(tf.log(energy),(-1,width,1)), feat[:, :, 1:]), axis=2) return feat def get_logits(new_input, length, first=[]): """ Compute the logits for a given waveform. First, preprocess with the TF version of MFC above, and then call DeepSpeech on the features. """ batch_size = new_input.get_shape()[0] # 1. Compute the MFCCs for the input audio # (this is differentable with our implementation above) empty_context = np.zeros((batch_size, 9, 26), dtype=np.float32) new_input_to_mfcc = compute_mfcc(new_input) features = tf.concat((empty_context, new_input_to_mfcc, empty_context), 1) # 2. We get to see 9 frames at a time to make our decision, # so concatenate them together. features = tf.reshape(features, [new_input.get_shape()[0], -1]) features = tf.stack([features[:, i:i+19*26] for i in range(0,features.shape[1]-19*26+1,26)],1) features = tf.reshape(features, [batch_size, -1, 19, 26]) # 3. Finally we process it with DeepSpeech # We need to init DeepSpeech the first time we're called if first == []: first.append(False) DeepSpeech.create_flags() tf.app.flags.FLAGS.alphabet_config_path = "DeepSpeech/data/alphabet.txt" DeepSpeech.initialize_globals() logits, _ = DeepSpeech.BiRNN(features, length, [0]*10) return logits
f480a48425fdbf71e9fbf98297f3494aabd36ba8
[ "Python" ]
2
Python
saumya0303/audio_adversarial_examples
fc91c5e027f21cf1e1f7cc4fe34351c1a4ea32a7
0081c91efa331e1523c26656602cbd594861dbf4
refs/heads/master
<file_sep>/* Created by RJudd July 13, 2002 */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_ccfftmop_d_def.h,v 2.0 2003/02/22 15:18:30 judd Exp $ */ #ifndef _VI_CCFFTMOP_D_DEF_H #define _VI_CCFFTMOP_D_DEF_H #include"VI_fftm_building_blocks_d.h" #include"VI_cmcopy_d_d.h" /*========================================================*/ void vsip_ccfftmop_d( const vsip_fftm_d *Offt, const vsip_cmview_d *x, const vsip_cmview_d *y) { vsip_fftm_d Nfft = *Offt; vsip_fftm_d *fftm = &Nfft; VI_cmcopy_d_d(x,y); fftm->type = VSIP_CCFFTIP; VI_ccfftmip_d(fftm,y); } #endif /* _VI_CCFFTMOP_D_DEF_H */ <file_sep>/* Created RJudd Nov 27, 2011 */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"vsip.h" #include"vsip_blockattributes_f.h" #include"vsip_vviewattributes_f.h" #include"vsip_mviewattributes_f.h" #define VGET(v,i) (*(v->block->array + (v->offset + (vsip_stride)(i) * v->stride) * v->block->rstride)) #define VPUT(v,i,s) {*(v->block->array + (v->offset + (vsip_stride)(i) * v->stride) * v->block->rstride) = (s);} #define ROW(a,r,i) {r.block= a->block;r.offset = a->offset + i * a->col_stride; r.stride =a->row_stride; r.length=a->row_length;} #define COL(a,c,i) {c.block= a->block;c.offset = a->offset + i * a->row_stride; c.stride =a->col_stride; c.length=a->col_length;} static void swapEven(const vsip_vview_f *a, vsip_index i, vsip_index j){ vsip_scalar_f t = VGET(a,i); VPUT(a,i,VGET(a,j)); VPUT(a,j,t); } static void swapOdd(const vsip_vview_f *a, vsip_index i, vsip_index j){ vsip_scalar_f t = VGET(a,i); VPUT(a,i,VGET(a,j)); VPUT(a,j+1,t); } static void freqswap(const vsip_vview_f *a){ vsip_length N=a->length; vsip_length n; vsip_index i; if(N > 1){ if(N & 1){ /* odd */ vsip_scalar_f t = VGET(a,N-1); n = N/2 - 1; for(i=0; i<=n; i++) swapOdd(a,n-i,N-i-2); VPUT(a,N/2,t); } else { /* even */ n=N/2; for(i=0; i<N/2; i++) swapEven(a,i,i+n); } } } void vsip_mfreqswap_f(const vsip_mview_f *a){ vsip_vview_f a_r; vsip_vview_f a_c; { /* freqswap eo */ vsip_index i; for(i=0; i<a->col_length; i++){ ROW(a,a_r,i); freqswap(&a_r); } for(i=0; i<a->row_length; i++){ COL(a,a_c,i); freqswap(&a_c); } } } <file_sep>// // MainWindowController.swift // MatrixExplorer // // Created by <NAME> on 1/17/17. // Copyright © 2017 JVSIP. All rights reserved. // import Cocoa import SwiftVsip class MainWindowController: NSWindowController { var blk: Vsip.Block? var mtrx: Vsip.Matrix? @IBOutlet weak var size: NSTextField! @IBOutlet weak var block: NSTextView! @IBOutlet weak var matrix: NSTextField! @IBOutlet weak var offset: NSTextField! @IBOutlet weak var rowLength: NSTextField! @IBOutlet weak var rowStride: NSTextField! @IBOutlet weak var colLength: NSTextField! @IBOutlet weak var colStride: NSTextField! var blockLength: Int { return (blk?.length)! } override var windowNibName: String? { return "MainWindowController" } override func windowDidLoad() { super.windowDidLoad() self.offset.integerValue = 0 self.rowStride.integerValue = 0 self.colStride.integerValue = 0 self.rowLength.integerValue = 1 self.colLength.integerValue = 1 // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file. } var maxBlockIndex: Int { return (self.mtrx?.offset)! + ((self.mtrx?.columnLength)! - 1) * (self.mtrx?.rowStride)! + ((self.mtrx?.rowLength)! - 1) * (self.mtrx?.columnStride)! } var toLong: Bool { return maxBlockIndex > self.blockLength - 1 } var toShort: Bool { return maxBlockIndex < 0 } @IBAction func createBlock(sender: AnyObject) { self.blk = Vsip.Block(length: self.size.integerValue, type: .d) let v = self.blk?.vector().ramp(Vsip.Scalar(0.0), increment: Vsip.Scalar(1.0)) self.block.string = v?.mString("5.0") let m = Int(sqrt(Double(blockLength))) self.mtrx = Vsip.Matrix(block: self.blk!, offset: 0, columnStride: m, columnLength: m, rowStride: 1, rowLength: m) self.matrix.stringValue = (self.mtrx?.mString("5.0"))! self.rowLength.integerValue = m self.colLength.integerValue = m self.rowStride.integerValue = 1 self.colStride.integerValue = m self.offset.integerValue = 0 } @IBAction func setOffset(sender: AnyObject) { self.mtrx?.offset = self.offset.integerValue if !toLong && !toShort { self.matrix.stringValue = (self.mtrx?.mString("%5.0"))! } else { self.matrix.stringValue = toLong ? "Too Long" : "Too Short" } } @IBAction func setRowLength(sender: AnyObject) { self.mtrx?.rowLength = self.rowLength.integerValue if !toLong && !toShort { self.matrix.stringValue = (self.mtrx?.mString("5.0"))! } else { self.matrix.stringValue = toLong ? "Too Long" : "Too Short" } } @IBAction func setRowStride(sender: AnyObject) { self.mtrx?.rowStride = self.rowStride.integerValue if !toLong && !toShort { self.matrix.stringValue = (self.mtrx?.mString("5.0"))! } else { self.matrix.stringValue = toLong ? "Too Long" : "Too Short" } } @IBAction func setColLength(sender: AnyObject) { self.mtrx?.columnLength = self.colLength.integerValue if !toLong && !toShort { self.matrix.stringValue = (self.mtrx?.mString("5.0"))! } else { self.matrix.stringValue = toLong ? "Too Long" : "Too Short" } self.matrix.maximumNumberOfLines = self.colLength.integerValue } @IBAction func setColStride(sender: AnyObject) { self.mtrx?.columnStride = self.colStride.integerValue if !toLong && !toShort { self.matrix.stringValue = (self.mtrx?.mString("5.0"))! } else { self.matrix.stringValue = toLong ? "Too Long" : "Too Short" } } } <file_sep>/* Created RJudd September 18, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_tcreate_f.c,v 2.1 2004/09/21 02:07:25 judd Exp $ */ #define VI_TVIEW_F_ #include"VI_support_priv_f.h" #include"VI_blockcreate_f.h" #include"VI_blockdestroy_f.h" vsip_tview_f* vsip_tcreate_f( vsip_length zlength, vsip_length ylength, vsip_length xlength, vsip_tmajor major, vsip_memory_hint hint) { vsip_block_f *block; vsip_tview_f *tview; block = VI_blockcreate_f(zlength * ylength * xlength,hint); if(block == NULL) return (vsip_tview_f*) NULL; tview = VI_tview_f(); if(tview == NULL){ VI_blockdestroy_f(block); return tview; } tview->block = block; tview->offset = (vsip_offset)0; tview->x_length = xlength; tview->y_length = ylength; tview->z_length = zlength; if(major == VSIP_TRAILING){ tview->z_stride = xlength * ylength; tview->y_stride = xlength; tview->x_stride = 1; } else { /* VSIP_LEADING */ tview->x_stride = zlength * ylength; tview->y_stride = zlength; tview->z_stride = 1; } tview->markings = vsip_valid_structure_object; return tview; } <file_sep>/* // vsip_cmrandn_f.c // jvsipF // // Created by <NAME> on 9/14/13. // Copyright (c) 2013 Independent Consultant. All rights reserved. */ /********************************************************************* // This code includes no warranty, express or implied, including / // the warranties of merchantability and fitness for a particular / // purpose. / // No person or entity assumes any legal liability or responsibility / // for the accuracy, completeness, or usefulness of any information, / // apparatus, product, or process disclosed, or represents that / // its use would not infringe privately owned rights. / *********************************************************************/ /********************************************************************* // The MIT License (see copyright for jvsip in top level directory) // http://opensource.org/licenses/MIT **********************************************************************/ #include"VI_cmcolview_f.h" #include"VI_cmrowview_f.h" #include"vsip.h" #include"vsip_cvviewattributes_f.h" #include"vsip_vviewattributes_f.h" #include"vsip_randobject.h" static void cvrandn_f( vsip_randstate *state, const vsip_cvview_f *r) { if(state->type) { /* nonportable generator */ vsip_scalar_ue32 a = state->a, c = state->c, X = state->X; vsip_length n = r->length; /* register */ vsip_stride rst = r->stride * r->block->cstride; vsip_scalar_f *rpr = (r->block->R->array) + r->offset * r->block->cstride; vsip_scalar_f *rpi = (r->block->I->array) + r->offset * r->block->cstride; while(n-- > 0){ vsip_scalar_f t2; X = a * X + c; *rpr = (vsip_scalar_f)X/(vsip_scalar_f)4294967296.0; X = a * X + c; *rpr += (vsip_scalar_f)X/(vsip_scalar_f)4294967296.0; X = a * X + c; *rpr += (vsip_scalar_f)X/(vsip_scalar_f)4294967296.0; X = a * X + c; t2 = (vsip_scalar_f)X/(vsip_scalar_f)4294967296.0; X = a * X + c; t2 += (vsip_scalar_f)X/(vsip_scalar_f)4294967296.0; X = a * X + c; t2 += (vsip_scalar_f)X/(vsip_scalar_f)4294967296.0; *rpi = *rpr - t2; *rpr = 3 - t2 - *rpr; rpr += rst; rpi += rst; } state->X = X; } else { /* portable generator */ vsip_scalar_ue32 itemp; vsip_length n = r->length; /* register */ vsip_stride rst = r->stride * r->block->cstride; vsip_scalar_f *rpr = (r->block->R->array) + r->offset * r->block->cstride; vsip_scalar_f *rpi = (r->block->I->array) + r->offset * r->block->cstride; while(n-- > 0){ vsip_scalar_f t2; state->X = state->X * state->a + state->c; state->X1 = state->X1 * state->a1 + state->c1; itemp = state->X - state->X1; if(state->X1 == state->X2){ state->X1++; state->X2++; } itemp = (itemp>>8) | 0x00000001; *rpr = (vsip_scalar_f)itemp/(vsip_scalar_f)16777216.0; state->X = state->X * state->a + state->c; state->X1 = state->X1 * state->a1 + state->c1; itemp = state->X - state->X1; if(state->X1 == state->X2){ state->X1++; state->X2++; } itemp = (itemp>>8) | 0x00000001; *rpr += (vsip_scalar_f)itemp/(vsip_scalar_f)16777216.0; state->X = state->X * state->a + state->c; state->X1 = state->X1 * state->a1 + state->c1; itemp = state->X - state->X1; if(state->X1 == state->X2){ state->X1++; state->X2++; } itemp = (itemp>>8) | 0x00000001; *rpr += (vsip_scalar_f)itemp/(vsip_scalar_f)16777216.0; /* end t1 */ state->X = state->X * state->a + state->c; state->X1 = state->X1 * state->a1 + state->c1; itemp = state->X - state->X1; if(state->X1 == state->X2){ state->X1++; state->X2++; } itemp = (itemp>>8) | 0x00000001; t2 = (vsip_scalar_f)itemp/(vsip_scalar_f)16777216.0; state->X = state->X * state->a + state->c; state->X1 = state->X1 * state->a1 + state->c1; itemp = state->X - state->X1; if(state->X1 == state->X2){ state->X1++; state->X2++; } itemp = (itemp>>8) | 0x00000001; t2 += (vsip_scalar_f)itemp/(vsip_scalar_f)16777216.0; state->X = state->X * state->a + state->c; state->X1 = state->X1 * state->a1 + state->c1; itemp = state->X - state->X1; if(state->X1 == state->X2){ state->X1++; state->X2++; } itemp = (itemp>>8) | 0x00000001; t2 += (vsip_scalar_f)itemp/(vsip_scalar_f)16777216.0; /* end t2 */ *rpi = *rpr - t2; *rpr = 3 - t2 - *rpr; rpr += rst; rpi += rst; } } return; } void vsip_cmrandn_f( vsip_randstate *state, const vsip_cmview_f *A) { vsip_index i; vsip_cvview_f v; vsip_length M=A->col_length, N=A->row_length; vsip_stride CS=A->col_stride, RS=A->row_stride; if (CS < RS){ /* do by column */ for (i=0; i<N; i++){ VI_cmcolview_f(A,i,&v); cvrandn_f(state,&v); } } else { /* do by row */ for (i=0; i<M; i++){ VI_cmrowview_f(A,i,&v); cvrandn_f(state,&v); } } } <file_sep>// // support.h // jvsip_pp0 // // Created by <NAME> on 1/28/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #ifndef jvsip_pp0_support_h #define jvsip_pp0_support_h #include <cstring> extern "C"{ #include<vsip.h> } #include <iostream> #include <cassert> namespace vsip { using std::endl; using std::cout; using std::string; //block void create(vsip_block_f**b,vsip_length l){ *b=vsip_blockcreate_f(l,VSIP_MEM_NONE); assert(b != NULL); } void create(vsip_cblock_f**b,vsip_length l){ *b=vsip_cblockcreate_f(l,VSIP_MEM_NONE); assert(b != NULL); } void create(vsip_block_i**b,vsip_length l){ *b=vsip_blockcreate_i(l,VSIP_MEM_NONE); assert(b != NULL); } void create(vsip_block_vi**b,vsip_length l){ *b=vsip_blockcreate_vi(l,VSIP_MEM_NONE); assert(b != NULL); } void create(vsip_block_mi**b,vsip_length l){ *b=vsip_blockcreate_mi(l,VSIP_MEM_NONE); assert(b != NULL); } void create(vsip_block_d**b,vsip_length l){ *b=vsip_blockcreate_d(l,VSIP_MEM_NONE); assert(b != NULL); } void create(vsip_cblock_d**b,vsip_length l){ *b=vsip_cblockcreate_d(l,VSIP_MEM_NONE); assert(b != NULL); } void create(vsip_block_si**b,vsip_length l){ *b=vsip_blockcreate_si(l,VSIP_MEM_NONE); assert(b != NULL); } void create(vsip_block_uc**b,vsip_length l){ *b=vsip_blockcreate_uc(l,VSIP_MEM_NONE); assert(b != NULL); } // views // f void create(vsip_vview_f**v,vsip_length l){ vsip_block_f*b; create(&b,l); *v=vsip_vbind_f(b,0,1,l); assert(v != NULL); } vsip_vview_f* create(vsip_block_f*b, vsip_offset o, vsip_stride s, vsip_length l){ vsip_vview_f *v=vsip_vbind_f(b,o,s,l); assert(v != NULL); return v; } void create(vsip_mview_f**m,vsip_length cl,vsip_length rl){ vsip_block_f*b; create(&b,cl*rl); *m=vsip_mbind_f(b,0,rl,cl,1,rl); assert(m != NULL); } vsip_mview_f* create(vsip_block_f*b, vsip_offset o, vsip_stride cs, vsip_length cl,vsip_stride rs, vsip_length rl){ vsip_mview_f*m=vsip_mbind_f(b,o,cs,cl,rs,rl); assert(m != NULL); return m; } // cf void create(vsip_cvview_f**v,vsip_length l){ vsip_cblock_f*b; create(&b,l); *v=vsip_cvbind_f(b,0,1,l); assert(v != NULL); } vsip_cvview_f* create(vsip_cblock_f*b, vsip_offset o, vsip_stride s, vsip_length l){ vsip_cvview_f*v=vsip_cvbind_f(b,o,s,l); assert(v != NULL); return v; } void create(vsip_cmview_f**m,vsip_length cl,vsip_length rl){ vsip_cblock_f*b; create(&b,cl*rl); *m=vsip_cmbind_f(b,0,rl,cl,1,rl); assert(m != NULL); } vsip_cmview_f* create(vsip_cblock_f*b, vsip_offset o, vsip_stride cs, vsip_length cl,vsip_stride rs, vsip_length rl){ vsip_cmview_f*m=vsip_cmbind_f(b,o,cs,cl,rs,rl); assert(m != NULL); return m; } // d void create(vsip_vview_d**v,vsip_length l){ vsip_block_d*b; create(&b,l); *v=vsip_vbind_d(b,0,1,l); assert(v != NULL); } vsip_vview_d* create(vsip_block_d*b, vsip_offset o, vsip_stride s, vsip_length l){ vsip_vview_d *v=vsip_vbind_d(b,o,s,l); assert(v != NULL); return v; } void create(vsip_mview_d**m,vsip_length cl,vsip_length rl){ vsip_block_d*b; create(&b,cl*rl); *m=vsip_mbind_d(b,0,rl,cl,1,rl); assert(m != NULL); } vsip_mview_d* create(vsip_block_d*b, vsip_offset o, vsip_stride cs, vsip_length cl,vsip_stride rs, vsip_length rl){ vsip_mview_d*m=vsip_mbind_d(b,o,cs,cl,rs,rl); assert(m != NULL); return m; } // cd void create(vsip_cvview_d**v,vsip_length l){ vsip_cblock_d*b; create(&b,l); *v=vsip_cvbind_d(b,0,1,l); assert(v != NULL); } vsip_cvview_d* create(vsip_cblock_d*b, vsip_offset o, vsip_stride s, vsip_length l){ vsip_cvview_d*v=vsip_cvbind_d(b,o,s,l); assert(v != NULL); return v; } void create(vsip_cmview_d**m,vsip_length cl,vsip_length rl){ vsip_cblock_d*b; create(&b,cl*rl); *m=vsip_cmbind_d(b,0,rl,cl,1,rl); assert(m != NULL); } vsip_cmview_d* create(vsip_cblock_d*b, vsip_offset o, vsip_stride cs, vsip_length cl,vsip_stride rs, vsip_length rl){ vsip_cmview_d*m=vsip_cmbind_d(b,o,cs,cl,rs,rl); assert(m != NULL); return m; } // i void create(vsip_vview_i**v,vsip_length l){ vsip_block_i*b; create(&b,l); *v=vsip_vbind_i(b,0,1,l); assert(v != NULL); } vsip_vview_i* create(vsip_block_i*b, vsip_offset o, vsip_stride s, vsip_length l){ vsip_vview_i *v=vsip_vbind_i(b,o,s,l); assert(v != NULL); return v; } void create(vsip_mview_i**m,vsip_length cl,vsip_length rl){ vsip_block_i*b; create(&b,cl*rl); *m=vsip_mbind_i(b,0,rl,cl,1,rl); assert(m != NULL); } vsip_mview_i* create(vsip_block_i*b, vsip_offset o, vsip_stride cs, vsip_length cl,vsip_stride rs, vsip_length rl){ vsip_mview_i*m=vsip_mbind_i(b,o,cs,cl,rs,rl); assert(m != NULL); return m; } // si void create(vsip_vview_si**v,vsip_length l){ vsip_block_si*b; create(&b,l); *v=vsip_vbind_si(b,0,1,l); assert(v != NULL); } vsip_vview_si* create(vsip_block_si*b, vsip_offset o, vsip_stride s, vsip_length l){ vsip_vview_si *v=vsip_vbind_si(b,o,s,l); assert(v != NULL); return v; } void create(vsip_mview_si**m,vsip_length cl,vsip_length rl){ vsip_block_si*b; create(&b,cl*rl); *m=vsip_mbind_si(b,0,rl,cl,1,rl); assert(m != NULL); } vsip_mview_si* create(vsip_block_si*b, vsip_offset o, vsip_stride cs, vsip_length cl,vsip_stride rs, vsip_length rl){ vsip_mview_si*m=vsip_mbind_si(b,o,cs,cl,rs,rl); assert(m != NULL); return m; } //uc void create(vsip_vview_uc**v,vsip_length l){ vsip_block_uc*b; create(&b,l); *v=vsip_vbind_uc(b,0,1,l); assert(v != NULL); } vsip_vview_uc* create(vsip_block_uc*b, vsip_offset o, vsip_stride s, vsip_length l){ vsip_vview_uc *v=vsip_vbind_uc(b,o,s,l); assert(v != NULL); return v; } void create(vsip_mview_uc**m,vsip_length cl,vsip_length rl){ vsip_block_uc*b; create(&b,cl*rl); *m=vsip_mbind_uc(b,0,rl,cl,1,rl); assert(m != NULL); } vsip_mview_uc* create(vsip_block_uc*b, vsip_offset o, vsip_stride cs, vsip_length cl,vsip_stride rs, vsip_length rl){ vsip_mview_uc*m=vsip_mbind_uc(b,o,cs,cl,rs,rl); assert(m != NULL); return m; } //vi void create(vsip_vview_vi**v,vsip_length l){ vsip_block_vi*b; create(&b,l); *v=vsip_vbind_vi(b,0,1,l); assert(v != NULL); } vsip_vview_vi* create(vsip_block_vi*b, vsip_offset o, vsip_stride s, vsip_length l){ vsip_vview_vi *v=vsip_vbind_vi(b,o,s,l); assert(v != NULL); return v; } //fft_f void create(string typ, vsip_fft_f** fftObj){ if(typ=="cc"){ }else if(typ=="cr"){ }else if(typ=="rc"){ } } //rand //block destroy void destroy(vsip_block_f* b){vsip_blockdestroy_f(b);b=nullptr;} void destroy(vsip_cblock_f* b){vsip_cblockdestroy_f(b);b=nullptr;} void destroy(vsip_block_d* b){vsip_blockdestroy_d(b);b=nullptr;} void destroy(vsip_cblock_d* b){vsip_cblockdestroy_d(b);b=nullptr;} void destroy(vsip_block_i* b){vsip_blockdestroy_i(b);b=nullptr;} void destroy(vsip_block_vi* b){vsip_blockdestroy_vi(b);b=nullptr;} void destroy(vsip_block_mi* b){vsip_blockdestroy_mi(b);b=nullptr;} void destroy(vsip_block_si* b){vsip_blockdestroy_si(b);b=nullptr;} void destroy(vsip_block_uc* b){vsip_blockdestroy_uc(b);b=nullptr;} void destroy(vsip_block_f** b,vsip_vview_f*v){*b=vsip_vdestroy_f(v);v=nullptr;} void destroy(vsip_vview_f*v) {vsip_vdestroy_f(v);v=nullptr;} void destroy(vsip_block_f** b,vsip_mview_f*v){*b=vsip_mdestroy_f(v);v=nullptr;} void destroy(vsip_mview_f*v) {vsip_mdestroy_f(v);v=nullptr;} void destroy(vsip_cblock_f** b,vsip_cvview_f*v){*b=vsip_cvdestroy_f(v);v=nullptr;} void destroy(vsip_cvview_f*v) {vsip_cvdestroy_f(v);v=nullptr;} void destroy(vsip_cblock_f** b,vsip_cmview_f*v){*b=vsip_cmdestroy_f(v);v=nullptr;} void destroy(vsip_cmview_f*v) {vsip_cmdestroy_f(v);v=nullptr;} void destroy(vsip_block_d** b,vsip_vview_d*v){*b=vsip_vdestroy_d(v);v=nullptr;} void destroy(vsip_vview_d*v) {vsip_vdestroy_d(v);v=nullptr;} void destroy(vsip_block_d** b,vsip_mview_d*v){*b=vsip_mdestroy_d(v);v=nullptr;} void destroy(vsip_mview_d*v) {vsip_mdestroy_d(v);v=nullptr;} void destroy(vsip_cblock_d** b,vsip_cvview_d*v){*b=vsip_cvdestroy_d(v);v=nullptr;} void destroy(vsip_cvview_d*v) {vsip_cvdestroy_d(v);v=nullptr;} void destroy(vsip_cblock_d** b,vsip_cmview_d*v){*b=vsip_cmdestroy_d(v);v=nullptr;} void destroy(vsip_cmview_d*v) {vsip_cmdestroy_d(v);v=nullptr;} void destroy(vsip_block_i** b, vsip_vview_i *v){*b = vsip_vdestroy_i(v);v=nullptr;} void destroy(vsip_block_vi** b, vsip_vview_vi *v){*b = vsip_vdestroy_vi(v);v=nullptr;} void destroy(vsip_block_si** b, vsip_vview_si *v){*b = vsip_vdestroy_si(v);v=nullptr;} void destroy(vsip_block_uc** b, vsip_vview_uc *v){*b = vsip_vdestroy_uc(v);v=nullptr;} void destroy(vsip_vview_i *v){vsip_vdestroy_i(v);v=nullptr;} void destroy(vsip_vview_vi *v){vsip_vdestroy_vi(v);v=nullptr;} void destroy(vsip_vview_si *v){vsip_vdestroy_si(v);v=nullptr;} void destroy(vsip_mview_uc *v){vsip_mdestroy_uc(v);v=nullptr;} void destroy(vsip_mview_i *v){vsip_mdestroy_i(v);v=nullptr;} void destroy(vsip_mview_si *v){vsip_mdestroy_si(v);v=nullptr;} vsip_vview_f * realview(vsip_vview_f **rv,vsip_cvview_f*cv){ *rv = vsip_vrealview_f(cv); return *rv; } vsip_vview_f *realview(vsip_cvview_f *cv){ return vsip_vrealview_f(cv); } vsip_vview_f * imagview(vsip_vview_f **rv,vsip_cvview_f*cv){ *rv = vsip_vimagview_f(cv); return *rv; } vsip_vview_f *imagview(vsip_cvview_f *cv){ return vsip_vimagview_f(cv); } vsip_vview_d * realview(vsip_vview_d **rv,vsip_cvview_d*cv){ *rv = vsip_vrealview_d(cv); return *rv; } vsip_vview_d *realview(vsip_cvview_d *cv){ return vsip_vrealview_d(cv); } vsip_vview_d * imagview(vsip_vview_d **rv,vsip_cvview_d*cv){ *rv = vsip_vimagview_d(cv); return *rv; } vsip_vview_d *imagview(vsip_cvview_d *cv){ return vsip_vimagview_d(cv); } float get(vsip_vview_f *v,vsip_index i){ return (float) vsip_vget_f(v,i); } float get(vsip_mview_f *v,vsip_index r, vsip_index c){ return (float)vsip_mget_f(v,r,c); } vsip_cscalar_f get(vsip_cvview_f *v,vsip_index i){ vsip_cscalar_f ans = vsip_cvget_f(v,i); return ans; } vsip_cscalar_f get(vsip_cmview_f *v,vsip_index r, vsip_index c){ vsip_cscalar_f ans = vsip_cmget_f(v,r,c); return ans; } int get(vsip_vview_i *v,vsip_index i){ return (int) vsip_vget_i(v,i); } int get(vsip_mview_i *v,vsip_index r, vsip_index c){ return (int)vsip_mget_i(v,r,c); } short get(vsip_vview_si *v,vsip_index i){ vsip_scalar_si ans = vsip_vget_si(v,i); return ans; } short get(vsip_mview_si *v,vsip_index r, vsip_index c){ return (short)vsip_mget_si(v,r,c); } vsip_index get(vsip_vview_vi *v,vsip_index i){ vsip_index ans = vsip_vget_vi(v,i); return ans; } float get(vsip_vview_d *v,vsip_index i){ return (float) vsip_vget_d(v,i); } float get(vsip_mview_d *v,vsip_index r, vsip_index c){ return (float)vsip_mget_d(v,r,c); } vsip_cscalar_d get(vsip_cvview_d *v,vsip_index i){ vsip_cscalar_d ans = vsip_cvget_d(v,i); return ans; } vsip_cscalar_d get(vsip_cmview_d *v,vsip_index r, vsip_index c){ vsip_cscalar_d ans = vsip_cmget_d(v,r,c); return ans; } // size() vsip_length vlength(vsip_vview_i*v){return vsip_vgetlength_i(v);} vsip_length vlength(vsip_vview_si*v){return vsip_vgetlength_si(v);} vsip_length vlength(vsip_vview_vi*v){return vsip_vgetlength_vi(v);} vsip_length vlength(vsip_vview_f*v){return vsip_vgetlength_f(v);} vsip_length rlength(vsip_mview_f*v){return vsip_mgetrowlength_f(v);} vsip_length clength(vsip_mview_f*v){return vsip_mgetcollength_f(v);} vsip_length vlength(vsip_cvview_f*v){return vsip_cvgetlength_f(v);} vsip_length rlength(vsip_cmview_f*v){return vsip_cmgetrowlength_f(v);} vsip_length clength(vsip_cmview_f*v){return vsip_cmgetcollength_f(v);} vsip_length vlength(vsip_vview_d*v){return vsip_vgetlength_d(v);} vsip_length rlength(vsip_mview_d*v){return vsip_mgetrowlength_d(v);} vsip_length clength(vsip_mview_d*v){return vsip_mgetcollength_d(v);} vsip_length vlength(vsip_cvview_d*v){return vsip_cvgetlength_d(v);} vsip_length rlength(vsip_cmview_d*v){return vsip_cmgetrowlength_d(v);} vsip_length clength(vsip_cmview_d*v){return vsip_cmgetcollength_d(v);} vsip_length rlength(vsip_mview_i*v){return vsip_mgetrowlength_i(v);} vsip_length rlength(vsip_mview_si*v){return vsip_mgetrowlength_si(v);} vsip_length clength(vsip_mview_i*v){return vsip_mgetcollength_i(v);} vsip_length clength(vsip_mview_si*v){return vsip_mgetcollength_si(v);} void mprint(vsip_vview_vi* v){ for(vsip_length i=0; i<vlength(v); i++) cout<<get(v,i)<<";\n"; } void mprint(vsip_vview_i* v){ for(vsip_length i=0; i<vlength(v); i++) cout<<get(v,i)<<";\n"; } void mprint(vsip_vview_f* v){ for(vsip_length i=0; i<vlength(v); i++) cout<<get(v,i)<<";\n"; } void mprint(vsip_cvview_f* v){ for(vsip_length i=0; i<vlength(v); i++){ vsip_cscalar_f ans=get(v,i); cout << "(" << ans.r << ", " << ans.i << ");\n"; } } void mprint(vsip_mview_f* v){ for(vsip_length i=0; i<rlength(v); i++){ for(vsip_length j=0; j<clength(v); j++){ cout << get(v,i,j)<<"; "; } cout << endl; } } void mprint(vsip_cmview_f* v){ for(vsip_length i=0; i<rlength(v); i++){ for(vsip_length j=0; j<clength(v); j++){ vsip_cscalar_f ans=get(v,i,j); cout << "(" << ans.r << ", " << ans.i << "); "; } cout << endl; } } void mprint(vsip_vview_d* v){ for(vsip_length i=0; i<vlength(v); i++) cout<<get(v,i)<<";\n"; } void mprint(vsip_cvview_d* v){ for(vsip_length i=0; i<vlength(v); i++){ vsip_cscalar_d ans=get(v,i); cout << "(" << ans.r << ", " << ans.i << ");\n"; } } void mprint(vsip_mview_d* v){ vsip_length rl=rlength(v),cl=clength(v); for(vsip_length i=0; i<rl; i++){ for(vsip_length j=0; j<cl; j++){ cout << get(v,i,j)<<"; "; } cout << endl; } } void mprint(vsip_cmview_d* v){ vsip_length rl=rlength(v),cl=clength(v); for(vsip_length i=0; i<rl; i++){ if(i==0) cout << "["; for(vsip_length j=0; j<cl; j++){ vsip_cscalar_d ans=get(v,i,j); cout << "(" << ans.r << ", " << ans.i << "); "; } if(i==rl) cout << "]"; cout << endl; } } } #endif <file_sep>## Created RJudd ## <NAME> Diego ## $Id: Makefile,v 2.0 2003/02/22 15:27:21 judd Exp $ ## Top Level of library distribution ## RDIR=$(HOME)/local RDIR=../.. ## C compiler CC=cc INCLUDEDIR=-I$(RDIR)/include LIBDIR=-L$(RDIR)/lib LIBS= -lvsip -lm OPTIONS=-O2 example: example1.c $(CC) -o example1 example1.c $(OPTIONS) $(INCLUDEDIR) $(LIBDIR) $(LIBS) clean: rm -f example1 example1.exe <file_sep>/* Created <NAME> 2013*/ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /********************************************************************* // The MIT License (see copyright for jvsip in top level directory) // http://opensource.org/licenses/MIT **********************************************************************/ #include<vsip.h> typedef struct {vsip_index i; vsip_index j;} svdCorner; typedef struct {vsip_scalar_f c; vsip_scalar_f s; vsip_scalar_f r;}givensObj_f ; typedef struct {vsip_vview_f* t; vsip_vview_f* ts; vsip_mview_f* B; vsip_mview_f* Bs; vsip_vview_f* bs; vsip_mview_f* L; vsip_mview_f* Ls; vsip_vview_f* ls_one; vsip_vview_f* ls_two; vsip_vview_f* d; vsip_vview_f* ds; vsip_vview_f* f; vsip_vview_f* fs; vsip_mview_f* R; vsip_mview_f* Rs; vsip_vview_f* rs_one; vsip_vview_f *rs_two; vsip_scalar_f eps0;int init; vsip_vview_vi *indx_L; vsip_vview_vi *indx_R;} svdObj_f; svdObj_f *svdInit_f(vsip_length, vsip_length); void svdFinalize_f(svdObj_f*); svdObj_f *svd_f(vsip_mview_f*); <file_sep>import Foundation import vsip public func oddNumber(_ n: Int) -> Bool { let b = n % 2 return b == 1 } public func VU_vfrdB_d(_ a: OpaquePointer,_ range: Double) -> Int { var ret = 0 let N_len = vsip_length(vsip_vgetlength_d(a)) var ca: OpaquePointer?, ia: OpaquePointer?, ra: OpaquePointer?, ta: OpaquePointer? var fft: OpaquePointer? if let t = vsip_cvcreate_d(N_len,VSIP_MEM_NONE) { ca = t } else { ret = 1 } if let t = vsip_ccfftip_create_d(N_len,1,VSIP_FFT_FWD,0,vsip_alg_hint(rawValue: 0)){ fft = t } else { ret = 1 } if let t = vsip_vrealview_d(ca) { ra = t }else { ret = 1 } if let t = vsip_vimagview_d(ca){ ia = t }else { ret = 1 } if let t = vsip_vcloneview_d(a) { ta = t }else { ret = 1 } if ret == 0 { let s = vsip_offset(vsip_vgetstride_d(ta)) vsip_vfill_d(0,ia); vsip_vcopy_d_d(a,ra) vsip_ccfftip_d(fft,ca) vsip_vcmagsq_d(ca,ra) var ind: vsip_index = 0 let max = vsip_vmaxval_d(ra,&ind) let min = max * range vsip_vclip_d(ra,min,max,min,max,ra) if oddNumber(Int(N_len)) { let Nlen = vsip_length( N_len/2) vsip_vputlength_d(ta,Nlen+1) vsip_vputlength_d(ra,Nlen+1) vsip_vputoffset_d(ta,Nlen * s) vsip_vcopy_d_d(ra,ta) vsip_vputlength_d(ra,Nlen) vsip_vputlength_d(ta,Nlen) vsip_vputoffset_d(ta,vsip_vgetoffset_d(a)) vsip_vputoffset_d(ra,Nlen+1) vsip_vcopy_d_d(ra,ta) } else { let Nlen = vsip_length( N_len/2) vsip_vcopy_d_d(ra,ta) vsip_vputlength_d(ta,Nlen) vsip_vputlength_d(a,Nlen) vsip_vputoffset_d(ta,(vsip_offset)(Nlen) * s) vsip_vswap_d(ta,a); vsip_vputlength_d(a,N_len) } vsip_vlog10_d(a,a) vsip_svmul_d(10,a,a) } vsip_fft_destroy_d(fft) vsip_vdestroy_d(ra) vsip_vdestroy_d(ia) vsip_cvalldestroy_d(ca) vsip_vdestroy_d(ta) return ret } <file_sep>import pyJvsip as pv from math import sqrt from svdBidiag import svdBidiag def svdCorners(f): j=f.length-1 while j > 0 and f[j] == 0.0: j-=1 if(j == 0 and f[j] == 0.0): i=0 else: i = j while i > 0 and f[i] != 0.0: i -= 1 if i==0 and f[0] == 0.0: i = 1 j += 2 elif i == 0 and f[0] != 0.0: i = 0 j += 2 else: i += 1 j += 2 return (i,j) def givensCoef(x1, x2): a=abs(x1);b=abs(x2) if x2 == 0.0: return(1.0,0.0,x1) elif a < b: t = x1/x2 t = b * sqrt(1.0 + t * t) else: t=x2/x1 t = a * sqrt(1.0 + t * t) if (x1 == 0.0): c=0.0 if x2 < 0: s = -1.0 else: s = 1.0 return(c,s,t) else: s = x2/t c = abs(x1)/t if x1 < 0: s = -s t=-t return(c,s,t) def prodG(L,i,j,c,s): a1= L.colview(i) a2= L.colview(j) t = c * a1 + s * a2 a2[:]= c * a2 - s * a1 a1[:]= t def gtProd(i,j,c,s,R): a1= R.rowview(i) a2= R.rowview(j) t= c * a1 + s * a2 a2[:]=c * a2 - s * a1 a1[:]=t def zeroRow(L,d,f): n = d.length xd=d[0] xf=f[0] c,s,r=givensCoef(xd,xf) if n == 1: d[0]=r f[0]=0.0 prodG(L,n,0,c,s) else: d[0]=r f[0]=0.0 xf=f[1] t= -xf * s; xf *= c f[1]=xf prodG(L,1,0,c,s); for i in range(1,n-1): xd=d[i] c,s,r=givensCoef(xd,t) prodG(L,i+1,0,c,s) d[i]=r xf=f[i+1] t=-xf * s; xf *= c f[i+1]=xf xd=d[n-1] c,s,r=givensCoef(xd,t) d[n-1]=r prodG(L,n,0,c,s) def zeroCol(d,f,R): n = f.length if n == 1: c,s,r=givensCoef(d[0],f[0]); d[0]=r; f[0]=0.0; gtProd(0,1,c,s,R) elif n == 2: xd=d[1] xf=f[1] c,s,r=givensCoef(xd,xf) d[1]= r f[1]=0.0 xf=f[0] t= -xf * s; xf *= c; f[0]=xf; gtProd(1,2,c,s,R); xd=d[0] c,s,r=givensCoef(xd,t); d[0]=r; gtProd(0,2,c,s,R); else: i=n-1; j=i-1; k=i xd=d[i] xf=f[i] c,s,r=givensCoef(xd,xf); xf=f[j] d[i]=r; f[i]=0.0; t=-xf*s; xf*=c f[j]=xf; gtProd(i,k+1,c,s,R); while i > 1: i = j; j = i-1; xd=d[i] c,s,r=givensCoef(xd,t); d[i]=r; xf=f[j] t= -xf * s; xf *= c; f[j]=xf; gtProd(i,k+1,c,s,R); xd=d[0] c,s,r=givensCoef(xd,t) d[0]=r gtProd(0,k+1,c,s,R) def zeroFind(d,eps0): j = d.length xd = d[j-1] while xd > eps0: if j > 1: j -= 1 xd=d[j-1] elif j==1: j -= 1 return 0 d[j-1]=0.0 return j def svdMu(d2,f1,d3,f2, eps0): cu=d2 * d2 + f1 * f1 cl=d3 * d3 + f2 * f2 cd = d2 * f2; T = (cu + cl) D = 4*(cu * cl - cd * cd)/(T*T) if D >= 1.0: root = 0.0 else: root = T * sqrt(1.0 - D) lambda1 = (T + root)/(2.) lambda2 = (T - root)/(2.) c1=abs(lambda1-cl) c2=abs(lambda2-cl) if(root == 0.0): if f2 < (d2 + d3) * eps0: f2=0.0 if(c1 < c2): mu = lambda1 else: mu = lambda2 return (mu, f2) def checksvd(L,d,f,R): B=pv.create(L.type,L.collength,R.rowlength).fill(0.0) if 'cmview' in B.type: b=B.realview.diagview else: b=B.diagview b(0)[:]=d b(1)[:]=f L.prod(B).prod(R).mprint('%.3f') def svdStep(L,d,f,R, eps0): n = d.length mu=0.0; x1=0.0; x2=0.0; t=0.0 d2=0.0; f1=0.0; d3=0.0; f2=0.0 assert n > 1, 'Error. d.length for svdStep must be at least 2' if n >= 3: d2=d[n-2];f1= f[n-3];d3 = d[n-1];f2= f[n-2] else: d2=d[0]; d3=d[1]; f1=0.0; f2=f[0] mu, f2 = svdMu(d2, f1, d3, f2, eps0) if(f2 == 0.0): f[n-2] = 0.0 x1=d[0] x2 = x1 * f[0] x1 *= x1; x1 -= mu c,s,r=givensCoef(x1,x2) x1=d[0];x2=f[0] f[0]=c*x2-s*x1 d[0]=c*x1+s*x2 t=d[1] d[1] *= c t *= s gtProd(0,1,c,s,R) for i in range(n-2): j=i+1; k=i+2 c,s,r = givensCoef(d[i],t) d[i]=r x1=d[j]*c x2=f[i]*s t= x1 - x2 x1=f[i] * c x2=d[j] * s f[i] = x1+x2 d[j] = t x1=f[j] t=s * x1 f[j]=x1*c prodG(L,i, j, c, s) c,s,r=givensCoef(f[i],t) f[i]=r x1=d[j]; x2=f[j] d[j]=c * x1 + s * x2; f[j]=c * x2 - s * x1 x1=d[k] t=s * x1; d[k]=x1*c gtProd(j,k, c, s,R) i=n-2; j=n-1 c,s,r = givensCoef(d[i],t) d[i] = r x1=d[j]*c; x2=f[i]*s t=x1 - x2 x1 = f[i] * c; x2=d[j] * s f[i] = x1+x2 d[j] = t prodG(L,i, j, c, s) def phaseCheck(L,d,f,R,eps0): nf=f.length; for i in range(d.length): ps=d[i] m = abs(ps) if(m >= eps0) and ps < 0.0: L.colview(i).neg d[i]=m; if (i < nf): f[i] = -f[i] elif m < eps0: d[i]=0.0 for i in range(nf): if abs(f[i]) < (d[i] + d[i+1]) * eps0: f[i]=0.0 def svdIteration(L0,d0,f0,R0,eps0): """ Iterate so that d0 will contain singular values of a matrix A and f0 will be all zeroes. Usage: L,d,R = svdIteration(L0,d0,f0,R0,eps0) Where: Assuming a decompostion of matrix A A = L0.prod(D0).prod(R0) and D0.diagview(0).realview[:]=d0 D0.diagview(1).realview[:]=f0 other entries of D0 are zero. eps0 is a small number representing zero for the iteration process. Returns L,d,R such that A = L.prod(D).prod(R) D compliant with L and R for matrix product D.diagview(0).realview[:]=d other entries of D are zero. """ cntr=0.0 maxcntr = 5 * d0.length while (cntr < maxcntr): cntr += 1 i,j=svdCorners(f0) if (j == 0): break d=d0[i:j]; f=f0[i:j-1] L=L0[:,i:j];R=R0[i:j,:] n=f.length k=zeroFind(d,eps0) if (k > 0 ): k=k-1; if(d[n] == 0.0): zeroCol(d,f,R); else: L=L[:,k:] d.putlength(d.length-(k+1)) d.putoffset(d.offset+k+1) f.putlength(f.length - k) f.putoffset(f.offset + k) zeroRow(L,d,f) else: svdStep(L,d,f,R, eps0) phaseCheck(L0,d0,f0,R0,eps0) return (L0,d0,R0) <file_sep>#!/usr/bin/env python """ setup.py file for numpy jvsip utilities module """ from distutils.core import setup, Extension setup (name = 'jvsipNumpy', version = '0.1', author = "<NAME>", description = """Numpy Utilities for Use in pyJvsip""", ext_modules = [Extension('_jvsipNumpyUtils', sources=['./numpyArrayCopies.c', './jvsipNumpyUtils_wrap.c'], include_dirs=['./','../../../c_VSIP_src']), ], py_modules = ["jvsipNumpyUtils","jvsipNumpy"], ) <file_sep>/* Created by RJudd July 13, 2002 */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_ccfftmop_f_def.h,v 2.0 2003/02/22 15:18:30 judd Exp $ */ #ifndef _VI_CCFFTMOP_F_DEF_H #define _VI_CCFFTMOP_F_DEF_H #include"VI_cmcopy_f_f.h" #include"VI_fftm_building_blocks_f.h" void vsip_ccfftmop_f(const vsip_fftm_f *Offt, const vsip_cmview_f *x, const vsip_cmview_f *y) { vsip_fftm_f Nfft = *Offt; vsip_fftm_f *fftm = &Nfft; VI_cmcopy_f_f(x,y); fftm->type = VSIP_CCFFTIP; VI_ccfftmip_f(fftm,y); } #endif /* _VI_CCFFTMOP_F_DEF_H */ <file_sep>from vsip import * ## for this file we append bb_ before functions to avoid python keywords def __isSizeCompatible(a,b): if 'mview' in a.type and 'mview' in b.type: if (a.rowlength == b.rowlength) and (a.collength == b.collength): return True elif 'vview' in a.type and 'vview' in b.type: if a.length == b.length: return True else: return False #vsip_sand_p def bb_and(a,b,c): """ Bitwise and Boolean and (bb_and). See VSIPL and function """ f={'mview_imview_imview_i':vsip_mand_i, 'mview_simview_simview_si':vsip_mand_si, 'vview_blvview_blvview_bl':vsip_vand_bl, 'vview_ivview_ivview_i':vsip_vand_i, 'vview_sivview_sivview_si':vsip_vand_si, 'vview_ucvview_ucvview_uc':vsip_vand_uc} assert __isSizeCompatible(a,b) and __isSizeCompatible(a,c),\ 'Size error in function and' t=a.type+b.type+c.type assert t in f, 'Type <:'+t+':> not supported for function bb_and.' f[t](a.vsip,b.vsip,c.vsip) return c #vsip_snot_p def bb_not(a,b): """ Bitwise and Boolean and (bb_not). See VSIPL not function """ f={'vview_blvview_bl':vsip_vnot_bl, 'vview_ivview_i':vsip_vnot_i, 'vview_sivview_si':vsip_vnot_si, 'vview_ucvview_uc':vsip_vnot_uc} assert __isSizeCompatible(a,b),'Size error in function bb_not' t=a.type+b.type assert t in f, 'Type <:'+t+':> not supported for function not.' f[t](a.vsip,b.vsip) return b #vsip_sor_p def bb_or(a,b,c): """ Bitwise and Boolean and (bb_or). See VSIPL or function """ f={'vview_blvview_blvview_bl':vsip_vor_bl, 'vview_ivview_ivview_i':vsip_vor_i, 'vview_sivview_sivview_si':vsip_vor_si, 'vview_ucvview_ucvview_uc':vsip_vor_uc} assert __isSizeCompatible(a,b) and __isSizeCompatible(a,c),\ 'Size error in function or' t=a.type+b.type+c.type assert t in f, 'Type <:'+t+':> not supported for function or.' f[t](a.vsip,b.vsip,c.vsip) return c #vsip_sxor_p def bb_xor(a,b,c): """ Bitwise and Boolean and (bb_xor). See VSIPL xor function """ f={'vview_ivview_ivview_i':vsip_vxor_i, 'vview_sivview_sivview_si':vsip_vxor_si, 'vview_ucvview_ucvview_uc':vsip_vxor_uc, 'vview_blvview_blvview_bl':vsip_vxor_bl} assert __isSizeCompatible(a,b) and __isSizeCompatible(a,c),\ 'Size error in function xor' t=a.type+b.type+c.type assert t in f, 'Type <:'+t+':> not supported for function xor.' f[t](a.vsip,b.vsip,c.vsip) return c<file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mget_put_si.h,v 2.0 2003/02/22 15:23:34 judd Exp $ */ static void mget_put_si(void){ printf("********\nTEST mget_put_si\n"); { vsip_scalar_si data_a[] = { 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1}; vsip_scalar_si ans[6][2] = {{ 0, 1},{ 1, 0},{ 1, 0},{ 1, 0},{ 0, 1},{ 0, 1}}; vsip_block_si *block_a = vsip_blockbind_si(data_a,12,VSIP_MEM_NONE); vsip_mview_si *a = vsip_mbind_si(block_a,0,2,6,1,2); vsip_block_si *block_b = vsip_blockcreate_si(50,VSIP_MEM_NONE); vsip_mview_si *b = vsip_mbind_si(block_b,5,5,6,2,2); vsip_index i,j; vsip_blockadmit_si(block_a,VSIP_TRUE); /* copy <a> into <b> */ for(i=0; i<6; i++) for(j=0; j<2; j++) vsip_mput_si(b,i,j,vsip_mget_si(a,i,j)); /* check <a> against ans */ printf("check unit stride compact view\n"); for(i=0; i<6; i++) for(j=0; j<2; j++) { vsip_scalar_si chk = (ans[i][j] - vsip_mget_si(a,i,j)); (chk == 0) ? printf("correct\n") : printf("error\n"); fflush(stdout); } printf("check general stride view\n"); for(i=0; i<6; i++) for(j=0; j<2; j++){ vsip_scalar_si chk = (ans[i][j] - vsip_mget_si(b,i,j)); (chk == 0) ? printf("correct\n") : printf("error\n"); fflush(stdout); } vsip_malldestroy_si(a); vsip_malldestroy_si(b); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mrecip_f.h,v 2.0 2003/02/22 15:23:26 judd Exp $ */ #include"VU_mprintm_f.include" static void mrecip_f(void){ printf("\n*******\nTEST mrecip_f\n\n"); { vsip_scalar_f data[] = {M_PI/8.0, M_PI/4.0, M_PI/3.0, M_PI/1.5, 1.25 * M_PI, 1.75 * M_PI}; vsip_scalar_f ans[] = {8.0/M_PI, 4.0/M_PI, 3.0/M_PI,1.5/M_PI, 1.0/(M_PI*1.25), 1.0/(M_PI*1.75)}; vsip_block_f *block = vsip_blockbind_f(data,6,VSIP_MEM_NONE); vsip_block_f *ans_block = vsip_blockbind_f(ans,6,VSIP_MEM_NONE); vsip_mview_f *a = vsip_mbind_f(block,0,2,3,1,2); vsip_mview_f *ansm = vsip_mbind_f(ans_block,0,2,3,1,2); vsip_mview_f *b = vsip_mcreate_f(3,2,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *chk = vsip_mcreate_f(3,2,VSIP_COL,VSIP_MEM_NONE); vsip_blockadmit_f(block,VSIP_TRUE); vsip_blockadmit_f(ans_block,VSIP_TRUE); printf("test out of place, compact, user \"a\", vsipl \"b\"\n"); vsip_mrecip_f(a,b); printf("mrecip_f(a,b)\n matrix a\n");VU_mprintm_f("8.6",a); printf("matrix b\n");VU_mprintm_f("8.6",b); printf("answer\n");VU_mprintm_f("8.4",ansm); vsip_msub_f(b,ansm,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check mrecip_f in place\n"); vsip_mrecip_f(a,a); vsip_msub_f(a,ansm,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_f(a); vsip_malldestroy_f(b); vsip_malldestroy_f(chk); vsip_malldestroy_f(ansm); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mrowindex.h,v 2.1 2009/09/05 18:01:45 judd Exp $ */ static void mrowindex(void){ printf("********\nTEST mrowindex\n"); { vsip_scalar_vi a_r = 2; vsip_scalar_vi a_c = 3; vsip_scalar_mi a = vsip_matindex(a_r,a_c); vsip_scalar_vi row = vsip_rowindex(a); printf(" %u = vsip_mrowindex((%2u,%2u))\n",(unsigned)row,(unsigned)a.r,(unsigned)a.c); ((row == a_r)) ? printf("correct\n") : printf("error\n"); fflush(stdout); } } /* done */ <file_sep>/* Created <NAME> */ /* Retired */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cmprod3_d.c,v 2.1 2006/04/27 01:58:00 judd Exp $ */ #include"vsip.h" #include"VI.h" #include"vsip_cmviewattributes_d.h" #include"vsip_cvviewattributes_d.h" /* note that matrix products may not be done in place */ void (vsip_cmprod3_d)( const vsip_cmview_d* a, const vsip_cmview_d* b, const vsip_cmview_d* c) { /* get the stride info */ /* st_r => stride row; st_c => stride column */ vsip_stride a_st_r = a->row_stride * a->block->cstride, a_st_c = a->col_stride * a->block->cstride, b_st_r = b->row_stride * b->block->cstride, b_st_c = b->col_stride * b->block->cstride, c_st_r = c->row_stride * c->block->cstride, c_st_c = c->col_stride * c->block->cstride; /* get the length info */ /* note we know a is 3 by 3 and b is 3 by row length */ vsip_length c_r_l = c->row_length; /* j_size */ /* get the pointers to the input and output data spaces */ vsip_scalar_d *ap_r = (a->block->R->array) + a->offset * a->block->cstride, *ap_i = (a->block->I->array) + a->offset * a->block->cstride, *bp_r = (b->block->R->array) + b->offset * b->block->cstride, *bp_i = (b->block->I->array) + b->offset * b->block->cstride, *cp_r = (c->block->R->array) + c->offset * c->block->cstride, *cp_i = (c->block->I->array) + c->offset * c->block->cstride; /* some additional pointers to store initial data */ vsip_scalar_d *ap0_r = ap_r, *ap0_i = ap_i, *bp0_r, *bp0_i, *cp0_r, *cp0_i; register vsip_scalar_d a00_r, a01_r, a02_r, a00_i, a01_i, a02_i; register vsip_scalar_d a10_r, a11_r, a12_r, a10_i, a11_i, a12_i; register vsip_scalar_d a20_r, a21_r, a22_r, a20_i, a21_i, a22_i; /* we need local storage for a column of b */ register vsip_scalar_d b0_r, b1_r, b2_r; register vsip_scalar_d b0_i, b1_i, b2_i; vsip_length i; /* need a counter */ /* we copy a to local storage */ a00_r = *ap0_r; a00_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a01_r = *ap0_r; a01_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a02_r = *ap0_r; a02_i = *ap0_i; ap0_r = ap_r + a_st_c; ap0_i = ap_i + a_st_c; a10_r = *ap0_r; a10_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a11_r = *ap0_r; a11_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a12_r = *ap0_r; a12_i = *ap0_i; ap0_r = ap_r + 2 * a_st_c; ap0_i = ap_i + 2 * a_st_c; a20_r = *ap0_r; a20_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a21_r = *ap0_r; a21_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a22_r = *ap0_r; a22_i = *ap0_i; for(i=0; i< c_r_l; i++){ /* copy i'th column of b into local */ bp0_r = bp_r + (vsip_stride)i * b_st_r; bp0_i = bp_i + (vsip_stride)i * b_st_r; b0_r = *bp0_r; b0_i = *bp0_i; bp0_r += b_st_c; bp0_i += b_st_c; b1_r = *bp0_r; b1_i = *bp0_i; bp0_r += b_st_c; bp0_i += b_st_c; b2_r = *bp0_r; b2_i = *bp0_i; /* get the pointer to the column where output will go */ cp0_r = cp_r + (vsip_stride)i * c_st_r; cp0_i = cp_i + (vsip_stride)i * c_st_r; /* do the math */ /* the real part */ *cp0_r = (a00_r * b0_r + a01_r * b1_r + a02_r * b2_r ) - (a00_i * b0_i + a01_i * b1_i + a02_i * b2_i ); cp0_r += c_st_c; *cp0_r = (a10_r * b0_r + a11_r * b1_r + a12_r * b2_r ) - (a10_i * b0_i + a11_i * b1_i + a12_i * b2_i ); cp0_r += c_st_c; *cp0_r = (a20_r * b0_r + a21_r * b1_r + a22_r * b2_r ) - (a20_i * b0_i + a21_i * b1_i + a22_i * b2_i ); /* the imaginary part */ *cp0_i = a00_r * b0_i + a01_r * b1_i + a02_r * b2_i + a00_i * b0_r + a01_i * b1_r + a02_i * b2_r ; cp0_i += c_st_c; *cp0_i = a10_r * b0_i + a11_r * b1_i + a12_r * b2_i + a10_i * b0_r + a11_i * b1_r + a12_i * b2_r ; cp0_i += c_st_c; *cp0_i = a20_r * b0_i + a21_r * b1_i + a22_r * b2_i + a20_i * b0_r + a21_i * b1_r + a22_i * b2_r ; } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: msinh_f.h,v 2.0 2003/02/22 15:23:26 judd Exp $ */ #include"VU_mprintm_f.include" static void msinh_f(void){ printf("\n*******\nTEST msinh_f\n\n"); { vsip_scalar_f data[] = {0, M_PI/4.0, M_PI/2.0, M_PI, 1.5 * M_PI, 1.75 * M_PI}; vsip_scalar_f ans[] = {0, 0.8687, 2.3013, 11.5487, 55.6544, 122.0735}; vsip_block_f *block = vsip_blockbind_f(data,6,VSIP_MEM_NONE); vsip_block_f *ans_block = vsip_blockbind_f(ans,6,VSIP_MEM_NONE); vsip_mview_f *a = vsip_mbind_f(block,0,1,2,2,3); vsip_mview_f *ansv = vsip_mbind_f(ans_block,0,1,2,2,3); vsip_mview_f *b = vsip_mcreate_f(2,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *chk = vsip_mcreate_f(2,3,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_f(block,VSIP_TRUE); vsip_blockadmit_f(ans_block,VSIP_TRUE); printf("vsip_msinh_f(a,b)\n"); vsip_msinh_f(a,b); printf("matrix a\n");VU_mprintm_f("8.6",a); printf("matrix b\n");VU_mprintm_f("8.6",b); printf("right answer \n");VU_mprintm_f("8.4",ansv); vsip_msub_f(b,ansv,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("inplace\n"); vsip_msinh_f(a,a); vsip_msub_f(a,ansv,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_f(a); vsip_malldestroy_f(b); vsip_malldestroy_f(chk); vsip_malldestroy_f(ansv); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mmaxmg_f.h,v 2.0 2003/02/22 15:23:25 judd Exp $ */ #include"VU_mprintm_f.include" static void mmaxmg_f(void){ printf("\n*******\nTEST mmaxmg_f\n\n"); { vsip_scalar_f data1[] = {-1, 2, 0, -5, -6, 3.4, -3.4, 5.6, -.3}; vsip_scalar_f data2[] = {-2, 1, 0, -3, -7, -3.4, -3.5, 5.6, -.2}; vsip_scalar_f ans[] = { 2, 2, 0, 5, 7, 3.4, 3.5, 5.6, .3}; vsip_block_f *block1 = vsip_blockbind_f(data1,9,VSIP_MEM_NONE); vsip_block_f *block2 = vsip_blockbind_f(data2,9,VSIP_MEM_NONE); vsip_block_f *ans_block = vsip_blockbind_f(ans,9,VSIP_MEM_NONE); vsip_mview_f *a = vsip_mbind_f(block1,0,3,3,1,3); vsip_mview_f *b = vsip_mbind_f(block2,0,3,3,1,3); vsip_mview_f *ansm = vsip_mbind_f(ans_block,0,3,3,1,3); vsip_mview_f *c = vsip_mcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *chk = vsip_mcreate_f(3,3,VSIP_COL,VSIP_MEM_NONE); vsip_blockadmit_f(block1,VSIP_TRUE); vsip_blockadmit_f(block2,VSIP_TRUE); vsip_blockadmit_f(ans_block,VSIP_TRUE); printf("test out of place, compact, user \"a\", vsipl \"b\"\n"); vsip_mmaxmg_f(a,b,c); printf("vsip_mmaxmg_f(a,b,c)\n matrix a\n");VU_mprintm_f("8.6",a); printf("matrix b\n");VU_mprintm_f("8.6",b); printf("matrix c\n");VU_mprintm_f("8.6",c); printf("expected answer to 4 decimal digits\n");VU_mprintm_f("8.4",ansm); vsip_msub_f(c,ansm,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check mmaxmg_f b,c inplace\n"); vsip_mmaxmg_f(a,b,b); vsip_msub_f(b,ansm,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_f(a); vsip_malldestroy_f(b); vsip_malldestroy_f(c); vsip_malldestroy_f(chk); vsip_malldestroy_f(ansm); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cvget_put_d.h,v 2.0 2003/02/22 15:23:33 judd Exp $ */ static void cvget_put_d(void){ printf("********\nTEST cvget_put_d\n"); { vsip_scalar_d datar_a[] = { 0, 1, 1, 0, 1, 0}; vsip_scalar_d datai_a[] = { 1, -1, -1, 1, -1, 1}; vsip_scalar_d ansr[] = { 0, 1, 1, 0, 1, 0}; vsip_scalar_d ansi[] = { 1, -1, -1, 1, -1, 1}; vsip_cblock_d *block_a = vsip_cblockbind_d(datar_a,datai_a,6,VSIP_MEM_NONE); vsip_cvview_d *a = vsip_cvbind_d(block_a,0,1,6); vsip_cblock_d *block_b = vsip_cblockcreate_d(50,VSIP_MEM_NONE); vsip_cvview_d *b = vsip_cvbind_d(block_b, 35,-2,6); vsip_index i; vsip_cblockadmit_d(block_a,VSIP_TRUE); /* copy <a> into <b> */ for(i=0; i<6; i++) vsip_cvput_d(b,i,vsip_cvget_d(a,i)); /* check <a> against ans */ printf("check unit stride compact view\n"); for(i=0; i<6; i++){ vsip_cscalar_d chk = vsip_cvget_d(a,i); chk.r = chk.r - ansr[i]; chk.i = chk.i - ansi[i]; chk.r = chk.r * chk.r + chk.i * chk.i; (chk.r < 0.0001) ? printf("correct\n") : printf("error\n"); fflush(stdout); } printf("check general stride view\n"); for(i=0; i<6; i++){ vsip_cscalar_d chk = vsip_cvget_d(b,i); chk.r = chk.r - ansr[i]; chk.i = chk.i - ansi[i]; chk.r = chk.r * chk.r + chk.i * chk.i; (chk.r < 0.0001) ? printf("correct\n") : printf("error\n"); fflush(stdout); } vsip_cvalldestroy_d(a); vsip_cvalldestroy_d(b); } return; } <file_sep>/* Created RJudd December 14, 1997 */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vsumval_si.c,v 2.0 2003/02/22 15:19:19 judd Exp $ */ /* Modified RJudd March 20, 1998 */ /* to vsip_vsumval_si.c */ /* Removed Tisdale error checking Sept 00 */ #include"vsip.h" #include"vsip_vviewattributes_si.h" vsip_scalar_si (vsip_vsumval_si)( const vsip_vview_si* a) { { /*define variables*/ /* register */ unsigned int n = (unsigned int) a->length; /* register */ int ast = (int)a->stride; vsip_scalar_si *ap = (a->block->array) + a->offset; vsip_scalar_si t = 0; /* do sum */ while(n-- > 0){ t += *ap; ap += ast; } /* return sum */ return t; } } <file_sep>/* Created RJudd March 18, 2012 */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"vsip.h" #include"vsip_cvviewattributes_d.h" #include"vsip_rcfirattributes_d.h" #include"vsip_vviewattributes_d.h" #include"VI_cvcopy_d_d.h" #include"VI_cvfill_d.h" static vsip_cscalar_d rcvdot_d( const vsip_vview_d* a, const vsip_cvview_d* b) { { vsip_length n = a->length; vsip_stride cbst = b->block->cstride; vsip_scalar_d *apr = (vsip_scalar_d*) ((a->block->array) + a->block->rstride * a->offset), *bpr = (vsip_scalar_d*) ((b->block->R->array) + cbst * b->offset), *bpi = (vsip_scalar_d*) ((b->block->I->array) + cbst * b->offset); vsip_stride ast = (a->block->rstride * a->stride), bst = (cbst * b->stride); vsip_cscalar_d r; r.r = 0; r.i = 0; while(n-- > 0){ r.r += *apr * *bpr; r.i += *apr * *bpi; apr += ast; bpr += bst; bpi += bst; } return r; } } int vsip_rcfirflt_d( vsip_rcfir_d *fir, const vsip_cvview_d *xc, const vsip_cvview_d *yc) { vsip_length nout,k; vsip_cvview_d xx = *(xc), yy = *(yc); vsip_vview_d H1 = *(fir->h), H2 = *(fir->h); vsip_cvview_d *x=&xx,*y=&yy; vsip_vview_d *h1=&H1,*h2=&H2; vsip_offset oinc; oinc = (vsip_offset)((vsip_stride)fir->D * x->stride); /* calculate number of terms in y */ nout = (fir->N - fir->p); nout = ((nout % fir->D) == 0) ? (nout / fir->D ) : (nout / fir->D + 1); /* do overlap section */ k = 0; x->length = fir->p + 1; h1->length = fir->s->length; h2->length = x->length; h2->offset = h1->length; while(x->length < fir->M){ vsip_cscalar_d a = rcvdot_d(h1,fir->s); vsip_cscalar_d b = rcvdot_d(h2,x); vsip_cvput_d(y,k++,vsip_cmplx_d(a.r + b.r,a.i + b.i)); x->length += fir->D; fir->s->length -= fir->D; fir->s->offset += fir->D; h1->length = fir->s->length; h2->length = x->length; h2->offset = h1->length; } x->offset += (x->length - fir->M) * x->stride; x->length = fir->M; while(k < nout){ /* do the rest of the pieces */ vsip_cvput_d(y,k++,rcvdot_d(fir->h,x)); x->offset += oinc; } { vsip_stride temp_p = (fir->p % fir->D) - (fir->N % fir->D); fir->p = ((temp_p < 0) ? (vsip_length)((vsip_stride)fir->D + temp_p) : (vsip_length)temp_p); } fir->s->offset = 0; fir->s->length = (fir->state == VSIP_STATE_SAVE) ? fir->M - 1 - fir->p : fir->M -1; x->length = fir->s->length; /* fix by JMA, 31/01/2000, incorrect offset calculation */ /* x->offset = xc->length - fir->s->length; */ x->offset = xc->offset + (xc->length - fir->s->length) * xc->stride; if((fir->s->length > 0) && (fir->state == VSIP_STATE_SAVE)) VI_cvcopy_d_d(x,fir->s); if(fir->state == VSIP_STATE_NO_SAVE) { VI_cvfill_d(vsip_cmplx_d((vsip_scalar_d)0,(vsip_scalar_d)0),fir->s); fir->p = 0; } return (int) k; } <file_sep>import vsiputils as vsip from param import * import kw as KW import ts as TS import numpy as np import matplotlib.pyplot as plt def mToA(m): M=vsip.getcollength(m) N=vsip.getrowlength(m) a=np.empty((M,N),float,'C') for i in range(M): for j in range(N): a[i,j] = vsip.get(m,(i,j)) return a def beamformer(fileName,figNum=1): param=param_read(fileName) navg=param['Navg'] ts=TS.Sim_ts(param) kw=KW.Kw(param) kw.zero() dtaIn=ts.instance() gramOut=kw.instance() for i in range(navg): ts.zero() ts.nb_sim() ts.noise_sim() kw.kw(dtaIn) for i in range(vsip.getrowlength(gramOut)): v=vsip.colview(gramOut,i) vsip.freqswap(v) vsip.destroy(v) max = vsip.maxval(gramOut,None) avg = vsip.meanval(gramOut) vsip.clip(gramOut,0.0,max,avg/100000.0,max,gramOut) vsip.log10(gramOut,gramOut) min = vsip.minval(gramOut,None) vsip.add(-min,gramOut,gramOut) max=vsip.maxval(gramOut,None) vsip.mul(1.0/max,gramOut,gramOut) fig = plt.figure(figNum,figsize=(10,4)) ax = fig.add_axes([0.10,0.10,0.85,0.80]) ax.set_yticklabels(['0','0','30','60','90','120','150','180']) ax.yaxis.set_ticks_position('right') im=mToA(gramOut) plt.imshow(im) plt.title('K-Omega Beamformer Output') plt.xlabel('Frequency') plt.ylabel(r'$\frac{cos(\theta)}{\lambda}$',fontsize=16,rotation='horizontal') plt.colorbar() <file_sep>/* Created RJudd */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mcumsum_d.c,v 2.1 2004/04/03 14:19:03 judd Exp $ */ #include"vsip.h" #include"vsip_mviewattributes_d.h" #include"VI_mcolview_d.h" #include"VI_mrowview_d.h" #include"VI_vcumsum_d.h" void vsip_mcumsum_d( const vsip_mview_d *a, vsip_major major, const vsip_mview_d *r) { { vsip_vview_d *va,vaa; vsip_vview_d *vr,vrr; vsip_index i; vsip_length m = a->col_length; vsip_length n = a->row_length; va = &vaa; vr = &vrr; if(major == VSIP_ROW){ for(i=0; i<m; i++){ VI_mrowview_d(a,i,va); VI_mrowview_d(r,i,vr); VI_vcumsum_d(va,vr); } } else { /* must be VSIP_COL */ for(i=0; i<n; i++){ VI_mcolview_d(a,i,va); VI_mcolview_d(r,i,vr); VI_vcumsum_d(va,vr); } } } return; } <file_sep>// // Block.cpp // cppJvsip // // Created by <NAME> on 4/28/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #include "Block.h" jvsip::Block::Block(string t, Scalar l) : t(t), s("block"),n(l.length()),count(0) { // t is d+p usually; "mi" for matrix index if(t== "f"){ create((vsip_block_f**)&obj,l.length()); d="r"; p="f"; } else if(t== "d"){ create((vsip_block_d**)&obj,l.length()); d="r"; p="d"; } else if(t== "cf"){ create((vsip_cblock_f**)&obj,l.length()); d="c"; p="f"; } else if(t== "cd"){ create((vsip_cblock_d**)&obj,l.length()); d="c"; p="d"; } else if(t== "i"){ create((vsip_block_i**)&obj,l.length()); d="r"; p="i"; } else if(t== "vi"){ create((vsip_block_vi**)&obj,l.length()); d="r"; p="vi"; } else if(t== "mi"){ create((vsip_block_mi**)&obj,l.length()); d="mi"; p="mi"; } else{std::cout << "precision case not found" << std::endl;exit(-1); } } jvsip::Block:: ~Block(){ if(count == 0){ string pcsn=precision(); if (pcsn=="f"){ destroy((vsip_block_f*)vsip()); std::cout<<type() << " block destroyed\n"; } else if (pcsn=="d"){ destroy((vsip_block_d*)vsip()); std::cout<<"block_d destroyed\n"; }else if (pcsn=="cf"){ destroy((vsip_cblock_f*)vsip()); std::cout<<"cblock_f destroyed\n"; }else if (pcsn=="cd"){ destroy((vsip_cblock_d*)vsip()); std::cout<<"cblock_d destroyed\n"; }else if (pcsn=="i"){ destroy((vsip_block_i*)vsip()); std::cout<<"block_d destroyed\n"; }else if (pcsn=="vi"){ destroy((vsip_block_vi*)vsip()); std::cout<<"block_d destroyed\n"; }else if (pcsn=="mi"){ destroy((vsip_block_mi*)vsip()); std::cout<<"block_mi destroyed\n"; } } else count--; } <file_sep>/* Created RJudd January 30, 2000 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cvlog_d.c,v 2.0 2003/02/22 15:18:50 judd Exp $ */ #include"vsip.h" #include"vsip_cvviewattributes_d.h" void (vsip_cvlog_d)( const vsip_cvview_d *a, const vsip_cvview_d *r) { { /* register */ unsigned int n = (unsigned int) r->length; vsip_stride cast = a->block->cstride; vsip_stride crst = r->block->cstride; vsip_scalar_d *apr = (vsip_scalar_d*) ((a->block->R->array) + cast * a->offset), *rpr = (vsip_scalar_d*) ((r->block->R->array) + crst * r->offset); vsip_scalar_d *api = (vsip_scalar_d*) ((a->block->I->array) + cast * a->offset), *rpi = (vsip_scalar_d*) ((r->block->I->array) + crst * r->offset); /* register */ int ast = (int)(cast * a->stride), rst = (int)(crst * r->stride); vsip_scalar_d mag = 0, s = 0, ss=0; if(a == r){ /* in place */ while(n-- > 0){ s = ((*rpr > 0) ? *rpr: -*rpr) + ((*rpi >0) ? *rpi: -*rpi); ss = s * s; if(s == 0){ mag = -VSIP_MAX_SCALAR_F; /* error */ } else { mag = (vsip_scalar_d)log(s * sqrt((*rpr * *rpr)/ss + (*rpi * *rpi)/ss)); } *rpi = (vsip_scalar_d)atan2(*rpi,*rpr); *rpr = mag; rpr += rst; rpi += rst; } } else { /* out of place */ while(n-- > 0){ s = ((*apr > 0) ? *apr: -*apr) + ((*api >0) ? *api: -*api); ss = s * s; if(s == 0){ *rpr = -VSIP_MAX_SCALAR_F; /* error */ } else { *rpr = (vsip_scalar_d)log(s * sqrt((*apr * *apr)/ss + (*api * *api)/ss)); } *rpi = (vsip_scalar_d)atan2(*api,*apr); apr += ast; api += ast; rpr += rst; rpi += rst; } } } return; } <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmcopyfrom_user_d.h,v 1.1 2007/04/18 03:59:06 judd Exp $ */ #include"VU_cmprintm_d.include" static void cmcopyfrom_user_d(void){ vsip_index i,j; printf("********\nTEST cmcopyfrom_user_d\n"); { /* check row copy interleaved */ vsip_cblock_d *block = vsip_cblockcreate_d(200,VSIP_MEM_NONE); vsip_scalar_d input[40]={0,0,0,1,0,2,0,3,1,0,1,1,1,2,1,3,2,0,2,1,2,2,2,3,3,0,3,1,3,2,3,3,4,0,4,1,4,2,4,3}; vsip_cmview_d *view = vsip_cmbind_d(block,100,2,5,12,4); vsip_cvview_d *all = vsip_cvbind_d(block,0,1,200); vsip_scalar_d check = 0; vsip_cvfill_d(vsip_cmplx_d(-1,-1),all); vsip_cmcopyfrom_user_d(input,(vsip_scalar_d*)NULL,VSIP_ROW,view); printf("check row copy interleaved\n"); VU_cmprintm_d("3.2",view); for(i=0; i<5; i++) { for(j=0; j < 4; j++) { check += fabs(input[2*(i * 4 + j)] - vsip_real_d(vsip_cmget_d(view,i,j))); check += fabs(input[2*(i * 4 + j)+1] - vsip_imag_d(vsip_cmget_d(view,i,j))); } } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_cvdestroy_d(all); vsip_cmdestroy_d(view); vsip_cblockdestroy_d(block); } { /* check col copy interleaved*/ vsip_cblock_d *block = vsip_cblockcreate_d(200,VSIP_MEM_NONE); vsip_scalar_d input[40]={0,0,1,0,2,0,3,0,4,0,0,1,1,1,2,1,3,1,4,1,0,2,1,2,2,2,3,2,4,2,0,3,1,3,2,3,3,3,4,3}; vsip_cmview_d *view = vsip_cmbind_d(block,100,2,5,12,4); vsip_cvview_d *all = vsip_cvbind_d(block,0,1,200); vsip_scalar_d check = 0; vsip_cvfill_d(vsip_cmplx_d(-1,-1),all); vsip_cmcopyfrom_user_d(input,(vsip_scalar_d*)NULL,VSIP_COL,view); printf("check col copy interleaved\n"); VU_cmprintm_d("3.2",view); for(j=0; j<4; j++) { for(i=0; i < 5; i++) { check += fabs(input[2*(i + j * 5)] - vsip_real_d(vsip_cmget_d(view,i,j))); check += fabs(input[2*(i + j * 5)+1] - vsip_imag_d(vsip_cmget_d(view,i,j))); } } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_cvdestroy_d(all); vsip_cmdestroy_d(view); vsip_cblockdestroy_d(block); } { /* check row copy split */ vsip_cblock_d *block = vsip_cblockcreate_d(200,VSIP_MEM_NONE); vsip_scalar_d input_r[20]={0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4}; vsip_scalar_d input_i[20]={0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3}; vsip_cmview_d *view = vsip_cmbind_d(block,100,2,5,12,4); vsip_cvview_d *all = vsip_cvbind_d(block,0,1,200); vsip_scalar_d check = 0; vsip_cvfill_d(vsip_cmplx_d(-1,-1),all); vsip_cmcopyfrom_user_d(input_r,input_i,VSIP_ROW,view); printf("check row copy split\n"); VU_cmprintm_d("3.2",view); for(i=0; i<5; i++) { for(j=0; j < 4; j++) { check += fabs(input_r[i * 4 + j] - vsip_real_d(vsip_cmget_d(view,i,j))); check += fabs(input_i[i * 4 + j] - vsip_imag_d(vsip_cmget_d(view,i,j))); } } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_cvdestroy_d(all); vsip_cmdestroy_d(view); vsip_cblockdestroy_d(block); } { /* check col copy split*/ vsip_cblock_d *block = vsip_cblockcreate_d(200,VSIP_MEM_NONE); vsip_scalar_d input_r[20]={0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4}; vsip_scalar_d input_i[20]={0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3}; vsip_cmview_d *view = vsip_cmbind_d(block,100,2,5,12,4); vsip_cvview_d *all = vsip_cvbind_d(block,0,1,200); vsip_scalar_d check = 0; vsip_cvfill_d(vsip_cmplx_d(-1,-1),all); vsip_cmcopyfrom_user_d(input_r,input_i,VSIP_COL,view); printf("check col copy split\n"); VU_cmprintm_d("3.2",view); for(j=0; j<4; j++) { for(i=0; i < 5; i++) { check += fabs(input_r[i + j * 5] - vsip_real_d(vsip_cmget_d(view,i,j))); check += fabs(input_i[i + j * 5] - vsip_imag_d(vsip_cmget_d(view,i,j))); } } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_cvdestroy_d(all); vsip_cmdestroy_d(view); vsip_cblockdestroy_d(block); } return; } <file_sep>//: Playground - noun: a place where people can play import Cocoa let mb = createMandelbrotImage(width: 500, height: 500, xS: -0.802, yS: -0.177, rad: 0.011, maxIteration: 110) let context = makeRGBImageContext(width: 500, height: 500, buffer: mb) let image = makeImage(context: context) <file_sep>/* Created RJudd September 30, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_tgetattrib_f.c,v 2.0 2003/02/22 15:19:05 judd Exp $ */ #include"VI_support_priv_f.h" void vsip_tgetattrib_f( const vsip_tview_f *v, vsip_tattr_f *attr) { attr->z_length = v->z_length; attr->y_length = v->y_length; attr->x_length = v->x_length; attr->z_stride = v->z_stride; attr->y_stride = v->y_stride; attr->x_stride = v->x_stride; attr->offset = v->offset; attr->block = v->block; return; } <file_sep>#!/usr/bin/env python from distutils.core import setup setup(name='vsipUser', version='0.1', description='Utility functions for C VSIPL module', author='<NAME>', author_email='<EMAIL>', py_modules=['vsipUser'], ) <file_sep>import pyJvsip as pjv from math import pi as pi from matplotlib.pyplot import * #make up some data for vector interpolation x0=pjv.ramp('vview_d',0.0,2*pi/10,11) y0=pjv.sin(x0,x0.empty) #make up an interpolation vector and output x=pjv.ramp('vview_d',0.0,2*pi/250,251) yEstimate=x.empty #interploate spln=pjv.Spline(x0.type,400) spln.interpolate(x0,y0,x,yEstimate) #calculate actual yActual=pjv.sin(x,x.empty) #plot the data and save as pdf subplot(3,1,1) plot(x0,y0);title('Sparse Sine') tick_params(axis='x',labelbottom='off') for i in range(x0.length): text(x0[i],y0[i],'|',verticalalignment='center',horizontalalignment='center') subplot(3,1,2) plot(x,yEstimate);title('Estimate of Dense Sine') tick_params(axis='x',labelbottom='off') subplot(3,1,3) plot(x,yEstimate-yActual);title('Error in Dense Sine') #plot zero line. There should be at least 11 zero errors plot(x,yActual.fill(0.0)) xlabel('Radian Values') for i in range(x0.length): text(x0[i],0,'|',verticalalignment='center',horizontalalignment='center') tight_layout() savefig('eXspline.pdf',figsize=(3,7)) <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: csvdiv_d.h,v 2.0 2003/02/22 15:23:22 judd Exp $ */ #include"VU_cvprintm_d.include" static void csvdiv_d(void){ printf("\n********\nTEST csvdiv_d\n"); { vsip_cscalar_d alpha = vsip_cmplx_d(1.5,-1.5); vsip_cvview_d *b = vsip_cvcreate_d(7,VSIP_MEM_NONE); vsip_cvview_d *c = vsip_cvcreate_d(7,VSIP_MEM_NONE); vsip_vview_d *c_i = vsip_vimagview_d(c); vsip_cvview_d *chk = vsip_cvcreate_d(7,VSIP_MEM_NONE); vsip_vview_d *chk_i = vsip_vimagview_d(chk); vsip_scalar_d data_r[] ={.1, .2, .3, .4, .5, .6, .7}; vsip_scalar_d data_i[] ={7,6,5,4,3,2,1}; vsip_scalar_d data_ans[] ={-.2112,-.2173, -.2414,-.2580, -.2810,-.3169, -.3342,-.4084, -.4054,-.5676, -.4817,-0.8945, -0.3020,-1.7114}; vsip_cblock_d *cblock = vsip_cblockbind_d(data_r,data_i,7,VSIP_MEM_NONE); vsip_cblock_d *cblock_ans = vsip_cblockbind_d(data_ans, (vsip_scalar_d*)NULL,7,VSIP_MEM_NONE); vsip_cvview_d *u_b = vsip_cvbind_d(cblock,0,1,7); vsip_cvview_d *u_ans = vsip_cvbind_d(cblock_ans,0,1,7); vsip_cblockadmit_d(cblock,VSIP_TRUE); vsip_cblockadmit_d(cblock_ans,VSIP_TRUE); vsip_cvcopy_d_d(u_b,b); printf("call vsip_csvdiv_d(alpha,b,c)\n"); printf("alpha = %f %+fi\n",vsip_real_d(alpha),vsip_imag_d(alpha)); printf("b =\n");VU_cvprintm_d("8.6",b); printf("test normal out of place\n"); vsip_csvdiv_d(alpha,b,c); printf("c =\n");VU_cvprintm_d("8.6",c); printf("right answer =\n");VU_cvprintm_d("8.4",u_ans); vsip_cvsub_d(u_ans,c,chk); vsip_cvmag_d(chk,chk_i); vsip_vclip_d(chk_i,.0002,.0002,0,1,chk_i); if(vsip_vsumval_d(chk_i) > .5) printf("error\n"); else printf("correct\n"); printf("test b,c inplace\n"); vsip_csvdiv_d(alpha,b,b); vsip_cvsub_d(u_ans,b,chk); vsip_cvmag_d(chk,chk_i); vsip_vclip_d(chk_i,.0002,.0002,0,1,chk_i); if(vsip_vsumval_d(chk_i) > .5) printf("error\n"); else printf("correct\n"); vsip_cvalldestroy_d(b); vsip_vdestroy_d(c_i); vsip_cvalldestroy_d(c); vsip_vdestroy_d(chk_i); vsip_cvalldestroy_d(chk); vsip_cvalldestroy_d(u_b); vsip_cvalldestroy_d(u_ans); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_offset_d.h,v 2.1 2007/04/18 17:05:56 judd Exp $ */ static void get_put_offset_d(void){ printf("********\nTEST get_put_offset_d\n"); { vsip_offset ivo = 3, icvo=10; vsip_stride ivs = 0, icvs=0; vsip_length ivl = 3, icvl=4; vsip_offset jvo = 2, jcvo=0; vsip_stride irs = 0, ics = 0; vsip_length irl = 2, icl = 3; vsip_stride ixs = 0, iys = 0, izs = 0; vsip_length ixl = 2, iyl = 3, izl = 4; vsip_block_d *b = vsip_blockcreate_d(80,VSIP_MEM_NONE); vsip_cblock_d *cb = vsip_cblockcreate_d(80,VSIP_MEM_NONE); vsip_vview_d *v = vsip_vbind_d(b,ivo,ivs,ivl); vsip_mview_d *m = vsip_mbind_d(b,ivo,ics,icl,irs,irl); vsip_tview_d *t = vsip_tbind_d(b,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_cvview_d *cv = vsip_cvbind_d(cb,icvo,icvs,icvl); vsip_cmview_d *cm = vsip_cmbind_d(cb,ivo,ics,icl,irs,irl); vsip_ctview_d *ct = vsip_ctbind_d(cb,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_offset s; printf("test vgetoffset_d\n"); fflush(stdout); { s = vsip_vgetoffset_d(v); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputoffset_d\n"); fflush(stdout); { vsip_vputoffset_d(v,jvo); s = vsip_vgetoffset_d(v); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } printf("test cvgetoffset_d\n"); fflush(stdout); { s = vsip_cvgetoffset_d(cv); (s == icvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputoffset_d\n"); fflush(stdout); { vsip_cvputoffset_d(cv,jcvo); s = vsip_cvgetoffset_d(cv); (s == jcvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /*************************************************************************/ printf("test mgetoffset_d\n"); fflush(stdout); { s = vsip_mgetoffset_d(m); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputoffset_d\n"); fflush(stdout); { vsip_mputoffset_d(m,jvo); s = vsip_mgetoffset_d(m); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } printf("test cmgetoffset_d\n"); fflush(stdout); { s = vsip_cmgetoffset_d(cm); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test cmputoffset_d\n"); fflush(stdout); { vsip_cmputoffset_d(cm,jvo); s = vsip_cmgetoffset_d(cm); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /*************************************************************************/ printf("test tgetoffset_d\n"); fflush(stdout); { s = vsip_tgetoffset_d(t); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputoffset_d\n"); fflush(stdout); { vsip_tputoffset_d(t,jvo); s = vsip_tgetoffset_d(t); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } printf("test ctgetoffset_d\n"); fflush(stdout); { s = vsip_ctgetoffset_d(ct); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test ctputoffset_d\n"); fflush(stdout); { vsip_ctputoffset_d(ct,jvo); s = vsip_ctgetoffset_d(ct); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } vsip_vdestroy_d(v); vsip_mdestroy_d(m); vsip_talldestroy_d(t); vsip_cvdestroy_d(cv); vsip_cmdestroy_d(cm); vsip_ctalldestroy_d(ct); } return; } <file_sep>/* Created by RJudd July 10, 2002 */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id */ #ifndef _VI_CRFFTMOP_D_DEF_H #define _VI_CRFFTMOP_D_DEF_H 1 #include"VI_fftm_building_blocks_d.h" #include"VI_mrealview_d.h" #include"VI_mimagview_d.h" #include"VI_cmrowview_d.h" #include"VI_cmcolview_d.h" #include"VI_mcopy_d_d.h" #include"VI_cvcopy_d_d.h" void vsip_crfftmop_d( const vsip_fftm_d *Offt, const vsip_cmview_d *Z, const vsip_mview_d *X) { vsip_fftm_d Nfft = *Offt; vsip_fftm_d *fft = &Nfft; vsip_length m = fft->mN; /* makes */ vsip_mview_d xx_e = *X; vsip_mview_d *X_e = &xx_e; vsip_mview_d xx_o = *X; vsip_mview_d *X_o = &xx_o; vsip_cvview_d yy = *fft->temp; vsip_cvview_d *y = &yy; /*y*/ vsip_mview_d YY_r; vsip_mview_d *Y_r; vsip_mview_d YY_i; vsip_mview_d *Y_i; vsip_cmview_d YY; vsip_cmview_d *Y = &YY; vsip_cvview_d ANG = *fft->temp; vsip_cvview_d *ang = &ANG; /*ang correction*/ vsip_cvview_d Z0,*z; vsip_stride zst,yst = fft->MN + 1; vsip_offset ysto = fft->MN; vsip_major major = fft->major; if(major == VSIP_ROW){ z = VI_cmrowview_d(Z,0,&Z0); *X_e = *X; X_e->row_stride = 2 * X->row_stride; X_e->row_length = ysto; *X_o = *X; X_o->row_stride = 2 * X->row_stride; X_o->row_length = ysto; X_e->offset += X->row_stride; zst = Z->col_stride; }else{ z = VI_cmcolview_d(Z,0,&Z0); *X_e = *X; X_e->col_stride = 2 * X->col_stride; X_e->col_length = ysto; *X_o = *X; X_o->col_stride = 2 * X->col_stride; X_o->col_length = ysto; X_e->offset += X->col_stride; zst = Z->row_stride; } /* make complex matrix from temp vector row major */ { Y->block = y->block; Y->row_length = fft->MN + 1; Y->col_length = fft->mN; Y->row_stride = 1; Y->col_stride = fft->MN +1; Y->offset = 2 * (fft->MN + 1); Y->markings = vsip_valid_structure_object; } /* end makes */ /* change ang view to to proper portion of temp */ ang->offset = fft->MN + 1; ang->length = fft->MN + 1; y = VI_cmrowview_d(Y,0,y); while(m-- > 0){ y->stride = -1; y->offset += ysto; /* copy z to y in reverse order */ VI_cvcopy_d_d(z,y); /* reset y to normal */ y->stride = 1; y->offset -= ysto; { /* this is where the sorting work is done */ vsip_cvview_d *w = ang; /* these first three steps are just to make*/ vsip_cvview_d *f = z; /* it easier to use already developed code */ vsip_cvview_d *b = y; /* register */ vsip_length n = b->length; vsip_stride cwst = w->block->cstride; vsip_stride cfst = f->block->cstride; vsip_stride cbst = b->block->cstride; vsip_scalar_d *wpr = (vsip_scalar_d *)((w->block->R->array) + cwst * w->offset), *fpr = (vsip_scalar_d *)((f->block->R->array) + cfst * f->offset), *bpr = (vsip_scalar_d *)((b->block->R->array) + cbst * b->offset); vsip_scalar_d *wpi = (vsip_scalar_d *)((w->block->I->array) + cwst * w->offset), *fpi = (vsip_scalar_d *)((f->block->I->array) + cfst * f->offset), *bpi = (vsip_scalar_d *)((b->block->I->array) + cbst * b->offset); /* register */ vsip_stride wst = cwst * w->stride, fst = cfst * f->stride, bst = cbst * b->stride; vsip_scalar_d temp; while(n-- > 0){ temp = /*(0.5) */ (*fpr + *bpr + *wpi * (*bpr - *fpr) - *wpr * (*fpi + *bpi)); *bpi = /*(0.5) */ (*fpi - *bpi - *wpi * (*fpi + *bpi) + *wpr * (*fpr - *bpr)); *bpr = temp; wpr += wst; wpi += wst; fpr += fst; fpi += fst; bpr += bst; bpi += bst; } } y->offset += yst; z->offset += zst; } { void* tfft = (void*)fft; ((vsip_fftm_d*)tfft)->major = VSIP_ROW;} Y->row_length = ysto; VI_ccfftmip_d(fft,Y); /* function resides in ccfftmop code */ { void* tfft = (void*)fft; ((vsip_fftm_d*)tfft)->major = major;} if( major == VSIP_COL) { Y->col_length = Y->row_length; Y->row_length = fft->mN; Y->row_stride = Y->col_stride; Y->col_stride = 1; } Y_r = VI_mrealview_d(Y,&YY_r); Y_i = VI_mimagview_d(Y,&YY_i); VI_mcopy_d_d(Y_r,X_o); VI_mcopy_d_d(Y_i,X_e); return; } #endif /* _VI_CRFFTMOP_D_DEF_H */ <file_sep>#see tasp_core_plus_book.pdf example 11 for more info on this example import pyJvsip as pv from matplotlib import pyplot N=1024 avg=1000 D=2 init=17 dataIn = pv.create('vview_f',D*N) dataFFT = pv.create('cvview_f',int(N/2) + 1) dataOut = pv.create('vview_f',N) spect_avg = pv.create('vview_f',int(N/2) + 1) spect_new = pv.create('vview_f',int(N/2) + 1) state = pv.Rand('NPRNG',N) fft=pv.FFT('rcfftop_f',(N,1,0,0)) b = [0.0234, -0.0094, -0.0180, -0.0129, 0.0037, 0.0110, -0.0026, -0.0195, -0.0136, 0.0122, 0.0232, -0.0007, -0.0314, -0.0223, 0.0250, 0.0483, -0.0002, -0.0746, -0.0619, 0.0930, 0.3023, 0.3999, 0.3023, 0.0930, -0.0619, -0.0746, -0.0002, 0.0483, 0.0250, -0.0223, -0.0314, -0.0007, 0.0232, 0.0122, -0.0136, -0.0195, -0.0026, 0.0110, 0.0037, -0.0129, -0.0180 ,-0.0094, 0.0234] fir = pv.FIR('fir_f',pv.listToJv('vview_f',b),'NONE',D*N,D,'NO') spect_avg.fill(0.0) for i in range(avg): state.randu(dataIn) pv.add(-.5,dataIn,dataIn) fir.flt(dataIn,dataOut) fft.dft(dataOut,dataFFT) pv.cmagsq(dataFFT,spect_new) pv.add(spect_new,spect_avg,spect_avg) pv.mul(1.0/avg,spect_avg,spect_avg); #print("spect_avg =");spect_avg.mprint('%.4f') x=spect_avg.empty.ramp(0,1.0/(spect_avg.length-1)) pyplot.plot(x.list,spect_avg.list) pyplot.title('Decimation 2') pyplot.ylabel('Not Normalized') pyplot.show() <file_sep>/* See Copyright in top level directory */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #ifndef _NUMPYARRAYCOPIES_H #define _NUMPYARRAYCOPIES_H #include<vsip.h> #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include"Python.h" #include"numpy/arrayobject.h" /* extra functions for python */ void vcopyToNParray_d(vsip_vview_d *, PyObject* ); void vcopyToNParray_f(vsip_vview_f *, PyObject* ); void cvcopyToNParray_d(vsip_cvview_d *, PyObject* ); void cvcopyToNParray_f(vsip_cvview_f *, PyObject* ); void mcopyToNParray_d(vsip_mview_d *, vsip_major, PyObject* ); void mcopyToNParray_f(vsip_mview_f *, vsip_major, PyObject* ); void cmcopyToNParray_d(vsip_cmview_d *, vsip_major, PyObject* ); void cmcopyToNParray_f(vsip_cmview_f *, vsip_major, PyObject* ); void vcopyFromNParray_d(vsip_vview_d *, PyObject* ); void vcopyFromNParray_f(vsip_vview_f *, PyObject* ); void cvcopyFromNParray_d(vsip_cvview_d *, PyObject* ); void cvcopyFromNParray_f(vsip_cvview_f *, PyObject* ); void mcopyFromNParray_d(vsip_mview_d *, vsip_major, PyObject* ); void mcopyFromNParray_f(vsip_mview_f *, vsip_major, PyObject* ); void cmcopyFromNParray_d(vsip_cmview_d *, vsip_major, PyObject* ); void cmcopyFromNParray_f(vsip_cmview_f *, vsip_major, PyObject* ); #endif <file_sep>/* Created RJudd */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"vsip.h" #include"vsip_permuteattributes.h" vsip_permute* vsip_mpermute_create_d( vsip_length m, vsip_length n, vsip_major major) { vsip_permute *retval= (vsip_permute *)malloc(sizeof(vsip_permute)); vsip_length Nindex; if(major == VSIP_ROW){ Nindex = m; } else { Nindex = n; } if(retval){ /* create space */ int check=0; retval->n_vi = Nindex; retval->major = major; if(!(retval->in = (vsip_scalar_vi*)malloc(sizeof(vsip_scalar_vi) * Nindex))) check++; if(!(retval->b = (vsip_scalar_vi*)malloc(sizeof(vsip_scalar_vi) * Nindex))) check++; if(check){ if(retval->in) free(retval->in); if(retval->b) free(retval->b); free(retval); retval = NULL; } } return retval; } <file_sep>/* Created by RJudd January 7, 1999 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_ccfftip_f_def.h,v 2.0 2003/02/22 15:18:29 judd Exp $ */ #include"vsip.h" #include"vsip_fftattributes_f.h" #include"vsip_cvviewattributes_f.h" #include"VI_fft_building_blocks_f.h" #include"VI_ccfftip_f.h" void vsip_ccfftip_f(const vsip_fft_f *Offt, const vsip_cvview_f *y) { vsip_fft_f Nfft = *Offt; vsip_fft_f *fft = &Nfft; VI_ccfftip_f(fft,y); return; } <file_sep>/* Created RJudd March 17, 2012 */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"vsip.h" #include"vsip_cvviewattributes_f.h" #include"vsip_vviewattributes_f.h" #include"vsip_rcfirattributes_f.h" #include"VI_cvfill_f.h" void vsip_rcfir_reset_f( vsip_rcfir_f *fir) { fir->p = 0; fir->s->length = fir->M - 1; VI_cvfill_f(vsip_cmplx_f((vsip_scalar_f)0,(vsip_scalar_f)0),fir->s); return; } <file_sep>import pyJvsip as pv from math import sqrt def houseProd(v,A): beta = 2.0/v.jdot(v) v.conj;w=v.prod(A).conj;v.conj A -= v.outer(beta,w) def prodHouse(A,v): beta = 2.0/v.jdot(v) w=A.prod(v) A-=w.outer(beta,v) def VHmatExtract(B): #B bidiagonalized with householder vectors stored in rows and columns. n = B.rowlength V=pv.create(B.type,n,n).fill(0.0);V.diagview(0).fill(1.0) if(n < 3): return V; for i in range(n-3,0,-1): j=i+1; v=B.rowview(i)[j:] t=v[0] v[0]=1.0 prodHouse(V[j:,j:],v) v[0]=t v=B.rowview(0)[1:] t=v[0];v[0]=1.0 prodHouse(V[1:,1:],v) v[0]=t return V def UmatExtract(B): m = B.collength n = B.rowlength U=pv.create(B.type,m,m).fill(0.0);U.diagview(0).fill(1.0) if (m > n): i=n-1; v=B.colview(i)[i:] t=v[0] v[0]=1.0 houseProd(v,U[i:,i:]) v[0]=t for i in range(n-2,0,-1): v=B.colview(i)[i:] t=v[0];v[0]=1.0 houseProd(v,U[i:,i:]) v[0]=t v=B.colview(0) t=v[0];v[0]=1.0 houseProd(v,U) v[0]=t return U def sign(a): if a.imag == 0.0: if a.real < 0.0: return -1.0 else: return 1.0 else: re = abs(a.real) im = abs(a.imag) if re < im: t=re/im; t*=t; t +=1; t = im*sqrt(t) else: t=im/re; t*=t; t +=1; t = re*sqrt(t) return a/t def houseVector(x): nrm=x.norm2 t=x[0] x[0]=nrm * sign(t) + t nrm = x.norm2 if nrm == 0.0: x[0]=1.0 else: x /= nrm return x def bidiag(B): x=B.colview(0) m=B.collength;n=B.rowlength assert m >= n,'For bidiag the input matrix must have a collength >= rowlength' v=x.empty.fill(0.0) for i in range(n-1): x=B.colview(i)[i:] v=v.block.bind(0,1,x.length) pv.copy(x,v) houseVector(v) z = v[0]; re = z.real; im = z.imag; z = re*re + im*im if z > 0.0: re /= z; im = -im/z if im == 0.0: z=re else: z=complex(re,im) v *= z; houseProd(v,B[i:,i:]); pv.copy(v[1:],x[1:]) if(i < n-2): j = i+1; v.putlength(n-j) x=B.rowview(i)[j:] pv.copy(x,v) houseVector(v); v.conj z = v[0]; re = z.real; im = z.imag; z = re*re + im*im if z > 0.0: re /= z; im = -im/z if im == 0.0: z=re else: z=complex(re,im) v[:] *= z; prodHouse(B[i:,j:],v); pv.copy(v[1:],x[1:]) if(m > n): i=n-1 x=B.colview(i)[i:] v=v.block.bind(0,1,x.length) pv.copy(x,v) houseVector(v) z = v[0]; re = z.real; im = z.imag; z = re*re + im*im if z > 0.0: re /= z; im = -im/z if im == 0.0: z=re else: z=complex(re,im) v[:] *= z; houseProd(v,B[i:,i:]); pv.copy(v[1:],x[1:]) return B def biDiagPhaseToZero(B,L, d, f, R, eps0): # here d and f may be complex nd=d.length nf=f.length assert nd == nf+1, 'For biDiagPhaseToZero the length of d should be nf+1' lc=L.colview rr=R.rowview for i in range(nd): ps = d[i] if ps == 0.0: ps = 1.0 m = 0.0 else: m=abs(ps) # hypot(ps.real,ps.imag) might have better numerical properties than abs ps /= m if(m < eps0): d[i]=0.0 else: d[i]=m if i < f.length: f[i] *= ps.conjugate() lc(i)[:] *= ps for i in range(nf-1): j=i+1 ps=f[i] if ps == 0.0: ps = 1.0 m=0.0 else: m=abs(ps) # hypot(ps.real,ps.imag) might have better numerical properties than abs ps /= m lc(j)[:] *= ps.conjugate() rr(j)[:] *= ps f[i] = m f[j] *= ps j=nf i=j-1 ps=f[i] if ps == 0.0: ps = 1.0 m = 0.0 else: m=abs(ps) ps /= m f[i]=m lc(j)[:] *= ps.conjugate() rr(j)[:] *= ps if 'cvview' in d.type: #From here d and f are real since imaginary is all zero return (d.realview.copy,f.realview.copy) else: return (d.copy,f.copy) def svdBidiag(A,eps): """ Usage: L,d,f,R,eps0= svdBidiag(A,eps) Where: A is a matrix supported types => mview_f, cmview_f, mview_d, cmview_d eps is a small number L is the left decomposition matrix d is a real vector representing the zero diagonal f is a real vector representing the first diagonal eps0 is a small number bassed upon eps and the frobenius norm of A Note: If B is A.empty.fill(0) and B.diagview(0).realview[:]=d; B.diagview(1).realview[:]=f then A=L.prod(B).prod(R) This aglorithm is done out-of-place so A is preserved. """ eps0 = A.normFro/float(A.rowlength) * eps B=A.copy bidiag(B) L=UmatExtract(B) R=VHmatExtract(B) b=B.diagview d,f=biDiagPhaseToZero(B,L, b(0), b(1), R, eps0) return (L,d,f,R,eps0) <file_sep>// // main.c // cVsipTest // // Created by <NAME> on 6/2/17. // Copyright © 2017 JVSIP. All rights reserved. // #include <stdio.h> #include <vsip.h> #include <VI_nuV.h> #include <VI_jofk.h> #include <vsip_fftattributes_d.h> #include <vsip_cvviewattributes_d.h> #include <vsip_vviewattributes_d.h> #include <vsip_cblockattributes_d.h> #include <vsip_blockattributes_d.h> int main(int argc, const char * argv[]) { /* vsip_scalar_vi *pn = (vsip_scalar_vi*) malloc(6 * sizeof(vsip_scalar_vi)); vsip_scalar_vi *p0 = (vsip_scalar_vi*) malloc(6 * sizeof(vsip_scalar_vi)); vsip_scalar_vi *pF = (vsip_scalar_vi*) malloc(6 * sizeof(vsip_scalar_vi)); vsip_length N = 1024 * 5 * 3 * 7 * 11 * 17; vsip_length k = VI_nuV(N, pn, p0, pF); printf("%lu\n",k); for(int i = 0; i<k; i++){ printf("%lu: %lu: %lu\n",pn[i], p0[i], pF[i]); } free(pn); free(p0); free(pF); */ int init = vsip_init((void*)0); int i; vsip_scalar_vi N = 8 * 3 * 3 * 7; vsip_fft_d *fft = vsip_ccfftop_create_d(N, 1.0,VSIP_FFT_FWD,1,VSIP_ALG_TIME); printf("%lu\n",fft->pF[fft->length - 1]); for(i=0; i<fft->length; i++) { printf("%lu, %lu\n",fft->pn[i],fft->p0[i]); } for(i=0; i<fft->N; i++){ printf("%lu\n",fft->index[i]); } vsip_fft_destroy_d(fft); init = vsip_finalize((void*)0); return 0; } <file_sep>import vsiputils as vsip def VU_rowview(v, m, i): mattr=vsip.getattrib(m) vattr=vsip.getattrib(v) vattr.offset = mattr.offset + i * mattr.col_stride vattr.length = mattr.row_length vattr.stride = mattr.row_stride vsip.putattrib(v,vattr); class Sim_ts(object): """ Simulate acoustic data with narrow band point sources from multiple directions and isotropic, band-limited noise. """ def __init__(self,param): c=param['c'] Dsens = param['Dsens'] Nsens = param['Nsens'] Nts = param['Nts'] Fs = param['Fs'] row=vsip.VSIP_ROW mem=vsip.VSIP_MEM_NONE state=vsip.VSIP_STATE_SAVE sym=vsip.VSIP_NONSYM rng=vsip.VSIP_PRNG L = int(2 * Fs/(Nsens * Dsens/c) + Nts + 1) self.Nsim_freqs = param['Nsim_freqs'] self.Nsens = Nsens self.Nsim_noise=param['Nsim_noise'] self.Nts = Nts self.Fs = Fs kernel = vsip.create('kaiser_d',(6,1,0)) self.fir = vsip.create('fir_d',(kernel, sym, 2*L, 2, state, 0,0)) self.noise = vsip.create('vview_d',(2*L,mem)) self.bl_noise = vsip.create('vview_d',(L,mem)) self.rand = vsip.create('randstate',(7,1,1,rng)) self.t = vsip.create('vview_d',(Nts,mem)) vsip.ramp(0,1.0/Fs,self.t) #vector of sample times self.t_dt = vsip.create('vview_d',(Nts,mem)) self.m_data = vsip.create('mview_d',(Nsens,Nts,row,mem)) self.v_data = vsip.rowview(self.m_data,0) self.d_t = param['Dsens']/param['c'] #travel time at end-fire between sensors self.sim_freqs = param['sim_freqs'] self.sim_bearings = param['sim_bearings'] vsip.allDestroy(kernel) def __del__(self): vsip.destroy(self.fir) vsip.allDestroy(self.noise) vsip.allDestroy(self.bl_noise) vsip.destroy(self.rand) vsip.allDestroy(self.t) vsip.allDestroy(self.t_dt) vsip.destroy(self.v_data) vsip.allDestroy(self.m_data) def nb_sim(self): from numpy import pi,cos for i in range(self.Nsim_freqs): f=self.sim_freqs[i] b=self.d_t * cos(self.sim_bearings[i] * pi/180.0) for j in range(self.Nsens): dt = float(j) * b vsip.add(dt,self.t,self.t_dt) vsip.mul(2 * pi * f, self.t_dt, self.t_dt); vsip.cos(self.t_dt,self.t_dt) vsip.mul(3.0,self.t_dt,self.t_dt) VU_rowview(self.v_data,self.m_data,j) vsip.add(self.t_dt,self.v_data,self.v_data) def noise_sim(self): from numpy import pi, cos d_t=self.d_t * self.Fs #sensor-to-sensor travel time at end-fire in samples o_0 = d_t * self.Nsens + 1 # array travel time at end-fire in samples a_stp = pi/self.Nsim_noise # angle step bl_attr = vsip.getattrib(self.bl_noise) for j in range(self.Nsim_noise): a_crct = cos(float(j) * a_stp) vsip.randn(self.rand,self.noise) vsip.firfilt(self.fir,self.noise,self.bl_noise) vsip.mul(12.0/float(self.Nsim_noise),self.bl_noise,self.bl_noise) vsip.putlength(self.bl_noise,self.Nts); for i in range(self.Nsens): vsip.putoffset(self.bl_noise,int(o_0 + i * d_t * a_crct)) VU_rowview(self.v_data,self.m_data,i) vsip.add(self.bl_noise,self.v_data,self.v_data) vsip.putattrib(self.bl_noise,bl_attr); vsip.add(-vsip.meanval(self.m_data),self.m_data,self.m_data); def zero(self): vsip.fill(0.0,self.m_data) def instance(self): return self.m_data <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmkron_f.h,v 2.0 2003/02/22 15:23:21 judd Exp $ */ #include"VU_cmprintm_f.include" static void cmkron_f(void){ printf("********\nTEST cmkron_f\n"); { vsip_cscalar_f alpha = vsip_cmplx_f(-3,2); vsip_scalar_f data_a_r[] = { 1, 1, 2, 0.5}; /* (2,2) rowmajor */ vsip_scalar_f data_a_i[] = { 1, -1, .5, 2}; vsip_scalar_f data_b_r[] = { 3, 4, 1, 5, 3, 4, 2, 2, 3}; /* (3,3) rowmajor */ vsip_scalar_f data_b_i[] = { 1, 1, 5, 1, 0.5, 1, 2, -2, -1}; vsip_scalar_f ans_r[] = { -14.0, -19.0, 0, -8.0, -9.0, -26.00, -24.0, -14.5, -19.0, -10.0, -5.5, -9.00, -8.0, -12.0, -16.0, -12.0, 8.0, 2.00, -23.5, -30.5, -19.5, -11.5, -17.0, 19.50, -37.5, -22.25, -30.5, -22.5, -14.0, -17.00, -19.0, -9.0, -18.5, -1.0, -21.0, -21.50}; vsip_scalar_f ans_i[] = { -8.0, -9.0, -26.0, 14.0, 19.0, 0, -10.0, -5.5, -9.0, 24.0, 14.5, 19.0, -12.0, 8.0, 2.0, 8.0, 12.0, 16.0, 0.5, 3.0, -32.5, -20.5, -25.5, -32.5, 5.5, 4.0, 3.0, -30.5, -17.75, -25.5, -9.0, 19.0, 14.5, -21.0, 1.0, -9.5}; vsip_cblock_f *block_a = vsip_cblockbind_f(data_a_r,data_a_i,4,VSIP_MEM_NONE); vsip_cblock_f *block_b = vsip_cblockbind_f(data_b_r,data_b_i,9,VSIP_MEM_NONE); vsip_cblock_f *block = vsip_cblockcreate_f(100,VSIP_MEM_NONE); vsip_cblock_f *ans_block = vsip_cblockbind_f(ans_r,ans_i,36,VSIP_MEM_NONE); vsip_cmview_f *a = vsip_cmbind_f(block_a,0,2,2,1,2); vsip_cmview_f *t_b = vsip_cmbind_f(block_b,0,3,3,1,3); vsip_cmview_f *b = vsip_cmbind_f(block,95,-1,3,-9,3); vsip_cmview_f *c = vsip_cmcreate_f(6,6,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *ansm = vsip_cmbind_f(ans_block,0,6,6,1,6); vsip_cmview_f *chk = vsip_cmcreate_f(6,6,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *chk_r = vsip_mrealview_f(chk); vsip_cblockadmit_f(block_a,VSIP_TRUE); vsip_cblockadmit_f(block_b,VSIP_TRUE); vsip_cblockadmit_f(ans_block,VSIP_TRUE); vsip_cmcopy_f_f(t_b,b); printf("vsip_cmkron_f(alpha,a,b,c)\n"); vsip_cmkron_f(alpha,a,b,c); printf("alpha = %f %+fi\n",alpha.r,alpha.i); printf("matrix a\n");VU_cmprintm_f("8.6",a); printf("matrix b\n");VU_cmprintm_f("8.6",b); printf("matrix c\n");VU_cmprintm_f("8.6",c); printf("right answer\n");VU_cmprintm_f("8.4",ansm); vsip_cmsub_f(c,ansm,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a); vsip_cmalldestroy_f(t_b); vsip_cmalldestroy_f(b); vsip_cmalldestroy_f(c); vsip_mdestroy_f(chk_r); vsip_cmalldestroy_f(chk); vsip_cmalldestroy_f(ansm); } return; } <file_sep>/* Created by RJudd January 7, 1999 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_ccfftmip_d_def.h,v 2.0 2003/02/22 15:18:29 judd Exp $ */ #include"VI_fftm_building_blocks_d.h" void vsip_ccfftmip_d(const vsip_fftm_d *Offt, const vsip_cmview_d *y) { vsip_fftm_d Nfft = *Offt; vsip_fftm_d *fftm = &Nfft; VI_ccfftmip_d(fftm,y); } <file_sep>import Foundation import vsip public func VU_vfprintyg_d(format: String, a: OpaquePointer, fname: String){ let N = vsip_vgetlength_d(a); let of = fopen(fname,"w+"); for i in 0..<N { let out = String(format: format, vsip_vget_d(a,i)).cString(using: .ascii) fwrite(out, MemoryLayout<Int8>.size, out!.count - 1, of) } fclose(of); } <file_sep>from vsip import * import vsiputils as vsip from numpy import sqrt def VI_cgivens_d( a, b): """ returns cos, sin, r """ c = vsip_cmplx_d(0.0,0.0) s = vsip_cmplx_d(0.0,0.0) r = vsip_cmplx_d(0.0,0.0) am = vsip_cmag_d(a) bm = vsip_cmag_d(b) if am == 0.0: r.r = b.r; r.i=b.i; s.r = 1.0; else: scale = am + bm; alpha = vsip_cmplx_d(a.r/am, a.i/am) scalesq = scale * scale norm = scale * sqrt((am*am)/scalesq + (bm * bm)/scalesq) c.r =am/norm s.r = (alpha.r * b.r + alpha.i * b.i)/norm s.i = (-alpha.r * b.i + alpha.i * b.r)/norm r.r = alpha.r * norm; r.i = alpha.i * norm return (c,s,r) def VI_cgivens_r_d(A): if vsip.getType(A)[1] != 'cmview_d': print("need complex cmview_d for input"); else: m = vsip.getcollength(A) n = vsip.getrowlength(A) for j in range(n): for i in range(m-1,j,-1): a=vsip.get(A,(i-1,j)) b=vsip.get(A,(i,j)) (c,s01,r)=VI_cgivens_d(a,b); # rotate r so the iamginary part is 0 a0p_r=vsip_cmag_d(r) vsip.put(A,(i-1,j),vsip_cmplx_d(a0p_r,0)) vsip.put(A,(i,j),vsip_cmplx_d(0,0)) # store a rotation vector in r if a0p_r != 0: r.r = r.r/a0p_r r.i = -r.i / a0p_r s10 = vsip_cmplx_d(-s01.r,s01.i) for k in range(1,n-j): a0=vsip.get(A,(i-1,j+k)) a1=vsip.get(A,(i,j+k)) a0_r=a0.r; a1_r=a1.r a0_i=a0.i; a1_i=a1.i a0 = vsip_cmplx_d(a0_r * c.r + a1_r * s01.r - a1_i * s01.i, a0_i * c.r + s01.r * a1_i + a1_r * s01.i) # correct a0 for rotation and place in matrix a0_p=vsip_cmplx_d(r.r * a0.r - r.i * a0.i, r.r * a0.i + r.i * a0.r) a1_p=vsip_cmplx_d(a1_r * c.r + s10.r * a0_r - s10.i * a0_i, a1_i * c.r + s10.r * a0_i + s10.i * a0_r) vsip.put(A,(i-1,j+k),a0_p) vsip.put(A,(i,j+k),a1_p) return A <file_sep>/* Created RJudd September 18, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mcreate_i.c,v 2.0 2003/02/22 15:18:55 judd Exp $ */ #include"vsip.h" #include"VI_blockcreate_i.h" #include"VI_blockdestroy_i.h" vsip_mview_i* (vsip_mcreate_i)( vsip_length col_length, vsip_length row_length, vsip_major major, vsip_memory_hint mem_hint) { vsip_block_i* b = VI_blockcreate_i( (vsip_length)(col_length * row_length), mem_hint); vsip_mview_i* v = (vsip_mview_i*)NULL; if(b != NULL){ v = (major == VSIP_ROW) ? vsip_mbind_i(b, (vsip_offset)0, (vsip_stride)row_length, col_length, (vsip_stride)1, row_length) : vsip_mbind_i(b, (vsip_offset)0, (vsip_stride)1,col_length, (vsip_stride)col_length, row_length); if(v == (vsip_mview_i*)NULL) VI_blockdestroy_i(b); } return v; } <file_sep>/* Created RJudd March 18, 2012 */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"vsip.h" #include"vsip_rcfirattributes_f.h" void vsip_rcfir_getattr_f( const vsip_rcfir_f *fir, vsip_rcfir_attr *attr) { attr->symm = fir->symm; attr->kernel_len = fir->M; attr->decimation = fir->D; attr->in_len = fir->N; attr->out_len = fir->N/fir->D + ((fir->N % fir->D) ? 1:0); attr->state = fir->state; return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: tmisc_view_f.h,v 2.1 2009/09/05 18:01:45 judd Exp $ */ static void tmisc_view_f(void){ printf("********\nTEST tmisc_view_f\n"); { vsip_index k,j,i; vsip_scalar_f data_r[4][3][4] = {{{0.0, 0.01, 0.02, 0.03}, \ {0.1, 0.11, 0.12, 0.13}, \ {0.2, 0.21, 0.22, 0.23}}, \ {{1.0, 1.01, 1.02, 1.03}, \ {1.1, 1.11, 1.12, 1.13}, \ {1.2, 1.21, 1.22, 1.23}}, \ {{2.0, 2.01, 2.02, 2.03}, \ {2.1, 2.11, 2.12, 2.13}, \ {2.2, 2.21, 2.22, 2.23}}, \ {{3.0, 3.01, 3.02, 3.03}, \ {3.1, 3.11, 3.12, 3.13}, \ {3.2, 3.21, 3.22, 3.23}}}; /* if a problem with tcreate is suspected check both leading and trailing options here */ vsip_tview_f *tview_a = vsip_tcreate_f(12,9,12,VSIP_LEADING,VSIP_MEM_NONE); /* vsip_tview_f *tview_a = vsip_tcreate_f(12,9,12,VSIP_TRAILING,VSIP_MEM_NONE); */ vsip_block_f *block_a = vsip_tgetblock_f(tview_a); vsip_tview_f *tview_b = vsip_tsubview_f(tview_a,1,2,3,4,3,4); vsip_stride z_a_st = vsip_tgetzstride_f(tview_a); vsip_stride y_a_st = vsip_tgetystride_f(tview_a); vsip_stride x_a_st = vsip_tgetxstride_f(tview_a); vsip_offset b_o_calc = z_a_st + 2 * y_a_st + 3 * x_a_st; vsip_offset b_o_get = vsip_tgetoffset_f(tview_b); vsip_tview_f *v = vsip_tbind_f(block_a,b_o_calc, z_a_st,4, y_a_st,3, x_a_st,4); vsip_mview_f *mview = (vsip_mview_f*)NULL; vsip_vview_f *vview = (vsip_vview_f*)NULL; vsip_tview_f *tview = (vsip_tview_f*)NULL; vsip_scalar_f a; vsip_scalar_f chk = 0; printf("z_a_st %d; y_a_st %d; x_a_st %d\n",(int)z_a_st,(int)y_a_st,(int)x_a_st); fflush(stdout); printf("b_o_calc %u; b_o_get %u\n",(unsigned)b_o_calc,(unsigned)b_o_get); fflush(stdout); for(k = 0; k < 4; k++){ for(j = 0; j < 3; j++){ for(i = 0; i < 4; i++){ a = data_r[k][j][i]; vsip_tput_f(v,k,j,i,a); } } } printf("test tmatrixview_f\n"); printf("TMZY\n"); fflush(stdout); for(i = 0; i < 4; i++){ mview = vsip_tmatrixview_f(v,VSIP_TMZY,i); for(j = 0; j < 3; j++){ for(k = 0; k < 4; k++){ a = vsip_mget_f(mview,k,j); a -= data_r[k][j][i]; chk += a * a; } } vsip_mdestroy_f(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TMYX\n"); fflush(stdout); for(k = 0; k < 4; k++){ mview = vsip_tmatrixview_f(v,VSIP_TMYX,k); for(j = 0; j < 3; j++){ for(i = 0; i < 4; i++){ a = vsip_mget_f(mview,j,i); a -= data_r[k][j][i]; chk += a * a; } } vsip_mdestroy_f(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TMZX\n"); fflush(stdout); for(j = 0; j < 3; j++){ mview = vsip_tmatrixview_f(v,VSIP_TMZX,j); for(k = 0; k < 4; k++){ for(i = 0; i < 4; i++){ a = vsip_mget_f(mview,k,i); a -= data_r[k][j][i]; chk += a * a; } } vsip_mdestroy_f(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test tvectview_f\n"); printf("TVX \n"); fflush(stdout); for(k=0; k<4; k++){ for(j=0; j<3; j++){ vview = vsip_tvectview_f(v,VSIP_TVX,k,j); for(i=0; i<4; i++){ a = vsip_vget_f(vview,i); a -= data_r[k][j][i]; chk += a * a; } } vsip_vdestroy_f(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test tvectview_f\n"); printf("TVY \n"); fflush(stdout); for(k=0; k<4; k++){ for(i=0; i<4; i++){ vview = vsip_tvectview_f(v,VSIP_TVY,k,i); for(j=0; j<3; j++){ a = vsip_vget_f(vview,j); a -= data_r[k][j][i]; chk += a * a ; } } vsip_vdestroy_f(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TVZ \n"); fflush(stdout); for(j=0; j<3; j++){ for(i=0; i<4; i++){ vview = vsip_tvectview_f(v,VSIP_TVZ,j,i); for(k=0; k<4; k++){ a = vsip_vget_f(vview,k); a -= data_r[k][j][i]; chk += a * a; } } vsip_vdestroy_f(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test ttransview_f\n"); fflush(stdout); printf("NOP\n"); fflush(stdout); tview = vsip_ttransview_f(v,VSIP_TTRANS_NOP); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_f(tview,k,j,i); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_f(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YX\n"); fflush(stdout); tview = vsip_ttransview_f(v,VSIP_TTRANS_YX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_f(tview,k,i,j); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_f(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("ZY\n"); fflush(stdout); tview = vsip_ttransview_f(v,VSIP_TTRANS_ZY); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_f(tview,j,k,i); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_f(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("ZX\n"); fflush(stdout); tview = vsip_ttransview_f(v,VSIP_TTRANS_ZX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_f(tview,i,j,k); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_f(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YXZY\n"); fflush(stdout); tview = vsip_ttransview_f(v,VSIP_TTRANS_YXZY); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_f(tview,i,k,j); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_f(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YXZX\n"); fflush(stdout); tview = vsip_ttransview_f(v,VSIP_TTRANS_YXZX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_f(tview,j,i,k); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_f(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; vsip_tdestroy_f(v); vsip_tdestroy_f(tview_b); vsip_talldestroy_f(tview_a); } return; } <file_sep>#include"vsip.h" #undef vsip_acos_d vsip_scalar_d vsip_acos_d(vsip_scalar_d); #undef vsip_acos_f vsip_scalar_f vsip_acos_f(vsip_scalar_f); #undef vsip_asin_d vsip_scalar_d vsip_asin_d(vsip_scalar_d); #undef vsip_asin_f vsip_scalar_f vsip_asin_f(vsip_scalar_f); #undef vsip_atan_d vsip_scalar_d vsip_atan_d(vsip_scalar_d); #undef vsip_atan_f vsip_scalar_f vsip_atan_f(vsip_scalar_f); #undef vsip_ceil_d vsip_scalar_d vsip_ceil_d(vsip_scalar_d); #undef vsip_ceil_f vsip_scalar_f vsip_ceil_f(vsip_scalar_f); #undef vsip_cos_d vsip_scalar_d vsip_cos_d(vsip_scalar_d); #undef vsip_cos_f vsip_scalar_f vsip_cos_f(vsip_scalar_f); #undef vsip_cosh_d vsip_scalar_d vsip_cosh_d(vsip_scalar_d); #undef vsip_cosh_f vsip_scalar_f vsip_cosh_f(vsip_scalar_f); #undef vsip_sin_d vsip_scalar_d vsip_sin_d(vsip_scalar_d); #undef vsip_sin_f vsip_scalar_f vsip_sin_f(vsip_scalar_f); #undef vsip_sinh_d vsip_scalar_d vsip_sinh_d(vsip_scalar_d); #undef vsip_sinh_f vsip_scalar_f vsip_sinh_f(vsip_scalar_f); #undef vsip_atan2_d vsip_scalar_d vsip_atan2_d(vsip_scalar_d, vsip_scalar_d); #undef vsip_atan2_f vsip_scalar_f vsip_atan2_f(vsip_scalar_f, vsip_scalar_f); #undef vsip_hypot_d vsip_scalar_d vsip_hypot_d(vsip_scalar_d, vsip_scalar_d); #undef vsip_hypot_f vsip_scalar_f vsip_hypot_f(vsip_scalar_f, vsip_scalar_f); #undef vsip_exp_d vsip_scalar_d vsip_exp_d(vsip_scalar_d); #undef vsip_exp_f vsip_scalar_f vsip_exp_f(vsip_scalar_f); #undef vsip_floor_d vsip_scalar_d vsip_floor_d(vsip_scalar_d); #undef vsip_floor_f vsip_scalar_f vsip_floor_f(vsip_scalar_f); #undef vsip_log_d vsip_scalar_d vsip_log_d(vsip_scalar_d); #undef vsip_log_f vsip_scalar_f vsip_log_f(vsip_scalar_f); #undef vsip_log10_d vsip_scalar_d vsip_log10_d(vsip_scalar_d); #undef vsip_log10_f vsip_scalar_f vsip_log10_f(vsip_scalar_f); #undef vsip_mag_d vsip_scalar_d vsip_mag_d(vsip_scalar_d); #undef vsip_mag_f vsip_scalar_f vsip_mag_f(vsip_scalar_f); #undef vsip_pow_d vsip_scalar_d vsip_pow_d(vsip_scalar_d,vsip_scalar_d); #undef vsip_pow_f vsip_scalar_f vsip_pow_f(vsip_scalar_f, vsip_scalar_f); #undef vsip_sqrt_d vsip_scalar_d vsip_sqrt_d(vsip_scalar_d); #undef vsip_sqrt_f vsip_scalar_f vsip_sqrt_f(vsip_scalar_f); #undef vsip_tan_d vsip_scalar_d vsip_tan_d(vsip_scalar_d); #undef vsip_tan_f vsip_scalar_f vsip_tan_f(vsip_scalar_f); #undef vsip_tanh_d vsip_scalar_d vsip_tanh_d(vsip_scalar_d); #undef vsip_tanh_f vsip_scalar_f vsip_tanh_f(vsip_scalar_f); #undef vsip_exp10_d vsip_scalar_d vsip_exp10_d(vsip_scalar_d); #undef vsip_exp10_f vsip_scalar_f vsip_exp10_f(vsip_scalar_f); #undef vsip_min_d vsip_scalar_d vsip_min_d(vsip_scalar_d,vsip_scalar_d); #undef vsip_min_f vsip_scalar_f vsip_min_f(vsip_scalar_f,vsip_scalar_f); #undef vsip_max_d vsip_scalar_d vsip_max_d(vsip_scalar_d,vsip_scalar_d); #undef vsip_max_f vsip_scalar_f vsip_max_f(vsip_scalar_f,vsip_scalar_f); <file_sep>// // View.swift // SJVsip // // Created by <NAME> on 11/4/17. // Copyright © 2017 JVSIP. All rights reserved. // import Foundation import vsip public class View: NSObject { public enum Shape: String { case v // vector case m // matrix } let block: Block let shape : Shape public var type: Scalar.Types{ return block.type } let jInit : JVSIP var myId = NSNumber(value: 0 as Int32) // Used to initialize a derived JVSIP View object public init(block: Block, shape: View.Shape){ self.block = block self.shape = shape jInit = JVSIP() myId = jInit.myId super.init() } func real(_ vsip: OpaquePointer) -> (Block, OpaquePointer){ let t = (self.type, self.shape) switch t{ case (.cf, .v): if let cRealView = vsip_vrealview_f(vsip) { let blk = vsip_vgetblock_f(cRealView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cRealView) } else { break } case(.cf, .m): if let cRealView = vsip_mrealview_f(vsip){ let blk = vsip_mgetblock_f(cRealView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cRealView) } else { break } case (.cd, .v): if let cRealView = vsip_vrealview_d(vsip){ let blk = vsip_vgetblock_d(cRealView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cRealView) } else { break } case (.cd, .m): if let cRealView = vsip_mrealview_d(vsip){ let blk = vsip_mgetblock_d(cRealView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cRealView) } else { break } default: print("Case not found") break } preconditionFailure("Failure of imag method") } public func imag(_ vsip: OpaquePointer) -> (Block?, OpaquePointer?){ let t = (self.type, self.shape) switch t{ case (.cf, .v): if let cImagView = vsip_vimagview_f(vsip){ let blk = vsip_vgetblock_f(cImagView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cImagView) } else { break } case(.cf, .m): if let cImagView = vsip_mimagview_f(vsip){ let blk = vsip_mgetblock_f(cImagView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cImagView) } else { break } case (.cd, .v): if let cImagView = vsip_vimagview_d(vsip){ let blk = vsip_vgetblock_d(cImagView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cImagView) } else { break } case (.cd, .m): if let cImagView = vsip_mimagview_d(vsip){ let blk = vsip_mgetblock_d(cImagView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cImagView) } else { break } default: print("Case not found") break } preconditionFailure("Failure of imag method") } // MARK: Attribute get/put options public func get(_ vsip:OpaquePointer, index: vsip_index) -> Scalar { let t = self.type switch t{ case .f: return Scalar(vsip_vget_f(vsip, index)) case .d: return Scalar(vsip_vget_d(vsip, index)) case .cf: return Scalar(vsip_cvget_f(vsip, index)) case .cd: return Scalar(vsip_cvget_d(vsip, index)) case .vi: return Scalar(vsip_vget_vi(vsip, index)) case .mi: return Scalar(vsip_vget_mi(vsip,index)) case .li: return Scalar(vsip_vget_li(vsip, index)) case .i: return Scalar(vsip_vget_i(vsip, index)) case .si: return Scalar(vsip_vget_si(vsip, index)) case .uc: return Scalar(vsip_vget_uc(vsip, index)) default: preconditionFailure("No Scalar Found for this case") } } public func get(_ vsip:OpaquePointer, rowIndex: vsip_index, columnIndex: vsip_index) -> Scalar { let t = self.type switch t{ case .f: return Scalar(vsip_mget_f(vsip, rowIndex, columnIndex)) case .d: return Scalar(vsip_mget_d(vsip, rowIndex, columnIndex)) case .cf: return Scalar(vsip_cmget_f(vsip, rowIndex, columnIndex)) case .cd: return Scalar(vsip_cmget_d(vsip,rowIndex, columnIndex)) case .li: return Scalar(vsip_mget_li(vsip,rowIndex, columnIndex)) case .i: return Scalar(vsip_mget_i(vsip,rowIndex, columnIndex)) case .si: return Scalar(vsip_mget_si(vsip,rowIndex, columnIndex)) case .uc: return Scalar(vsip_mget_uc(vsip,rowIndex, columnIndex)) default: preconditionFailure("No Scalar Found for this case") } } public func put(_ vsip:OpaquePointer, index: vsip_index, value: Scalar){ let t = self.type switch t{ case .f: vsip_vput_f(vsip, index, value.vsip_f) case .d: vsip_vput_d(vsip, index, value.vsip_d) case .cf: vsip_cvput_f(vsip,index,value.vsip_cf) case .cd: vsip_cvput_d(vsip,index,value.vsip_cd) case .vi: vsip_vput_vi(vsip,index,value.vsip_vi) case .mi: vsip_vput_mi(vsip,index,value.vsip_mi) case .li: vsip_vput_li(vsip, index, value.vsip_li) case .i: vsip_vput_i(vsip,index,value.vsip_i) case .si: vsip_vput_si(vsip,index,value.vsip_si) case .uc: vsip_vput_uc(vsip,index,value.vsip_uc) default: preconditionFailure("No Scalar Found for this case") } } public func put(_ vsip:OpaquePointer, rowIndex: vsip_index, columnIndex: vsip_index, value: Scalar){ let t = self.type switch t{ case .f: vsip_mput_f(vsip, rowIndex, columnIndex, value.vsip_f) case .d: vsip_mput_d(vsip, rowIndex, columnIndex, value.vsip_d) case .cf: vsip_cmput_f(vsip, rowIndex, columnIndex,value.vsip_cf) case .cd: vsip_cmput_d(vsip, rowIndex, columnIndex,value.vsip_cd) case .li: vsip_mput_li(vsip, rowIndex, columnIndex, value.vsip_li) case .i: vsip_mput_i(vsip, rowIndex, columnIndex,value.vsip_i) case .si: vsip_mput_si(vsip, rowIndex, columnIndex,value.vsip_si) case .uc: vsip_mput_uc(vsip, rowIndex, columnIndex,value.vsip_uc) default: preconditionFailure("No Scalar Found for this case") } } } <file_sep>#ifndef _JVSIP_H #define _JVSIP_H #include<vsip.h> void jvsip_mprod2_d( const vsip_mview_d*, const vsip_mview_d*, const vsip_mview_d*); void jvsip_mprod2_f( const vsip_mview_f*, const vsip_mview_f*, const vsip_mview_f*); void jvsip_cmprod2_d( const vsip_cmview_d*, const vsip_cmview_d*, const vsip_cmview_d*); void jvsip_cmprod2_f( const vsip_cmview_f*, const vsip_cmview_f*, const vsip_cmview_f*); void jvsip_cmprodh2_d( const vsip_cmview_d*, const vsip_cmview_d*, const vsip_cmview_d*); void jvsip_cmprodh2_f( const vsip_cmview_f*, const vsip_cmview_f*, const vsip_cmview_f*); #endif /* _JVSIP_H */ <file_sep>// // main.cpp // test1 // // Created by <NAME> on 4/21/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #include <iostream> #include <cstring> #include "../jvsiph.h" extern "C"{ #include<vsip.h> } int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; jvsip::Scalar ascalar(50); std::cout << ascalar.scalar_i() << std::endl; std::cout << jvsip::Scalar(-100l).stride() << std::endl; jvsip::Block aBlock("f",100); jvsip::View aView(aBlock,0,1,100); aView.ramp(jvsip::Scalar(0.0f),jvsip::Scalar(0.5f)); vsip_vview_f *aVView=(vsip_vview_f*)aView.vsip(); std::cout << 10 << " : " << aView[10].scalar_f()<< std::endl; vsip_vput_f(aVView,10,9.2); vsip_svmul_f(2.0, aVView, aVView); std::cout << aView[jvsip::Scalar(10)].scalar_f() << std::endl; std::cout << 10.0f << " : " << vsip_vget_f((vsip_vview_f*)aView.vsip(),10)<< std::endl; for(int i=0; i<aView.length().length(); i++) std::cout << aView[i].scalar_f() << std::endl; aView.length(aView.length().length()/3); for(int i=0; i<aView.length().length(); i++) std::cout << aView[i].scalar_f() << std::endl; aView.offset(jvsip::Scalar(aView.offset().offset()+2)); for(int i=0; i<aView.length().length(); i++) std::cout << aView[i].scalar_f() << std::endl; aView.stride(jvsip::Scalar(2)); for(int i=0; i<aView.length().length(); i++) std::cout << aView[i].scalar_f() << std::endl; return 0; } <file_sep>/* Created by RJudd September 9, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_ccfftmip_f_loop.h,v 2.0 2003/02/22 15:18:30 judd Exp $ */ /* Use a loop of vsip_ccfftip_f.h to calculate fftm */ /* input matrix x, output matrix y, fftm object fftm */ #include"VI_cmrowview_f.h" #include"VI_cmcolview_f.h" void vsip_ccfftmip_f(const vsip_fftm_f *Offt, const vsip_cmview_f *y) { vsip_fftm_f Nfft = *Offt; vsip_fftm_f *fftm = &Nfft; vsip_fft_f *fft = (vsip_fft_f*)fftm->ext_fftm_obj; vsip_index k = 0; vsip_cvview_f zz; if(fftm->major == VSIP_ROW){ while(k < y->col_length){ vsip_ccfftip_f(fft, VI_cmrowview_f(y,k,&zz)); k++; } } else { /* must be column */ while(k < y->row_length){ vsip_ccfftip_f(fft, VI_cmcolview_f(y,k,&zz)); k++; } } } <file_sep>import pyJvsip as pv N=6 A = pv.create('vview_f',N).ramp(0,1) B = A.empty.fill(5.0) C = A.empty.fill(0.0) print('A = '+A.mstring('%+2.0f')) print('B = '+B.mstring('%+2.0f')) pv.add(A,B,C) print('C = A+B') print('C = '+C.mstring('%+2.0f')) """ OUTPUT A = [ 0 1 2 3 4 5 6 7] B = [ 5 5 5 5 5 5 5 5] C = A+B C = [ 5 6 7 8 9 10 11 12] """ <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cvouter_covariance_f.h,v 2.1 2004/05/16 05:02:35 judd Exp $ */ #include"VU_cmprintm_f.include" #include"VU_cvprintm_f.include" static void cvouter_covariance_f(void){ printf("********\nTEST cvouter_f\n"); { vsip_cscalar_f alpha = vsip_cmplx_f(4.0,0.0); vsip_scalar_f data_a_r[] = { 1.1, 1.2, 2.1, 2.2, -3.1, -3.3}; vsip_scalar_f data_a_i[] = { -1.1, -2.2, -3.1, -4.2, 0.1, -2.3}; vsip_cblock_f *block_a = vsip_cblockbind_f(data_a_r,data_a_i,6,VSIP_MEM_NONE); vsip_cvview_f *a = vsip_cvbind_f(block_a,0,1,6); vsip_cmview_f *ansm = vsip_cmcreate_f(6,6,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *chk = vsip_cmcreate_f(6,6,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *R = vsip_cmcreate_f(6,6,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *chk_i = vsip_mimagview_f(chk); vsip_cblockadmit_f(block_a,VSIP_TRUE); { /* make the answer matrix */ vsip_index i,j; for(i=0; i< vsip_cvgetlength_f(a); i++){ vsip_cscalar_f a1 = vsip_cvget_f(a,i); vsip_cmput_f(ansm,i,i,vsip_cmplx_f(vsip_cmagsq_f(a1),0)); for(j=i+1; j<vsip_cvgetlength_f(a); j++){ vsip_cscalar_f a2 = vsip_cmul_f(a1,vsip_conj_f(vsip_cvget_f(a,j))); vsip_cmput_f(ansm,i,j,a2); vsip_cmput_f(ansm,j,i,vsip_conj_f(a2)); } } vsip_rscmmul_f(4.0,ansm,ansm); } printf("vsip_cvouter_f(alpha,a,a,R)\n"); vsip_cvouter_f(alpha,a,a,R); printf("alpha = (%f %+fi) \n",vsip_real_f(alpha),vsip_imag_f(alpha)); printf("vector a\n");VU_cvprintm_f("8.6",a); printf("matrix R\n");VU_cmprintm_f("8.6",R); printf("right answer\n");VU_cmprintm_f("8.4",ansm); vsip_cmsub_f(R,ansm,chk); vsip_cmmag_f(chk,chk_i); vsip_mclip_f(chk_i,.0001,.0001,0,1,chk_i); if(vsip_msumval_f(chk_i) > .5) printf("error\n"); else printf("correct\n"); vsip_cvalldestroy_f(a); vsip_cmalldestroy_f(R); vsip_mdestroy_f(chk_i); vsip_cmalldestroy_f(chk); vsip_cmalldestroy_f(ansm); } return; } <file_sep>import matplotlib.pyplot as plt import beamformer as bf bf.beamformer('param_file') plt.show() <file_sep>def firfbe(a,wi,Abe): """ FIR Find Band Edges % w = fir_fbe(a,wi,Abe); % find band edges of an FIR filter using Newton's method % using initial estimates % % A : a(1)+a(2)*cos(w)+...+a(n+1)*cos(n*w) % wi : initial values for the band edges % Abe : value of H at the band edges """ m=a.empty.ramp(0,1) w = wi.copy for k in range(15): A = w.outer(m).cos.prod(a)-Abe A1 = w.outer(m).sin.neg.prod(m*a) w -= A*A1.recip return w <file_sep>/* Created RJudd */ /* $Id: vsip_permute_destroy.c,v 2.1 2008/08/17 18:01:49 judd Exp $ */ /* * vsip_permute_destroy.c * VU_permute * * Created by <NAME> on 7/21/07. * */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"vsip.h" #include"vsip_permuteattributes.h" void vsip_permute_destroy(vsip_permute *perm){ if(perm){ if(perm->in) free(perm->in); if(perm->b) free(perm->b); free(perm); perm=NULL; } return; } <file_sep> /* // jvsip_ceil.c // jvsip // // Created by <NAME> on 6/20/14. // Copyright (c) 2014 Independent Consultant. All rights reserved. */ /********************************************************************* // This code includes no warranty, express or implied, including / // the warranties of merchantability and fitness for a particular / // purpose. / // No person or entity assumes any legal liability or responsibility / // for the accuracy, completeness, or usefulness of any information, / // apparatus, product, or process disclosed, or represents that / // its use would not infringe privately owned rights. / *********************************************************************/ /********************************************************************* // The MIT License (see copyright for jvsip in top level directory) // http://opensource.org/licenses/MIT **********************************************************************/ #include"vsip.h" #include"vsip_mviewattributes_d.h" #include"vsip_vviewattributes_d.h" #include"vsip_mviewattributes_f.h" #include"vsip_vviewattributes_f.h" #include"vsip_mviewattributes_i.h" #include"vsip_vviewattributes_i.h" #include<math.h> #include"vsip_scalars.h" void vsip_mceil_d_d(const vsip_mview_d* a, const vsip_mview_d* r) { vsip_length n_mj, /* major length */ n_mn; /* minor length */ vsip_stride ast_mj, ast_mn, rst_mj, rst_mn; vsip_scalar_d *rp = (r->block->array) + r->offset * r->block->rstride; vsip_scalar_d *ap = (a->block->array) + a->offset * a->block->rstride; vsip_scalar_d *rp0 = rp; vsip_scalar_d *ap0 = ap; if(r->row_stride < r->col_stride){ n_mj = r->row_length; n_mn = r->col_length; rst_mj = r->row_stride; rst_mn = r->col_stride; ast_mj = a->row_stride; ast_mn = a->col_stride; ast_mj *= a->block->rstride; ast_mn *= a->block->rstride; } else { n_mn = r->row_length; n_mj = r->col_length; rst_mn = r->row_stride; rst_mj = r->col_stride; ast_mn = a->row_stride; ast_mj = a->col_stride; ast_mn *= a->block->rstride; ast_mj *= a->block->rstride; } while(n_mn-- > 0){ vsip_length n = n_mj; while(n-- >0){ *rp = VSIP_CEIL_D(*ap); ap += ast_mj; rp += rst_mj; } ap0 += ast_mn; rp0 += rst_mn; ap = ap0; rp = rp0; } return; } void vsip_mceil_d_i(const vsip_mview_d* a, const vsip_mview_i* r) { vsip_length n_mj, /* major length */ n_mn; /* minor length */ vsip_stride ast_mj, ast_mn, rst_mj, rst_mn; vsip_scalar_i *rp = (r->block->array) + r->offset; vsip_scalar_d *ap = (a->block->array) + a->offset * a->block->rstride; vsip_scalar_i *rp0 = rp; vsip_scalar_d *ap0 = ap; if(r->row_stride < r->col_stride){ n_mj = r->row_length; n_mn = r->col_length; rst_mj = r->row_stride; rst_mn = r->col_stride; ast_mj = a->row_stride; ast_mn = a->col_stride; ast_mj *= a->block->rstride; ast_mn *= a->block->rstride; } else { n_mn = r->row_length; n_mj = r->col_length; rst_mn = r->row_stride; rst_mj = r->col_stride; ast_mn = a->row_stride; ast_mj = a->col_stride; ast_mn *= a->block->rstride; ast_mj *= a->block->rstride; } while(n_mn-- > 0){ vsip_length n = n_mj; while(n-- >0){ vsip_scalar_d t = VSIP_CEIL_D(*ap); if(t == 0.0) *rp = 0; else *rp = t > 0 ? (vsip_scalar_i)(t+DBL_EPSILON):(vsip_scalar_i)(t-DBL_EPSILON); ap += ast_mj; rp += rst_mj; } ap0 += ast_mn; rp0 += rst_mn; ap = ap0; rp = rp0; } return; } void vsip_mceil_f_f(const vsip_mview_f* a, const vsip_mview_f* r) { vsip_length n_mj, /* major length */ n_mn; /* minor length */ vsip_stride ast_mj, ast_mn, rst_mj, rst_mn; vsip_scalar_f *rp = (r->block->array) + r->offset * r->block->rstride; vsip_scalar_f *ap = (a->block->array) + a->offset * a->block->rstride; vsip_scalar_f *rp0 = rp; vsip_scalar_f *ap0 = ap; if(r->row_stride < r->col_stride){ n_mj = r->row_length; n_mn = r->col_length; rst_mj = r->row_stride; rst_mn = r->col_stride; ast_mj = a->row_stride; ast_mn = a->col_stride; rst_mj *= r->block->rstride; rst_mn *= r->block->rstride; ast_mj *= a->block->rstride; ast_mn *= a->block->rstride; } else { n_mn = r->row_length; n_mj = r->col_length; rst_mn = r->row_stride; rst_mj = r->col_stride; ast_mn = a->row_stride; ast_mj = a->col_stride; rst_mn *= r->block->rstride; rst_mj *= r->block->rstride; ast_mn *= a->block->rstride; ast_mj *= a->block->rstride; } while(n_mn-- > 0){ vsip_length n = n_mj; while(n-- >0){ *rp = VSIP_CEIL_F(*ap); ap += ast_mj; rp += rst_mj; } ap0 += ast_mn; rp0 += rst_mn; ap = ap0; rp = rp0; } return; } void vsip_mceil_f_i(const vsip_mview_f* a, const vsip_mview_i* r) { vsip_length n_mj, /* major length */ n_mn; /* minor length */ vsip_stride ast_mj, ast_mn, rst_mj, rst_mn; vsip_scalar_i *rp = (r->block->array) + r->offset; vsip_scalar_f *ap = (a->block->array) + a->offset * a->block->rstride; vsip_scalar_i *rp0 = rp; vsip_scalar_f *ap0 = ap; if(r->row_stride < r->col_stride){ n_mj = r->row_length; n_mn = r->col_length; rst_mj = r->row_stride; rst_mn = r->col_stride; ast_mj = a->row_stride; ast_mn = a->col_stride; ast_mj *= a->block->rstride; ast_mn *= a->block->rstride; } else { n_mn = r->row_length; n_mj = r->col_length; rst_mn = r->row_stride; rst_mj = r->col_stride; ast_mn = a->row_stride; ast_mj = a->col_stride; ast_mn *= a->block->rstride; ast_mj *= a->block->rstride; } while(n_mn-- > 0){ vsip_length n = n_mj; while(n-- >0){ vsip_scalar_f t = VSIP_CEIL_F(*ap); if(t == 0.0) *rp = 0; else *rp = t > 0 ? (vsip_scalar_i)(t+DBL_EPSILON):(vsip_scalar_i)(t-DBL_EPSILON); ap += ast_mj; rp += rst_mj; } ap0 += ast_mn; rp0 += rst_mn; ap = ap0; rp = rp0; } return; } void vsip_vceil_d_d(const vsip_vview_d* a, const vsip_vview_d* r) { vsip_length n = r->length; vsip_stride ast = a->stride * a->block->rstride, rst = r->stride * r->block->rstride; vsip_scalar_d *ap = (a->block->array) + a->offset * a->block->rstride; vsip_scalar_d *rp = (r->block->array) + r->offset * r->block->rstride; while(n-- > 0){ *rp = VSIP_CEIL_D(*ap); ap += ast; rp += rst; } } void vsip_vceil_d_i(const vsip_vview_d* a, const vsip_vview_i* r) { vsip_length n = r->length; vsip_stride ast = a->stride * a->block->rstride, rst = r->stride; vsip_scalar_d *ap = (a->block->array) + a->offset * a->block->rstride; vsip_scalar_i *rp = (r->block->array) + r->offset; while(n-- > 0){ vsip_scalar_d t = VSIP_CEIL_D(*ap); if(t == 0.0) *rp = 0; else *rp = t > 0 ? (vsip_scalar_i)(t+DBL_EPSILON):(vsip_scalar_i)(t-DBL_EPSILON); ap += ast; rp += rst; } } void vsip_vceil_f_f(const vsip_vview_f* a, const vsip_vview_f* r) { vsip_length n = r->length; vsip_stride ast = a->stride * a->block->rstride, rst = r->stride * r->block->rstride; vsip_scalar_f *ap = (a->block->array) + a->offset * a->block->rstride; vsip_scalar_f *rp = (r->block->array) + r->offset * r->block->rstride; while(n-- > 0){ *rp = VSIP_CEIL_F(*ap); ap += ast; rp += rst; } } void vsip_vceil_f_i(const vsip_vview_f* a, const vsip_vview_i* r) { vsip_length n = r->length; vsip_stride ast = a->stride * a->block->rstride, rst = r->stride; vsip_scalar_f *ap = (a->block->array) + a->offset * a->block->rstride; vsip_scalar_i *rp = (r->block->array) + r->offset; while(n-- > 0){ vsip_scalar_f t = VSIP_CEIL_F(*ap); if(t == 0.0) *rp = 0; else *rp = t > 0 ? (vsip_scalar_i)(t+DBL_EPSILON):(vsip_scalar_i)(t-DBL_EPSILON); ap += ast; rp += rst; } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mminmgval_d.h,v 2.0 2003/02/22 15:23:25 judd Exp $ */ #include"VU_mprintm_d.include" static void mminmgval_d(void){ printf("\n*******\nTEST mminmgval_d\n\n"); { vsip_scalar_d data1[] = {-1, 2, 0, -5, -6, 3.4, -3.4, 5.6, -.3}; vsip_block_d *block1 = vsip_blockbind_d(data1,9,VSIP_MEM_NONE); vsip_mview_d *a = vsip_mbind_d(block1,0,3,3,1,3); vsip_block_d *block2 = vsip_blockcreate_d(50,VSIP_MEM_NONE); vsip_mview_d *b = vsip_mbind_d(block2,49,-2,3,-8,3); vsip_scalar_mi index; vsip_scalar_mi ind_ans = vsip_matindex(0,2); vsip_scalar_d val; vsip_blockadmit_d(block1,VSIP_TRUE); vsip_mcopy_d_d(a,b); val = vsip_mminmgval_d(a,&index); printf("val = vsip_mminmgval_d(a,index)\n matrix a = \n");VU_mprintm_d("8.6",a); printf("val = %f\n",val); printf("index = (%ld, %ld)\n",vsip_colindex(index),vsip_rowindex(index)); if(fabs(0 - val) > .0001) printf("value error\n"); else printf("value correct\n"); if((vsip_colindex(index) != vsip_colindex(ind_ans)) || (vsip_rowindex(index) != vsip_rowindex(ind_ans))) printf("index error\n"); else printf("index correct\n"); printf("case for non-compact matrix with negative strides\n"); val = vsip_mminmgval_d(b,&index); printf("val = vsip_mminmgval_d(b,index)\n matrix b = \n");VU_mprintm_d("8.6",b); printf("val = %f\n",val); printf("index = (%ld, %ld)\n",vsip_colindex(index),vsip_rowindex(index)); if(fabs(0 - val) > .0001) printf("value error\n"); else printf("value correct\n"); if((vsip_colindex(index) != vsip_colindex(ind_ans)) || (vsip_rowindex(index) != vsip_rowindex(ind_ans))) printf("index error\n"); else printf("index correct\n"); vsip_malldestroy_d(a); vsip_malldestroy_d(b); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vcloneview_mi.h,v 2.0 2003/02/22 15:23:35 judd Exp $ */ static void vcloneview_mi(void){ printf("********\nTEST vcloneview_mi\n"); { vsip_scalar_vi data_r[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; vsip_scalar_vi data_c[10] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; vsip_offset o = 40; vsip_stride s = -3; vsip_length n = 10; vsip_block_mi *b = vsip_blockcreate_mi(100,VSIP_MEM_NONE); vsip_vview_mi *v = vsip_vbind_mi(b,o,s,n); vsip_vview_mi *sv = vsip_vcloneview_mi(v); int chk = 0; int i; for(i=0; i< (int)n; i++){ vsip_scalar_mi a; a.r = data_r[i]; a.c = data_c[i]; vsip_vput_mi(v,i,a); } for(i=0; i< (int)n; i++){ vsip_scalar_mi a = vsip_vget_mi(sv,i); int a_r = (int)(a.r - data_r[i]); int a_c = (int)(a.c - data_c[i]); chk += a_r * a_r + a_c * a_c; } (chk != 0) ? printf("error \n") : printf("correct \n"); fflush(stdout); vsip_vdestroy_mi(sv); vsip_valldestroy_mi(v); } return; } <file_sep>/* Created RJudd November 21, 2012 */ /* See copyright (MIT License) included with distribution */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"vsip.h" #include"vsip_vviewattributes_li.h" vsip_scalar_li (vsip_vminval_li)( const vsip_vview_li* a, vsip_index *j) { { /* register */ vsip_length n = a->length, n0 ; /* register */ vsip_stride ast = a->stride; vsip_scalar_li *ap = (a->block->array) + a->offset, r; n0 = n - 1; r = *ap; if(j != NULL) *j = (vsip_index) 0; while(n-- > 0){ if( r > *ap){ r = *ap; if(j != NULL) *j = (vsip_index) ( n0 - n); } ap += ast; } return r; } } <file_sep>// // jofkTest.swift // vsip // // Created by <NAME> on 6/10/17. // Copyright © 2017 JVSIP. All rights reserved. // import Foundation import vsip public func jofk(){ let _ = vsip_init(nil) // let N = 8 * 3 * 3 * 7 // let fft = vsip_ccfftop_create_d(vsip_scalar_vi(N),1.0,VSIP_FFT_FWD,1,VSIP_ALG_TIME) let _ = vsip_finalize(nil) } <file_sep>#!/bin/sh cc -o svd_test_f svd_test_f.c svd.c -I$HOME/local/src/jvsip/include -L$HOME/local/src/jvsip/lib -lvsip cc -o csvd_test_f csvd_test_f.c svd.c -I$HOME/local/src/jvsip/include -L$HOME/local/src/jvsip/lib -lvsip cc -o svd_test_d svd_test_d.c svd.c -I$HOME/local/src/jvsip/include -L$HOME/local/src/jvsip/lib -lvsip cc -o csvd_test_d csvd_test_d.c svd.c -I$HOME/local/src/jvsip/include -L$HOME/local/src/jvsip/lib -lvsip <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: msumval_bl.h,v 2.0 2003/02/22 15:23:26 judd Exp $ */ #include"VU_mprintm_d.include" static void msumval_bl(void){ printf("\n*******\nTEST msumval_bl\n"); { vsip_scalar_bl data[] = {0, 1, 0, 1, 0, 1, 1, 1, 1, 0}; vsip_mview_bl *m1 = vsip_mbind_bl( vsip_blockbind_bl(data,10,VSIP_MEM_NONE),0,5,2,1,5); vsip_block_bl *block = vsip_blockcreate_bl(1024,VSIP_MEM_NONE); vsip_mview_bl *m = vsip_mbind_bl(block,4,20,2,2,5); vsip_mview_d *pm = vsip_mcreate_d(2,5,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_bl(vsip_mgetblock_bl(m1),VSIP_TRUE); vsip_mcopy_bl_bl(m1,m); printf("matrix m1, user matrix, compact, row major\n"); vsip_mcopy_bl_d(m1,pm); VU_mprintm_d("1.0",pm); printf("matrix m1, VSIPL matrix, irregular, row major\n"); printf("col stride 20, row stride 2\n"); printf("copy m1 to m. Matrix m equals\n"); vsip_mcopy_bl_d(m,pm); VU_mprintm_d("1.0",pm); printf("msumval_bl(m1) = %ld\n",vsip_msumval_bl(m1)); printf("msumval_bl(m) = %ld\n",vsip_msumval_bl(m)); printf("ans should be 6 \n"); if((6 - vsip_msumval_bl(m)) != 0 || (6 - vsip_msumval_bl(m1))!= 0 ){ printf("error\n"); }else{ printf("correct\n"); } vsip_malldestroy_bl(m); vsip_malldestroy_bl(m1); vsip_malldestroy_d(pm); } return; } <file_sep>/* Created RJudd */ /********************************************************************** // TASP VSIPL Documentation and Code includes no warranty, / // express or implied, including the warranties of merchantability / // and fitness for a particular purpose. No person or organization / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vinterp_spline_f.c,v 2.1 2008/08/17 18:01:49 judd Exp $ */ /* Based on f77 algorithm in Cheney & Kincaid Numerical Mathematics (2ndEd) */ #include"vsip.h" #include"vsip_vviewattributes_f.h" #include"vsip_splineattributes_f.h" void vsip_vinterp_spline_f( const vsip_vview_f *t0, const vsip_vview_f *y0, vsip_spline_f *spl, const vsip_vview_f *xf0, const vsip_vview_f *yf0){ vsip_length N = t0->length; vsip_length M = xf0->length; vsip_stride t_st = t0->stride * t0->block->rstride, y_st = y0->stride * y0->block->rstride, xf_st = xf0->stride * xf0->block->rstride, yf_st = yf0->stride * yf0->block->rstride; vsip_index i; vsip_stride j; vsip_scalar_f *t = t0->block->array + t0->offset * t0->block->rstride; vsip_scalar_f *y = y0->block->array + y0->offset * y0->block->rstride; vsip_scalar_f *xf = xf0->block->array + xf0->offset * xf0->block->rstride; vsip_scalar_f *yf = yf0->block->array + yf0->offset * yf0->block->rstride; vsip_scalar_f *z = spl->z, *h=spl->h, *b = spl->b, *u = spl->u, *v = spl->v; { /* calculate constants */ for(i=0; i<N-1; i++){ h[i] = t[(i+1) * t_st] - t[i * t_st]; b[i] = (y[(i+1) * y_st] - y[i * y_st])/h[i]; } u[1] = 2.0 * (h[0] + h[1]); v[1] = 6.0 * (b[1] - b[0]); for(i=2; i<N-1; i++){ u[i] = 2.0 * (h[i] + h[i-1]) - h[i-1] * h[i-1] / u[i-1];\ v[i] = 6.0 * (b[i] - b[i-1]) - h[i-1] * v[i-1] / u[i-1];\ } z[N-1] = 0.0; for(i=N-2; i>0; i--) z[i] = (v[i] - h[i] * z[i+1])/u[i]; z[0] = 0.0; } for(i=0; i<M; i++){ vsip_scalar_f d,h,b,p,x; x = xf[i * xf_st]; j = N-2; while((x < (d = t[j * t_st])) && (j >= 0)){ j--; } { register vsip_scalar_f yj,zj,zj1; yj = y[j * y_st]; zj=z[j]; zj1=z[j+1]; d = x - d; if(j < 0) j = 0; if(d < 0) return; h = t[(j+1) * t_st] - t[j * t_st]; b = (y[(j+1) * y_st] - yj)/h - h * (zj1 + 2.0 * zj)/6.0; p = ((0.5 * zj +d * (zj1 - zj)/(6.0 * h)) * d + b) * d; yf[i * yf_st] = yj + p;; } } return; } <file_sep>/* Created RJudd August 11, 2002 */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_cvget_d.h,v 2.0 2003/02/22 15:18:31 judd Exp $ */ #ifndef VI_CVGET_D_H #define VI_CVGET_D_H 1 #include"vsip.h" #include"vsip_cblockattributes_d.h" #include"vsip_cvviewattributes_d.h" /* get and store a value in the internal block scalar storage */ #define VI_CVGETP_D(v, k) { vsip_offset o = (v)->block->cstride * ((v)->offset + (vsip_stride)(k) * (v)->stride); \ (v)->block->a_scalar.r = *((v)->block->R->array + o); \ (v)->block->a_scalar.i = *((v)->block->I->array + o);} /* retrieve the value stored in the internal block scalar storage */ #define VI_CVGET_D(v) ((v)->block->a_scalar) #endif /* VI_CVGET_D_H */ <file_sep>/* Created RJudd March 18, 2012 */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"vsip.h" #include"VI_mrowview_f.h" #include"VI_mcolview_f.h" #include"VI_cmrowview_f.h" #include"VI_cmcolview_f.h" static void vcmplx_f(const vsip_vview_f* a, const vsip_vview_f* b, const vsip_cvview_f* r) { vsip_length n = r->length; vsip_stride crst = r->block->cstride; vsip_scalar_f *ap = (vsip_scalar_f*) (a->block->array) + a->offset * a->block->rstride, *bp = (vsip_scalar_f*) (b->block->array) + b->offset * b->block->rstride, *rpr = (vsip_scalar_f*) ((r->block->R->array) + crst * r->offset), *rpi = (vsip_scalar_f*) ((r->block->I->array) + crst * r->offset); vsip_scalar_f temp; vsip_stride ast = a->stride * a->block->rstride, bst = b->stride * b->block->rstride, rst = crst * r->stride; while(n-- > 0){ temp = *ap; *rpi = *bp; *rpr = temp; ap += ast; bp += bst; rpr += rst; rpi += rst; } } void vsip_mcmplx_f(const vsip_mview_f* a, const vsip_mview_f* b, const vsip_cmview_f* r){ vsip_index i; vsip_vview_f av; vsip_vview_f bv; vsip_cvview_f rv; if(a->row_stride < a->col_stride){ for(i=0; i < a->col_length; i++){ VI_mrowview_f(a,i,&av); VI_mrowview_f(b,i,&bv);VI_cmrowview_f(r,i,&rv); vcmplx_f(&av,&bv,&rv); } } else { for(i=0; i < a->col_length; i++){ VI_mcolview_f(a,i,&av); VI_mcolview_f(b,i,&bv);VI_cmcolview_f(r,i,&rv); vcmplx_f(&av,&bv,&rv); } } } <file_sep>#include"ts.h" static void VU_rowview_f( vsip_vview_f *v, vsip_mview_f* m, vsip_index i) { vsip_mattr_f mattr; vsip_vattr_f vattr; vsip_mgetattrib_f(m,&mattr); vattr.offset = mattr.offset + i * mattr.col_stride; vattr.length = mattr.row_length; vattr.stride = mattr.row_stride; vsip_vputattrib_f(v,&vattr); return; } int ts_init( ts_obj* ts, param_obj *param) { int retval = 0; if(param){ vsip_scalar_f L = 2 * param->Fs/(param->Nsens * param->Dsens/param->c) + param->Nts + 1; vsip_vview_f *kernel = vsip_vcreate_kaiser_f(6,1,0); ts->Nsim_freqs=param->Nsim_freqs; ts->freqs = param->sim_freqs; ts->bearings = param->sim_bearings; ts->Nts = param->Nts; ts->Nsens = param->Nsens; ts->c = param->c; ts->Dsens = param->Dsens; ts->Nsim_noise=param->Nsim_noise; ts->Fs = param->Fs; if(kernel) ts->fir=vsip_fir_create_f(kernel,VSIP_NONSYM, 2*L,2,VSIP_STATE_SAVE,0,0); if(!ts->fir) retval++; ts->noise = vsip_vcreate_f(2*L,VSIP_MEM_NONE); if(!ts->noise) retval++; ts->bl_noise = vsip_vcreate_f(L,VSIP_MEM_NONE); if(!ts->bl_noise) retval++; ts->rand = vsip_randcreate(7,1,1,VSIP_PRNG); if(!ts->rand) retval++; ts->t = vsip_vcreate_f(param->Nts,VSIP_MEM_NONE); if(ts->t) vsip_vramp_f(0,1.0/param->Fs,ts->t); else retval++; ts->t_dt = vsip_vcreate_f(param->Nts,VSIP_MEM_NONE); if(!ts->t_dt) retval++; ts->m_data = vsip_mcreate_f(param->Nsens,param->Nts,VSIP_ROW,VSIP_MEM_NONE); if(ts->m_data) ts->v_data = vsip_mrowview_f(ts->m_data,0); else retval++; if(!ts->v_data) retval++; vsip_valldestroy_f(kernel); } else { printf("param object not valid\n"); retval++; } return retval; } void ts_fin(ts_obj* ts) { vsip_fir_destroy_f(ts->fir); vsip_valldestroy_f(ts->noise); vsip_valldestroy_f(ts->bl_noise); vsip_randdestroy(ts->rand); vsip_valldestroy_f(ts->t); vsip_valldestroy_f(ts->t_dt); vsip_vdestroy_f(ts->v_data); vsip_malldestroy_f(ts->m_data); return; } void ts_sim_nb(ts_obj *ts) { int i,j; vsip_mview_f *m_data = ts->m_data; vsip_vview_f *v_data = ts->v_data; vsip_vview_f *t = ts->t; vsip_vview_f *t_dt = ts->t_dt; vsip_scalar_f dt; vsip_scalar_f d_t = ts->Dsens/ts->c; for(i=0; i<ts->Nsim_freqs;i++){ float f=ts->freqs[i]; float b=d_t * (float)cos(ts->bearings[i]*M_PI/180); for(j=0; j<ts->Nsens; j++){ dt = (float)j * b; vsip_svadd_f(dt,t,t_dt); vsip_svmul_f(2 * M_PI * f,t_dt,t_dt); vsip_vcos_f(t_dt,t_dt); vsip_svmul_f(3,t_dt,t_dt); VU_rowview_f(v_data,m_data,j); vsip_vadd_f(t_dt,v_data,v_data); } /* next phone */ } /* next frequency/bearing */ return; } void ts_sim_noise( ts_obj *ts){ vsip_mview_f *m_data = ts->m_data; vsip_vview_f *v_data = ts->v_data; vsip_vview_f *noise = ts->noise; vsip_vview_f *bl_noise = ts->bl_noise; vsip_fir_f *fir = ts->fir; vsip_randstate *rand = ts->rand; vsip_scalar_f d_t = ts->Fs * (float)ts->Dsens / ts->c; vsip_offset o_0 = (vsip_offset) (d_t * ts->Nsens + 1); vsip_scalar_f a_stp = M_PI/(float)ts->Nsim_noise; vsip_vattr_f bl_attr; vsip_vgetattrib_f(bl_noise,&bl_attr); for(j=0; j<ts->Nsim_noise; j++){ vsip_scalar_f a_crct = cos((float)j * a_stp); vsip_vrandn_f(rand,noise); vsip_firflt_f(fir,noise,bl_noise); vsip_svmul_f(12.0/(float)ts->Nsim_noise,bl_noise,bl_noise); vsip_vputlength_f(bl_noise,ts->Nts); for(i=0; i<ts->Nsens; i++){ vsip_vputoffset_f(bl_noise, (vsip_index)(o_0 + i * d_t * a_crct)); VU_rowview_f(v_data,m_data,i); vsip_vadd_f(bl_noise,v_data,v_data); } vsip_vputattrib_f(bl_noise,&bl_attr); } vsip_smadd_f(-vsip_mmeanval_f(m_data),m_data,m_data); } void ts_zero(ts_obj *ts){ vsip_mfill_f(0,ts->m_data); } vsip_mview_f * ts_instance(ts_obj *ts){ return ts->m_data; } <file_sep>/* * vsip_vsortip_i.c * * Created by <NAME> on 10/26/07. * It uses private information and is compatible with the tvcpp * reference implementation of VSIPL; however the functions are not * yet approved for official inclusion into VSIPL * */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include "vsip_blockattributes_i.h" #include "vsip_vviewattributes_i.h" #include "vsip_blockattributes_vi.h" #include "vsip_vviewattributes_vi.h" #include "vsip.h" #define VRAMP(x) { \ vsip_scalar_vi k; \ vsip_scalar_vi *ind = x->block->array + x->offset; \ vsip_stride str = x->stride; \ for(k=0; k<x->length; k++){ \ *ind = k; \ ind += str;} \ } /* below adaption of K&R qsort; section 4.10 */ #define VGET(v,i) (*(v->block->array+(vsip_offset) (v->offset + (vsip_stride)i * v->stride))) #define SWAP(x,i,j) { /* x is float vector view; i,j are indices */ \ vsip_scalar_i tmp = VGET(x,i); \ VGET(x,i) = VGET(x,j); \ VGET(x,j) = tmp; \ } #define SWAP_VI(x,i,j) { /* x is vector view of type index; i,j are indices */ \ vsip_scalar_vi tmp = VGET(x,i); \ VGET(x,i) = VGET(x,j); \ VGET(x,j) = tmp; \ } static void VI_qsort_i(vsip_vview_i *v, vsip_index left, vsip_index right, vsip_vview_vi *vi){ vsip_index i,last; vsip_index iright; if(left >= right){ return; } else { iright = (vsip_index)(left+right)/2; } SWAP(v,left, iright); if(vi) SWAP_VI(vi,left,iright); last = left; for(i=left+1; i<= right; i++){ if(VGET(v,i) < VGET(v,left)){ last++; SWAP(v,last,i); if(vi) SWAP_VI(vi,last,i); } } SWAP(v,left,last); if(vi) SWAP_VI(vi,left,last); if(last > 0) VI_qsort_i(v,left,last-1,vi); VI_qsort_i(v,last+1,right,vi); return; } static void VI_qsortmag_i(vsip_vview_i *v, vsip_index left, vsip_index right, vsip_vview_vi *vi){ vsip_index i,last; vsip_index iright; if(left >= right){ return; } else { iright = (vsip_index)(left+right)/2; } SWAP(v,left, iright); if(vi) SWAP_VI(vi,left,iright); last = left; for(i=left+1; i<= right; i++){ if(abs(VGET(v,i)) < abs(VGET(v,left))){ last++; SWAP(v,last,i); if(vi) SWAP_VI(vi,last,i); } } SWAP(v,left,last); if(vi) SWAP_VI(vi,left,last); if(last > 0) VI_qsortmag_i(v,left,last-1,vi); VI_qsortmag_i(v,last+1,right,vi); return; } void vsip_vsortip_i(const vsip_vview_i *in_out, vsip_sort_mode mode, vsip_sort_dir dir, vsip_bool fill, const vsip_vview_vi *vi0){ vsip_vview_i in = *in_out; vsip_vview_vi viN,*vi; vi = &viN; if(vi0){ /* mirror sort an index */ viN = *vi0; if(fill) VRAMP(vi); } else { vi = (vsip_vview_vi*)0; } if(dir == VSIP_SORT_DESCENDING){ /* need to go through vector backwards */ in.offset += in.stride * (in.length-1); in.stride *= -1; if(vi0){ vi->offset += (vi->length - 1) * vi->stride; vi->stride *= -1; } } if(mode == VSIP_SORT_BYMAGNITUDE){ VI_qsortmag_i(&in,(vsip_index) 0,(vsip_index)(in.length-1),vi); } else { VI_qsort_i(&in,(vsip_index) 0,(vsip_index)(in.length-1),vi); } return; } <file_sep>/* Created RJudd September 5, 2006 */ /* VSIPL Consultant */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cmcopyfrom_user_d.c,v 2.1 2007/04/18 17:15:17 judd Exp $ */ #include"vsip.h" #include"vsip_cmviewattributes_d.h" void (vsip_cmcopyfrom_user_d)( vsip_scalar_d* const re, vsip_scalar_d* const im, vsip_major major, const vsip_cmview_d* a) { vsip_index i,j; vsip_length m = a->col_length; vsip_length n = a->row_length; vsip_stride ast_row = a->row_stride * a->block->cstride; vsip_stride ast_col = a->col_stride * a->block->cstride; vsip_scalar_d *ap_r = (a->block->R->array) + a->offset * a->block->cstride; vsip_scalar_d *ap_i = (a->block->I->array) + a->offset * a->block->cstride; vsip_scalar_d *aprow_r; vsip_scalar_d *apcol_r; vsip_scalar_d *aprow_i; vsip_scalar_d *apcol_i; if(im == NULL){ /* user storage must be interleaved */ if(major == VSIP_ROW){ vsip_scalar_d *rp = re; for(j=0; j<m; j++){ aprow_r = ap_r + ast_col * j; aprow_i = ap_i + ast_col * j; for(i=0; i<n; i++){ *aprow_r = *rp; rp++; aprow_r += ast_row; *aprow_i = *rp; aprow_i += ast_row; rp++; } } } else { /* must be column */ vsip_scalar_d *rp = re; for(i=0; i<n; i++){ apcol_r = ap_r + ast_row * i; apcol_i = ap_i + ast_row * i; for(j=0; j<m; j++){ *apcol_r = *rp; rp++; apcol_r += ast_col; *apcol_i = *rp; apcol_i += ast_col; rp++; } } } } else { /* user storage must be split */ if(major == VSIP_ROW){ vsip_scalar_d *rp = re; vsip_scalar_d *ip = im; for(j=0; j<m; j++){ aprow_r = ap_r + ast_col * j; aprow_i = ap_i + ast_col * j; for(i=0; i<n; i++){ *aprow_r = *rp; rp++; aprow_r += ast_row; *aprow_i = *ip; aprow_i += ast_row; ip++; } } } else { /* must be column */ vsip_scalar_d *rp = re; vsip_scalar_d *ip = im; for(i=0; i<n; i++){ apcol_r = ap_r + ast_row * i; apcol_i = ap_i + ast_row * i; for(j=0; j<m; j++){ *apcol_r = *rp; rp++; apcol_r += ast_col; *apcol_i = *ip; apcol_i += ast_col; ip++; } } } } return; } <file_sep>/* Created RJudd September 18, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_ctcreate_f.c,v 2.1 2004/09/21 02:07:24 judd Exp $ */ #define VI_CTVIEW_F_ #include"VI_support_cpriv_f.h" #include"VI_cblockcreate_f.h" #include"VI_cblockdestroy_f.h" vsip_ctview_f* vsip_ctcreate_f( vsip_length zlength, vsip_length ylength, vsip_length xlength, vsip_tmajor major, vsip_memory_hint hint) { vsip_cblock_f *block; vsip_ctview_f *ctview; block = VI_cblockcreate_f(zlength * ylength * xlength,hint); if(block == NULL) return (vsip_ctview_f*) NULL; ctview = VI_ctview_f(); if(ctview == NULL){ VI_cblockdestroy_f(block); return ctview; } ctview->block = block; ctview->offset = (vsip_offset)0; ctview->x_length = xlength; ctview->y_length = ylength; ctview->z_length = zlength; if(major == VSIP_TRAILING){ ctview->z_stride = xlength * ylength; ctview->y_stride = xlength; ctview->x_stride = 1; } else { /* VSIP_LEADING */ ctview->x_stride = zlength * ylength; ctview->y_stride = zlength; ctview->z_stride = 1; } ctview->markings = vsip_valid_structure_object; return ctview; } <file_sep>/* See Copyright in top level directory */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #ifndef _VSIP_H #define _VSIP_H #define JVSIP_VSIPL 1 #define JVSIP_VERSION_MAJOR 1.0 #define JVSIP_VERSION_MINOR 0.5 #include<stdio.h> #include<stdlib.h> #include<float.h> #include<math.h> #include<limits.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #define VSIP_PI M_PI #define VSIP_CMPLX_MEM VSIP_CMPLX_INTERLEAVED #define VSIP_MAX_SCALAR_BL INT_MAX #define VSIP_FALSE 0 #define VSIP_TRUE !VSIP_FALSE #define VSIP_MAX_SCALAR_VI ULONG_MAX #define VSIP_MAX_SCALAR_D DBL_MAX #define VSIP_MAX_SCALAR_F FLT_MAX #define VSIP_MAX_SCALAR_I INT_MAX #define VSIP_MAX_SCALAR_SI SHRT_MAX #define VSIP_MIN_SCALAR_D DBL_MIN #define VSIP_MIN_SCALAR_F FLT_MIN #define VSIP_MIN_SCALAR_I INT_MIN #define VSIP_MIN_SCALAR_SI SHRT_MIN #define vsip_acos_d acos #define vsip_acos_f (vsip_scalar_f)acos #define vsip_asin_d asin #define vsip_asin_f (vsip_scalar_f)asin #define vsip_atan2_d atan2 #define vsip_atan2_f (vsip_scalar_f)atan2 #define vsip_atan_d atan #define vsip_atan_f (vsip_scalar_f)atan #define vsip_ceil_d ceil #define vsip_ceil_f (vsip_scalar_f)ceil #define vsip_cos_d cos #define vsip_cos_f (vsip_scalar_f)cos #define vsip_cosh_d cosh #define vsip_cosh_f (vsip_scalar_f)cosh #define vsip_exp_d exp #define vsip_exp_f (vsip_scalar_f)exp #define vsip_floor_d floor #define vsip_floor_f (vsip_scalar_f)floor #define vsip_log10_d log10 #define vsip_log10_f (vsip_scalar_f)log10 #define vsip_log_d log #define vsip_log_f (vsip_scalar_f)log #define vsip_mag_d fabs #define vsip_mag_f (vsip_scalar_f)fabs #define vsip_pow_d pow #define vsip_pow_f (vsip_scalar_f)pow #define vsip_sin_d sin #define vsip_sin_f (vsip_scalar_f)sin #define vsip_sinh_d sinh #define vsip_sinh_f (vsip_scalar_f)sinh #define vsip_sqrt_d sqrt #define vsip_sqrt_f (vsip_scalar_f)sqrt #define vsip_tan_d tan #define vsip_tan_f (vsip_scalar_f)tan #define vsip_tanh_d tanh #define vsip_tanh_f (vsip_scalar_f)tanh #define vsip_exp10_d(x) (pow(10,x)) #define vsip_fmod_d(x,y) ((vsip_scalar_d)(x - ((long)(x/y))*y)) #define vsip_hypot_d(x,y)((vsip_scalar_d)(sqrt(x * x + y * y))) #define vsip_rsqrt_d(x) ((vsip_scalar_d)(1.0/sqrt(x))) #define vsip_recip_d(x) ((vsip_scalar_d)(1.0/(x))) #define vsip_min_d(x,y) ((vsip_scalar_d)((x < y) ? x : y)) #define vsip_max_d(x,y) ((vsip_scalar_d)((x < y) ? y : x)) #define vsip_exp10_f(x) ((vsip_scalar_f)(pow(10,x))) #define vsip_fmod_f(x,y)((vsip_scalar_f)(x - ((int)(x/y))*y)) #define vsip_hypot_f(x,y)((vsip_scalar_f)(sqrt(x * x + y * y))) #define vsip_rsqrt_f(x) ((vsip_scalar_f)(1.0/sqrt(x))) #define vsip_recip_f(x) ((vsip_scalar_f)(1.0/(x))) #define vsip_min_f(x,y) ((vsip_scalar_f)((x < y) ? x : y)) #define vsip_max_f(x,y) ((vsip_scalar_f)((x < y) ? y : x)) #define vsip_rowindex(x) ((x).r) #define vsip_colindex(x) ((x).c) #define vsip_real_d(x) ((x).r) #define vsip_imag_d(x) ((x).i) #define vsip_CJMUL_f(x,y, z) ((*(z)).r = (x).r * (y).r + (x).i * (y).i); ((*(z)).i = -(x).r * (y).i + (x).i * (y).r) #define vsip_CJMUL_d(x,y, z) ((*(z)).r = (x).r * (y).r + (x).i * (y).i); ((*(z)).i = -(x).r * (y).i + (x).i * (y).r) #define vsip_CONJ_f(x, y) ((*(y)).r = (x).r); ((*(y)).i = -(x).i) #define vsip_CONJ_d(x, y) ((*(y)).r = (x).r); ((*(y)).i = -(x).i) #define vsip_CRSUB_f(x,y,z) ((*(z)).r = (x).r - (y)); ((*(z)).i = (x).i) #define vsip_CRSUB_d(x,y,z) ((*(z)).r = (x).r - (y)); ((*(z)).i = (x).i) #define vsip_RCSUB_f(x,y,z) ((*(z)).r = -(y).r + (x)); ((*(z)).i = -(y).i) #define vsip_RCSUB_d(x,y,z) ((*(z)).r = -(y).r + (x)); ((*(z)).i = -(y).i) #define vsip_RCADD_f(x,y,z) ((*(z)).r = (y).r + (x)); ((*(z)).i = (y).i) #define vsip_RCADD_d(x,y,z) ((*(z)).r = (y).r + (x)); ((*(z)).i = (y).i) #define vsip_CMPLX_f(x,y, z) ((*(z)).r = (x)); ((*(z)).i = (y)) #define vsip_CMPLX_d(x,y, z) ((*(z)).r = (x)); ((*(z)).i = (y)) #define vsip_CNEG_f(x, y) ((*(y)).r = -(x).r); ((*(y)).i = -(x).i) #define vsip_CNEG_d(x, y) ((*(y)).r = -(x).r); ((*(y)).i = -(x).i) #define vsip_CMUL_f(x,y, z) ((*(z)).r = (x).r * (y).r - (x).i * (y).i); ((*(z)).i = (x).r * (y).i + (x).i * (y).r) #define vsip_CMUL_d(x,y, z) ((*(z)).r = (x).r * (y).r - (x).i * (y).i); ((*(z)).i = (x).r * (y).i + (x).i * (y).r) #define vsip_RCMUL_f(x,y,z) ((*(z)).r = (x) * (y).r); ((*(z)).i = (x) * (y).i) #define vsip_RCMUL_d(x,y,z) ((*(z)).r = (x) * (y).r); ((*(z)).i = (x) * (y).i) #define vsip_CRDIV_f(x,y,z) ((*(z)).r = (x).r / (y)); ((*(z)).i = (x).i / (y)) #define vsip_CRDIV_d(x,y,z) ((*(z)).r = (x).r / (y)); ((*(z)).i = (x).i / (y)) #define vsip_CADD_f(x,y,z) ((*(z)).r = (x).r + (y).r); ((*(z)).i = (x).i + (y).i) #define vsip_CADD_d(x,y,z) ((*(z)).r = (x).r + (y).r); ((*(z)).i = (x).i + (y).i) #define vsip_CSUB_f(x,y,z) ((*(z)).r = (x).r - (y).r); ((*(z)).i = (x).i - (y).i) #define vsip_CSUB_d(x,y,z) ((*(z)).r = (x).r - (y).r); ((*(z)).i = (x).i - (y).i) #define vsip_real_f(x) ((x).r) #define vsip_imag_f(x) ((x).i) typedef unsigned char vsip_scalar_uc; typedef signed int vsip_scalar_i; typedef signed long int vsip_scalar_li ; typedef signed short int vsip_scalar_si; typedef unsigned int vsip_scalar_ue32; typedef signed int vsip_scalar_bl; typedef vsip_scalar_bl vsip_bool; typedef float vsip_scalar_f; typedef double vsip_scalar_d; typedef unsigned long int vsip_scalar_vi; typedef vsip_scalar_vi vsip_offset; typedef vsip_scalar_vi vsip_length; typedef vsip_scalar_vi vsip_index; typedef signed long int vsip_stride; typedef struct { vsip_scalar_vi r,c; } vsip_scalar_mi; typedef struct { vsip_scalar_d r, i; } vsip_cscalar_d; typedef struct { vsip_scalar_f r, i; } vsip_cscalar_f; typedef enum { VSIP_SORT_ASCENDING = 0, VSIP_SORT_DESCENDING = 1 } vsip_sort_dir; typedef enum { VSIP_SORT_BYVALUE = 0, VSIP_SORT_BYMAGNITUDE = 1 } vsip_sort_mode; typedef enum { VSIP_MEM_NONE = 0, VSIP_MEM_RDONLY = 1, VSIP_MEM_CONST = 2, VSIP_MEM_SHARED = 3, VSIP_MEM_SHARED_RDONLY = 4, VSIP_MEM_SHARED_CONST = 5 } vsip_memory_hint; typedef enum { VSIP_CMPLX_INTERLEAVED, VSIP_CMPLX_SPLIT, VSIP_CMPLX_NONE } vsip_cmplx_mem; typedef enum { VSIP_TVX = 0, VSIP_TVY = 1, VSIP_TVZ = 2 }vsip_tvslice; typedef enum { VSIP_TMYX = 0, VSIP_TMZX = 1, VSIP_TMZY = 2 } vsip_tmslice; typedef enum { VSIP_TTRANS_NOP = 0, VSIP_TTRANS_YX = 1, VSIP_TTRANS_ZY = 2, VSIP_TTRANS_ZX = 3, VSIP_TTRANS_YXZY = 4, VSIP_TTRANS_YXZX = 5 }vsip_ttrans; typedef enum { VSIP_ROW = 0, VSIP_COL = 1 } vsip_major; typedef enum { VSIP_TRAILING = 0, VSIP_LEADING = 1 } vsip_tmajor; typedef enum { VSIP_MAT_NTRANS = 0, VSIP_MAT_TRANS = 1, VSIP_MAT_HERM = 2, VSIP_MAT_CONJ = 3 } vsip_mat_op; typedef enum { VSIP_COV = 0, VSIP_LLS =1 } vsip_qrd_prob; typedef enum { VSIP_MAT_LSIDE = 0, VSIP_MAT_RSIDE =1 } vsip_mat_side; typedef enum { VSIP_QRD_NOSAVEQ = 0, VSIP_QRD_SAVEQ = 1, VSIP_QRD_SAVEQ1 = 2 } vsip_qrd_qopt; typedef enum { VSIP_TR_LOW = 0, VSIP_TR_UPP = 1 } vsip_mat_uplo; typedef enum { VSIP_SVD_UVNOS = 0, VSIP_SVD_UVFULL = 1, VSIP_SVD_UVPART = 2 } vsip_svd_uv; typedef enum { VSIP_FFT_FWD = -1, VSIP_FFT_INV = +1 } vsip_fft_dir; typedef enum { VSIP_FFT_IP = 0, VSIP_FFT_OP = 1 } vsip_fft_place; typedef enum { VSIP_ALG_SPACE = 0, VSIP_ALG_TIME = 1, VSIP_ALG_NOISE = 2 } vsip_alg_hint; typedef enum { VSIP_NONSYM = 0, VSIP_SYM_EVEN_LEN_ODD = 1, VSIP_SYM_EVEN_LEN_EVEN = 2 } vsip_symmetry; typedef enum { VSIP_SUPPORT_FULL = 0, VSIP_SUPPORT_SAME = 1, VSIP_SUPPORT_MIN = 2 } vsip_support_region; typedef enum { VSIP_BIASED = 0, VSIP_UNBIASED = 1 } vsip_bias; typedef enum { VSIP_STATE_NO_SAVE = 1, VSIP_STATE_SAVE = 2 } vsip_obj_state; typedef enum { VSIP_HIST_RESET = 1, VSIP_HIST_ACCUM = 2 } vsip_hist_opt; typedef enum { VSIP_PRNG = 0, VSIP_NPRNG = 1 } vsip_rng; typedef struct vsip_blockattributes_vi vsip_block_vi; typedef struct vsip_blockattributes_mi vsip_block_mi; typedef struct vsip_blockattributes_bl vsip_block_bl; typedef struct vsip_blockattributes_d vsip_block_d; typedef struct vsip_cblockattributes_d vsip_cblock_d; typedef struct vsip_blockattributes_f vsip_block_f; typedef struct vsip_cblockattributes_f vsip_cblock_f; typedef struct vsip_blockattributes_i vsip_block_i; typedef struct vsip_blockattributes_li vsip_block_li; typedef struct vsip_blockattributes_si vsip_block_si; typedef struct vsip_blockattributes_uc vsip_block_uc; typedef struct vsip_vviewattributes_bl vsip_vview_bl; typedef struct vsip_vviewattributes_vi vsip_vview_vi; typedef struct vsip_vviewattributes_mi vsip_vview_mi; typedef struct vsip_vviewattributes_d vsip_vview_d; typedef struct vsip_vviewattributes_f vsip_vview_f; typedef struct vsip_vviewattributes_i vsip_vview_i; typedef struct vsip_vviewattributes_li vsip_vview_li; typedef struct vsip_vviewattributes_si vsip_vview_si; typedef struct vsip_vviewattributes_uc vsip_vview_uc; typedef struct vsip_mviewattributes_d vsip_mview_d; typedef struct vsip_mviewattributes_f vsip_mview_f; typedef struct vsip_mviewattributes_bl vsip_mview_bl; typedef struct vsip_mviewattributes_i vsip_mview_i; typedef struct vsip_mviewattributes_li vsip_mview_li; typedef struct vsip_mviewattributes_si vsip_mview_si; typedef struct vsip_mviewattributes_uc vsip_mview_uc; typedef struct vsip_cvviewattributes_d vsip_cvview_d; typedef struct vsip_cvviewattributes_f vsip_cvview_f; typedef struct vsip_cmviewattributes_d vsip_cmview_d; typedef struct vsip_cmviewattributes_f vsip_cmview_f; typedef struct vsip_randobject vsip_randstate; typedef struct vsip_ludattributes_d vsip_lu_d; typedef struct vsip_ludattributes_f vsip_lu_f; typedef struct vsip_cludattributes_d vsip_clu_d; typedef struct vsip_cludattributes_f vsip_clu_f; typedef struct vsip_permuteattributes vsip_permute; typedef struct vsip_choldattributes_d vsip_chol_d; typedef struct vsip_choldattributes_f vsip_chol_f; typedef struct vsip_ccholdattributes_d vsip_cchol_d; typedef struct vsip_ccholdattributes_f vsip_cchol_f; typedef struct vsip_qrdattributes_d vsip_qr_d; typedef struct vsip_qrdattributes_f vsip_qr_f; typedef struct vsip_cqrdattributes_d vsip_cqr_d; typedef struct vsip_cqrdattributes_f vsip_cqr_f; typedef struct vsip_fftattributes_d vsip_fft_d; typedef struct vsip_fftattributes_f vsip_fft_f; typedef struct vsip_fftmattributes_f vsip_fftm_f; typedef struct vsip_fftmattributes_d vsip_fftm_d; typedef struct vsip_firattributes_f vsip_fir_f; typedef struct vsip_firattributes_d vsip_fir_d; typedef struct vsip_cfirattributes_f vsip_cfir_f; typedef struct vsip_cfirattributes_d vsip_cfir_d; typedef struct vsip_rcfirattributes_f vsip_rcfir_f; typedef struct vsip_rcfirattributes_d vsip_rcfir_d; typedef struct vsip_corr1dattributes_f vsip_corr1d_f; typedef struct vsip_ccorr1dattributes_f vsip_ccorr1d_f; typedef struct vsip_corr1dattributes_d vsip_corr1d_d; typedef struct vsip_ccorr1dattributes_d vsip_ccorr1d_d; typedef struct vsip_conv1dattributes_f vsip_conv1d_f; typedef struct vsip_conv1dattributes_d vsip_conv1d_d; typedef struct vsip_tviewattributes_f vsip_tview_f; typedef struct vsip_tviewattributes_d vsip_tview_d; typedef struct vsip_tviewattributes_i vsip_tview_i; typedef struct vsip_tviewattributes_li vsip_tview_li; typedef struct vsip_tviewattributes_si vsip_tview_si; typedef struct vsip_tviewattributes_uc vsip_tview_uc; typedef struct vsip_ctviewattributes_f vsip_ctview_f; typedef struct vsip_ctviewattributes_d vsip_ctview_d; typedef struct vsip_splineattributes_f vsip_spline_f; typedef struct vsip_splineattributes_d vsip_spline_d; typedef struct { vsip_offset offset; vsip_stride stride; vsip_length length; vsip_block_d* block; } vsip_vattr_d; typedef struct { vsip_offset offset; vsip_stride stride; vsip_length length; vsip_block_f* block; } vsip_vattr_f; typedef struct { vsip_offset offset; vsip_stride stride; vsip_length length; vsip_cblock_d* block; } vsip_cvattr_d; typedef struct { vsip_offset offset; vsip_stride stride; vsip_length length; vsip_cblock_f* block; } vsip_cvattr_f; typedef struct { vsip_offset offset; vsip_stride stride; vsip_length length; vsip_block_vi* block; } vsip_vattr_vi; typedef struct { vsip_offset offset; vsip_stride stride; vsip_length length; vsip_block_mi* block; } vsip_vattr_mi; typedef struct { vsip_offset offset; vsip_stride stride; vsip_length length; vsip_block_bl* block; } vsip_vattr_bl; typedef struct { vsip_offset offset; vsip_stride stride; vsip_length length; vsip_block_i* block; } vsip_vattr_i; typedef struct { vsip_offset offset; vsip_stride stride; vsip_length length; vsip_block_li* block; } vsip_vattr_li; typedef struct { vsip_offset offset; vsip_stride stride; vsip_length length; vsip_block_si* block; } vsip_vattr_si; typedef struct { vsip_offset offset; vsip_stride stride; vsip_length length; vsip_block_uc* block; } vsip_vattr_uc; typedef struct { vsip_offset offset; vsip_stride row_stride; vsip_length row_length; vsip_stride col_stride; vsip_length col_length; vsip_block_d* block; } vsip_mattr_d; typedef struct { vsip_offset offset; vsip_stride row_stride; vsip_length row_length; vsip_stride col_stride; vsip_length col_length; vsip_block_f* block; } vsip_mattr_f; typedef struct { vsip_offset offset; vsip_stride row_stride; vsip_length row_length; vsip_stride col_stride; vsip_length col_length; vsip_cblock_d* block; } vsip_cmattr_d; typedef struct { vsip_offset offset; vsip_stride row_stride; vsip_length row_length; vsip_stride col_stride; vsip_length col_length; vsip_cblock_f* block; } vsip_cmattr_f; typedef struct { vsip_offset offset; vsip_stride row_stride; vsip_length row_length; vsip_stride col_stride; vsip_length col_length; vsip_block_bl* block; } vsip_mattr_bl; typedef struct { vsip_offset offset; vsip_stride row_stride; vsip_length row_length; vsip_stride col_stride; vsip_length col_length; vsip_block_i* block; } vsip_mattr_i; typedef struct { vsip_offset offset; vsip_stride row_stride; vsip_length row_length; vsip_stride col_stride; vsip_length col_length; vsip_block_li* block; } vsip_mattr_li; typedef struct { vsip_offset offset; vsip_stride row_stride; vsip_length row_length; vsip_stride col_stride; vsip_length col_length; vsip_block_si* block; } vsip_mattr_si; typedef struct { vsip_offset offset; vsip_stride row_stride; vsip_length row_length; vsip_stride col_stride; vsip_length col_length; vsip_block_uc* block; } vsip_mattr_uc; typedef struct { vsip_offset offset; vsip_length z_length; vsip_stride z_stride; vsip_length y_length; vsip_stride y_stride; vsip_length x_length; vsip_stride x_stride; vsip_block_f *block; } vsip_tattr_f; typedef struct { vsip_offset offset; vsip_length z_length; vsip_stride z_stride; vsip_length y_length; vsip_stride y_stride; vsip_length x_length; vsip_stride x_stride; vsip_block_d *block; } vsip_tattr_d; typedef struct { vsip_offset offset; vsip_length z_length; vsip_stride z_stride; vsip_length y_length; vsip_stride y_stride; vsip_length x_length; vsip_stride x_stride; vsip_block_i *block; } vsip_tattr_i; typedef struct { vsip_offset offset; vsip_length z_length; vsip_stride z_stride; vsip_length y_length; vsip_stride y_stride; vsip_length x_length; vsip_stride x_stride; vsip_block_li *block; } vsip_tattr_li; typedef struct { vsip_offset offset; vsip_length z_length; vsip_stride z_stride; vsip_length y_length; vsip_stride y_stride; vsip_length x_length; vsip_stride x_stride; vsip_block_si *block; } vsip_tattr_si; typedef struct { vsip_offset offset; vsip_length z_length; vsip_stride z_stride; vsip_length y_length; vsip_stride y_stride; vsip_length x_length; vsip_stride x_stride; vsip_block_uc *block; } vsip_tattr_uc; typedef struct { vsip_offset offset; vsip_length z_length; vsip_stride z_stride; vsip_length y_length; vsip_stride y_stride; vsip_length x_length; vsip_stride x_stride; vsip_cblock_f *block; } vsip_ctattr_f; typedef struct { vsip_offset offset; vsip_length z_length; vsip_stride z_stride; vsip_length y_length; vsip_stride y_stride; vsip_length x_length; vsip_stride x_stride; vsip_cblock_d *block; } vsip_ctattr_d; typedef struct { vsip_length n; } vsip_lu_attr_d; typedef struct { vsip_length n; } vsip_clu_attr_d; typedef struct { vsip_length n; } vsip_lu_attr_f; typedef struct { vsip_length n; } vsip_clu_attr_f; typedef struct { vsip_mat_uplo uplo; vsip_length n; } vsip_chol_attr_d; typedef struct { vsip_mat_uplo uplo; vsip_length n; } vsip_chol_attr_f; typedef struct { vsip_mat_uplo uplo; vsip_length n; } vsip_cchol_attr_d; typedef struct { vsip_mat_uplo uplo; vsip_length n; } vsip_cchol_attr_f; typedef struct { vsip_length m; vsip_length n; vsip_qrd_qopt Qopt; } vsip_qr_attr_f; typedef struct { vsip_length m; vsip_length n; vsip_qrd_qopt Qopt; } vsip_qr_attr_d; typedef struct { vsip_length m; vsip_length n; vsip_qrd_qopt Qopt; } vsip_cqr_attr_f; typedef struct { vsip_length m; vsip_length n; vsip_qrd_qopt Qopt; } vsip_cqr_attr_d; typedef struct { vsip_length m; vsip_length n; vsip_svd_uv Usave; vsip_svd_uv Vsave; } vsip_sv_attr_f; typedef struct { vsip_length m; vsip_length n; vsip_svd_uv Usave; vsip_svd_uv Vsave; } vsip_csv_attr_f; typedef struct { vsip_length m; vsip_length n; vsip_svd_uv Usave; vsip_svd_uv Vsave; } vsip_sv_attr_d; typedef struct { vsip_length m; vsip_length n; vsip_svd_uv Usave; vsip_svd_uv Vsave; } vsip_csv_attr_d; typedef struct { vsip_scalar_vi input; vsip_scalar_vi output; vsip_fft_place place; vsip_scalar_d scale; vsip_fft_dir dir; } vsip_fft_attr_d; typedef struct { vsip_scalar_vi input; vsip_scalar_vi output; vsip_fft_place place; vsip_scalar_f scale; vsip_fft_dir dir; } vsip_fft_attr_f; typedef struct { vsip_scalar_mi input; vsip_scalar_mi output; vsip_fft_place place; vsip_scalar_d scale; vsip_fft_dir dir; vsip_major major; } vsip_fftm_attr_d; typedef struct { vsip_scalar_mi input; vsip_scalar_mi output; vsip_fft_place place; vsip_scalar_f scale; vsip_fft_dir dir; vsip_major major; } vsip_fftm_attr_f; typedef struct { vsip_scalar_vi kernel_len; vsip_symmetry symm; vsip_scalar_vi in_len; vsip_scalar_vi out_len; vsip_length decimation; vsip_obj_state state; } vsip_fir_attr; typedef struct { vsip_scalar_vi kernel_len; vsip_symmetry symm; vsip_scalar_vi in_len; vsip_scalar_vi out_len; vsip_length decimation; vsip_obj_state state; } vsip_cfir_attr; typedef struct { vsip_scalar_vi kernel_len; vsip_symmetry symm; vsip_scalar_vi in_len; vsip_scalar_vi out_len; vsip_length decimation; vsip_obj_state state; } vsip_rcfir_attr; typedef struct { vsip_scalar_vi ref_len; vsip_scalar_vi data_len; vsip_support_region support; vsip_scalar_vi lag_len; } vsip_corr1d_attr; typedef struct { vsip_scalar_vi kernel_len; vsip_symmetry symm; vsip_scalar_vi data_len; vsip_support_region support; vsip_scalar_vi out_len; int decimation; } vsip_conv1d_attr; vsip_block_bl* vsip_blockbind_bl ( vsip_scalar_bl * const, vsip_length, vsip_memory_hint ) ; vsip_block_bl* vsip_blockcreate_bl ( vsip_length, vsip_memory_hint ) ; vsip_block_bl* vsip_mdestroy_bl ( vsip_mview_bl* ) ; vsip_block_bl* vsip_mgetblock_bl ( const vsip_mview_bl* ) ; vsip_block_bl* vsip_vdestroy_bl ( vsip_vview_bl* ) ; vsip_block_bl* vsip_vgetblock_bl ( const vsip_vview_bl* ) ; vsip_block_d* vsip_tdestroy_d ( vsip_tview_d* ) ; vsip_block_d* vsip_tgetblock_d ( const vsip_tview_d* ) ; vsip_block_d* vsip_blockbind_d ( vsip_scalar_d * const, vsip_length, vsip_memory_hint ) ; vsip_block_d* vsip_blockcreate_d ( vsip_length, vsip_memory_hint ) ; vsip_block_d* vsip_mdestroy_d ( vsip_mview_d* ) ; vsip_block_d* vsip_mgetblock_d ( const vsip_mview_d* ) ; vsip_block_d* vsip_vdestroy_d ( vsip_vview_d* ) ; vsip_block_d* vsip_vgetblock_d ( const vsip_vview_d* ) ; vsip_block_f* vsip_tdestroy_f ( vsip_tview_f* ) ; vsip_block_f* vsip_tgetblock_f ( const vsip_tview_f* ) ; vsip_block_f* vsip_blockbind_f ( vsip_scalar_f * const, vsip_length, vsip_memory_hint ) ; vsip_block_f* vsip_blockcreate_f ( vsip_length, vsip_memory_hint ) ; vsip_block_f* vsip_mdestroy_f ( vsip_mview_f* ) ; vsip_block_f* vsip_mgetblock_f ( const vsip_mview_f* ) ; vsip_block_f* vsip_vdestroy_f ( vsip_vview_f* ) ; vsip_block_f* vsip_vgetblock_f ( const vsip_vview_f* ) ; vsip_block_i* vsip_tdestroy_i ( vsip_tview_i* ) ; vsip_block_i* vsip_tgetblock_i ( const vsip_tview_i* ) ; vsip_block_i* vsip_blockbind_i ( vsip_scalar_i * const, vsip_length, vsip_memory_hint ) ; vsip_block_i* vsip_blockcreate_i ( vsip_length, vsip_memory_hint ) ; vsip_block_i* vsip_mdestroy_i ( vsip_mview_i* ) ; vsip_block_i* vsip_mgetblock_i ( const vsip_mview_i* ) ; vsip_block_i* vsip_vdestroy_i ( vsip_vview_i* ) ; vsip_block_i* vsip_vgetblock_i ( const vsip_vview_i* ) ; vsip_block_li* vsip_tdestroy_li ( vsip_tview_li* ) ; vsip_block_li* vsip_tgetblock_li ( const vsip_tview_li* ) ; vsip_block_li* vsip_blockbind_li ( vsip_scalar_li* const, vsip_length, vsip_memory_hint ) ; vsip_block_li* vsip_blockcreate_li ( vsip_length, vsip_memory_hint ) ; vsip_block_li* vsip_mdestroy_li ( vsip_mview_li* ) ; vsip_block_li* vsip_mgetblock_li ( const vsip_mview_li* ) ; vsip_block_li* vsip_vdestroy_li ( vsip_vview_li* ) ; vsip_block_li* vsip_vgetblock_li ( const vsip_vview_li* ) ; vsip_block_mi* vsip_blockbind_mi ( vsip_scalar_vi * const, vsip_length, vsip_memory_hint ) ; vsip_block_mi* vsip_blockcreate_mi ( vsip_length, vsip_memory_hint ) ; vsip_block_mi* vsip_vdestroy_mi ( vsip_vview_mi* ) ; vsip_block_mi* vsip_vgetblock_mi ( const vsip_vview_mi* ) ; vsip_block_si* vsip_tdestroy_si ( vsip_tview_si* ) ; vsip_block_si* vsip_tgetblock_si ( const vsip_tview_si* ) ; vsip_block_si* vsip_blockbind_si ( vsip_scalar_si * const, vsip_length, vsip_memory_hint ) ; vsip_block_si* vsip_blockcreate_si ( vsip_length, vsip_memory_hint ) ; vsip_block_si* vsip_mdestroy_si ( vsip_mview_si* ) ; vsip_block_si* vsip_mgetblock_si ( const vsip_mview_si* ) ; vsip_block_si* vsip_vdestroy_si ( vsip_vview_si* ) ; vsip_block_si* vsip_vgetblock_si ( const vsip_vview_si* ) ; vsip_block_uc* vsip_tdestroy_uc ( vsip_tview_uc* ) ; vsip_block_uc* vsip_tgetblock_uc ( const vsip_tview_uc* ) ; vsip_block_uc* vsip_blockbind_uc ( vsip_scalar_uc * const, vsip_length, vsip_memory_hint ) ; vsip_block_uc* vsip_blockcreate_uc ( vsip_length, vsip_memory_hint ) ; vsip_block_uc* vsip_mdestroy_uc ( vsip_mview_uc* ) ; vsip_block_uc* vsip_mgetblock_uc ( const vsip_mview_uc* ) ; vsip_block_uc* vsip_vdestroy_uc ( vsip_vview_uc* ) ; vsip_block_uc* vsip_vgetblock_uc ( const vsip_vview_uc* ) ; vsip_block_vi* vsip_blockbind_vi ( vsip_scalar_vi * const, vsip_length, vsip_memory_hint ) ; vsip_block_vi* vsip_blockcreate_vi ( vsip_length, vsip_memory_hint ) ; vsip_block_vi* vsip_vdestroy_vi ( vsip_vview_vi* ) ; vsip_block_vi* vsip_vgetblock_vi ( const vsip_vview_vi* ) ; vsip_cblock_d* vsip_ctdestroy_d ( vsip_ctview_d* ) ; vsip_cblock_d* vsip_ctgetblock_d ( const vsip_ctview_d* ) ; vsip_cblock_d* vsip_cblockbind_d ( vsip_scalar_d* const, vsip_scalar_d* const, vsip_length, vsip_memory_hint ) ; vsip_cblock_d* vsip_cblockcreate_d ( vsip_length, vsip_memory_hint ) ; vsip_cblock_d* vsip_cmdestroy_d ( vsip_cmview_d* ) ; vsip_cblock_d* vsip_cmgetblock_d ( const vsip_cmview_d* ) ; vsip_cblock_d* vsip_cvdestroy_d ( vsip_cvview_d* ) ; vsip_cblock_d* vsip_cvgetblock_d ( const vsip_cvview_d* ) ; vsip_cblock_f* vsip_ctdestroy_f ( vsip_ctview_f* ) ; vsip_cblock_f* vsip_ctgetblock_f ( const vsip_ctview_f* ) ; vsip_cblock_f* vsip_cblockbind_f ( vsip_scalar_f* const, vsip_scalar_f* const, vsip_length, vsip_memory_hint ) ; vsip_cblock_f* vsip_cblockcreate_f ( vsip_length, vsip_memory_hint ) ; vsip_cblock_f* vsip_cmdestroy_f ( vsip_cmview_f* ) ; vsip_cblock_f* vsip_cmgetblock_f ( const vsip_cmview_f* ) ; vsip_cblock_f* vsip_cvdestroy_f ( vsip_cvview_f* ) ; vsip_cblock_f* vsip_cvgetblock_f ( const vsip_cvview_f* ) ; int vsip_blockadmit_bl ( vsip_block_bl*, vsip_scalar_bl ) ; int vsip_blockadmit_d ( vsip_block_d*, vsip_scalar_bl ) ; int vsip_blockadmit_f ( vsip_block_f*, vsip_scalar_bl ) ; int vsip_blockadmit_i ( vsip_block_i*, vsip_scalar_bl ) ; int vsip_blockadmit_li ( vsip_block_li*, vsip_scalar_bl ) ; int vsip_blockadmit_mi ( vsip_block_mi*, vsip_scalar_bl ) ; int vsip_blockadmit_si ( vsip_block_si*, vsip_scalar_bl ) ; int vsip_blockadmit_uc ( vsip_block_uc*, vsip_scalar_bl ) ; int vsip_blockadmit_vi ( vsip_block_vi*, vsip_scalar_bl ) ; int vsip_cblockadmit_d ( vsip_cblock_d*, vsip_scalar_bl ) ; int vsip_cblockadmit_f ( vsip_cblock_f*, vsip_scalar_bl ) ; int vsip_cchold_d ( vsip_cchol_d*, const vsip_cmview_d* ) ; int vsip_cchold_destroy_d ( vsip_cchol_d* ) ; int vsip_cchold_destroy_f ( vsip_cchol_f* ) ; int vsip_cchold_f ( vsip_cchol_f*, const vsip_cmview_f* ) ; int vsip_ccholsol_d ( const vsip_cchol_d*, const vsip_cmview_d* ) ; int vsip_ccholsol_f ( const vsip_cchol_f*, const vsip_cmview_f* ) ; int vsip_ccorr1d_destroy_d ( vsip_ccorr1d_d* ) ; int vsip_ccorr1d_destroy_f ( vsip_ccorr1d_f *cor ) ; int vsip_ccovsol_d ( const vsip_cmview_d*, const vsip_cmview_d* ) ; int vsip_ccovsol_f ( const vsip_cmview_f*, const vsip_cmview_f* ) ; int vsip_rcfir_destroy_d ( vsip_rcfir_d* ) ; int vsip_rcfir_destroy_f ( vsip_rcfir_f* ) ; int vsip_cfir_destroy_d ( vsip_cfir_d* ) ; int vsip_cfir_destroy_f ( vsip_cfir_f* ) ; int vsip_rcfirflt_d ( vsip_rcfir_d*, const vsip_cvview_d*, const vsip_cvview_d* ) ; int vsip_rcfirflt_f ( vsip_rcfir_f*, const vsip_cvview_f*, const vsip_cvview_f* ) ; int vsip_cfirflt_d ( vsip_cfir_d*, const vsip_cvview_d*, const vsip_cvview_d* ) ; int vsip_cfirflt_f ( vsip_cfir_f*, const vsip_cvview_f*, const vsip_cvview_f* ) ; int vsip_chold_d ( vsip_chol_d*, const vsip_mview_d* ) ; int vsip_chold_destroy_d ( vsip_chol_d* ) ; int vsip_chold_destroy_f ( vsip_chol_f* ) ; int vsip_chold_f ( vsip_chol_f*, const vsip_mview_f* ) ; int vsip_cholsol_d ( const vsip_chol_d*, const vsip_mview_d* ) ; int vsip_cholsol_f ( const vsip_chol_f*, const vsip_mview_f* ) ; int vsip_cllsqsol_d ( const vsip_cmview_d*, const vsip_cmview_d* ) ; int vsip_cllsqsol_f ( const vsip_cmview_f*, const vsip_cmview_f* ) ; int vsip_clud_d ( vsip_clu_d*, const vsip_cmview_d* ) ; int vsip_clud_destroy_d ( vsip_clu_d* ) ; int vsip_clud_destroy_f ( vsip_clu_f* ) ; int vsip_clud_f ( vsip_clu_f*, const vsip_cmview_f* ) ; int vsip_clusol_d ( const vsip_clu_d*, vsip_mat_op, const vsip_cmview_d* ) ; int vsip_clusol_f ( const vsip_clu_f*, vsip_mat_op, const vsip_cmview_f* ) ; int vsip_conv1d_destroy_d ( vsip_conv1d_d* ) ; int vsip_conv1d_destroy_f ( vsip_conv1d_f* ) ; int vsip_corr1d_destroy_d ( vsip_corr1d_d* ) ; int vsip_corr1d_destroy_f ( vsip_corr1d_f* ) ; int vsip_covsol_d ( const vsip_mview_d*, const vsip_mview_d* ) ; int vsip_covsol_f ( const vsip_mview_f*, const vsip_mview_f* ) ; int vsip_cqrd_d ( vsip_cqr_d*, const vsip_cmview_d* ) ; int vsip_cqrd_destroy_d ( vsip_cqr_d* ) ; int vsip_cqrd_destroy_f ( vsip_cqr_f* ) ; int vsip_cqrd_f ( vsip_cqr_f*, const vsip_cmview_f* ) ; int vsip_cqrdprodq_d ( const vsip_cqr_d*, vsip_mat_op, vsip_mat_side, const vsip_cmview_d* ) ; int vsip_cqrdprodq_f ( const vsip_cqr_f*, vsip_mat_op, vsip_mat_side, const vsip_cmview_f* ) ; int vsip_cqrdsolr_d ( const vsip_cqr_d *, vsip_mat_op opR, vsip_cscalar_d, const vsip_cmview_d * ) ; int vsip_cqrdsolr_f ( const vsip_cqr_f *, vsip_mat_op opR, vsip_cscalar_f, const vsip_cmview_f * ) ; int vsip_cqrsol_d ( const vsip_cqr_d*, vsip_qrd_prob, const vsip_cmview_d* ) ; int vsip_cqrsol_f ( const vsip_cqr_f*, vsip_qrd_prob, const vsip_cmview_f* ) ; int vsip_ctoepsol_d ( const vsip_cvview_d*, const vsip_cvview_d*, const vsip_cvview_d*, const vsip_cvview_d* ) ; int vsip_ctoepsol_f ( const vsip_cvview_f*, const vsip_cvview_f*, const vsip_cvview_f*, const vsip_cvview_f* ) ; int vsip_fft_destroy_d ( vsip_fft_d* ) ; int vsip_fft_destroy_f ( vsip_fft_f* ) ; int vsip_fftm_destroy_d ( vsip_fftm_d* ) ; int vsip_fftm_destroy_f ( vsip_fftm_f* ) ; int vsip_finalize ( void* ) ; int vsip_fir_destroy_d ( vsip_fir_d* ) ; int vsip_fir_destroy_f ( vsip_fir_f* ) ; int vsip_firflt_d ( vsip_fir_d*, const vsip_vview_d*, const vsip_vview_d* ) ; int vsip_firflt_f ( vsip_fir_f*, const vsip_vview_f*, const vsip_vview_f* ) ; int vsip_init ( void* ) ; int vsip_llsqsol_d ( const vsip_mview_d*, const vsip_mview_d* ) ; int vsip_llsqsol_f ( const vsip_mview_f*, const vsip_mview_f* ) ; int vsip_lud_d ( vsip_lu_d*, const vsip_mview_d* ) ; int vsip_lud_destroy_d ( vsip_lu_d* ) ; int vsip_lud_destroy_f ( vsip_lu_f* ) ; int vsip_lud_f ( vsip_lu_f*, const vsip_mview_f* ) ; int vsip_lusol_d ( const vsip_lu_d*, vsip_mat_op, const vsip_mview_d* ) ; int vsip_lusol_f ( const vsip_lu_f*, vsip_mat_op, const vsip_mview_f* ) ; int vsip_qrd_d ( vsip_qr_d*, const vsip_mview_d* ) ; int vsip_qrd_destroy_d ( vsip_qr_d* ) ; int vsip_qrd_destroy_f ( vsip_qr_f* ) ; int vsip_qrd_f ( vsip_qr_f*, const vsip_mview_f* ) ; int vsip_qrdprodq_d ( const vsip_qr_d*, vsip_mat_op, vsip_mat_side, const vsip_mview_d* ) ; int vsip_qrdprodq_f ( const vsip_qr_f*, vsip_mat_op, vsip_mat_side, const vsip_mview_f* ) ; int vsip_qrdsolr_d ( const vsip_qr_d *, vsip_mat_op opR, vsip_scalar_d, const vsip_mview_d * ) ; int vsip_qrdsolr_f ( const vsip_qr_f *, vsip_mat_op opR, vsip_scalar_f, const vsip_mview_f * ) ; int vsip_qrsol_d ( const vsip_qr_d*, vsip_qrd_prob, const vsip_mview_d* ) ; int vsip_qrsol_f ( const vsip_qr_f*, vsip_qrd_prob, const vsip_mview_f* ) ; int vsip_randdestroy ( vsip_randstate *) ; int vsip_toepsol_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d* ) ; int vsip_toepsol_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f* ) ; vsip_cmview_d* vsip_cmbind_d(const vsip_cblock_d*,vsip_offset,vsip_stride, vsip_length,vsip_stride, vsip_length ); vsip_cmview_f* vsip_cmbind_f(const vsip_cblock_f*,vsip_offset,vsip_stride, vsip_length,vsip_stride, vsip_length ); vsip_mview_d* vsip_mbind_d(const vsip_block_d*,vsip_offset,vsip_stride, vsip_length,vsip_stride, vsip_length ); vsip_mview_f* vsip_mbind_f(const vsip_block_f*,vsip_offset,vsip_stride, vsip_length,vsip_stride, vsip_length ); vsip_mview_i* vsip_mbind_i(const vsip_block_i*,vsip_offset,vsip_stride, vsip_length,vsip_stride, vsip_length ); vsip_mview_li* vsip_mbind_li(const vsip_block_li*,vsip_offset,vsip_stride, vsip_length,vsip_stride, vsip_length ); vsip_mview_si* vsip_mbind_si(const vsip_block_si*,vsip_offset,vsip_stride, vsip_length,vsip_stride, vsip_length ); vsip_mview_uc* vsip_mbind_uc(const vsip_block_uc*,vsip_offset,vsip_stride, vsip_length,vsip_stride, vsip_length ); vsip_mview_bl* vsip_mbind_bl(const vsip_block_bl*,vsip_offset,vsip_stride, vsip_length,vsip_stride, vsip_length ); vsip_vview_i* vsip_vbind_i( const vsip_block_i*, vsip_offset, vsip_stride, vsip_length); vsip_vview_li* vsip_vbind_li( const vsip_block_li*, vsip_offset, vsip_stride, vsip_length); vsip_vview_uc* vsip_vbind_uc( const vsip_block_uc*, vsip_offset, vsip_stride, vsip_length); vsip_vview_vi* vsip_vbind_vi( const vsip_block_vi*, vsip_offset, vsip_stride, vsip_length); vsip_vview_bl* vsip_vbind_bl( const vsip_block_bl*, vsip_offset, vsip_stride, vsip_length); vsip_vview_si* vsip_vbind_si( const vsip_block_si*, vsip_offset, vsip_stride, vsip_length); vsip_vview_mi* vsip_vbind_mi( const vsip_block_mi*, vsip_offset, vsip_stride, vsip_length); vsip_tview_f *vsip_tbind_f(const vsip_block_f*,vsip_offset,vsip_stride,vsip_length,vsip_stride,vsip_length,vsip_stride,vsip_length); vsip_tview_d *vsip_tbind_d(const vsip_block_d*,vsip_offset,vsip_stride,vsip_length,vsip_stride,vsip_length,vsip_stride,vsip_length); vsip_vview_d* vsip_vcreate_blackman_d(vsip_length, vsip_memory_hint); vsip_vview_d* vsip_vcreate_hanning_d(vsip_length, vsip_memory_hint); vsip_vview_d* vsip_vcreate_kaiser_d(vsip_length, vsip_scalar_d, vsip_memory_hint); vsip_vview_d* vsip_vcreate_cheby_d(vsip_length, vsip_scalar_d, vsip_memory_hint); vsip_vview_f* vsip_vcreate_blackman_f(vsip_length, vsip_memory_hint); vsip_vview_f* vsip_vcreate_hanning_f(vsip_length, vsip_memory_hint); vsip_vview_f* vsip_vcreate_kaiser_f(vsip_length,vsip_scalar_f, vsip_memory_hint); vsip_vview_f* vsip_vcreate_cheby_f(vsip_length, vsip_scalar_f, vsip_memory_hint); vsip_vview_f* vsip_vputoffset_f( vsip_vview_f*, vsip_offset); vsip_vview_f* vsip_vputstride_f( vsip_vview_f*, vsip_stride); vsip_vview_f* vsip_vputlength_f( vsip_vview_f*, vsip_length); vsip_vview_f* vsip_vputattrib_f( vsip_vview_f*, const vsip_vattr_f*); vsip_vview_d* vsip_vputoffset_d( vsip_vview_d*, vsip_offset); vsip_vview_d* vsip_vputstride_d( vsip_vview_d*, vsip_stride); vsip_vview_d* vsip_vputlength_d( vsip_vview_d*, vsip_length); vsip_vview_d* vsip_vputattrib_d( vsip_vview_d*, const vsip_vattr_d*); vsip_vview_f* vsip_vcreate_f( vsip_length, vsip_memory_hint); vsip_vview_vi* vsip_vcreate_vi( vsip_length, vsip_memory_hint); vsip_vview_f* vsip_vcloneview_f( const vsip_vview_f*); vsip_vview_f* vsip_vbind_f( const vsip_block_f*, vsip_offset, vsip_stride, vsip_length); vsip_mview_d* vsip_mcreate_d(vsip_length,vsip_length,vsip_major,vsip_memory_hint); vsip_mview_f* vsip_mcreate_f(vsip_length,vsip_length,vsip_major,vsip_memory_hint); vsip_cmview_d* vsip_cmcreate_d(vsip_length,vsip_length,vsip_major,vsip_memory_hint); vsip_cmview_f* vsip_cmcreate_f(vsip_length,vsip_length,vsip_major,vsip_memory_hint); vsip_mview_i* vsip_mcreate_i(vsip_length,vsip_length,vsip_major,vsip_memory_hint); vsip_mview_li* vsip_mcreate_li(vsip_length,vsip_length,vsip_major,vsip_memory_hint); vsip_mview_si* vsip_mcreate_si(vsip_length,vsip_length,vsip_major,vsip_memory_hint); vsip_mview_uc* vsip_mcreate_uc(vsip_length,vsip_length,vsip_major,vsip_memory_hint); vsip_mview_bl* vsip_mcreate_bl(vsip_length,vsip_length,vsip_major,vsip_memory_hint); vsip_vview_d* vsip_vcreate_d( vsip_length, vsip_memory_hint); vsip_vview_d* vsip_vcloneview_d( const vsip_vview_d*); vsip_vview_d* vsip_vbind_d( const vsip_block_d*, vsip_offset, vsip_stride, vsip_length); vsip_cvview_f* vsip_cvputoffset_f( vsip_cvview_f*, vsip_offset); vsip_cvview_f* vsip_cvputstride_f( vsip_cvview_f*, vsip_stride); vsip_cvview_f* vsip_cvputlength_f( vsip_cvview_f*, vsip_length); vsip_cvview_f* vsip_cvputattrib_f( vsip_cvview_f*, const vsip_cvattr_f*); vsip_cvview_d* vsip_cvputoffset_d( vsip_cvview_d*, vsip_offset); vsip_cvview_d* vsip_cvputstride_d( vsip_cvview_d*, vsip_stride); vsip_cvview_d* vsip_cvputlength_d( vsip_cvview_d*, vsip_length); vsip_cvview_d* vsip_cvputattrib_d( vsip_cvview_d*, const vsip_cvattr_d*); vsip_cvview_f* vsip_cvcreate_f( vsip_length, vsip_memory_hint); vsip_cvview_f* vsip_cvcloneview_f( const vsip_cvview_f*); vsip_cvview_f* vsip_cvbind_f( const vsip_cblock_f*, vsip_offset, vsip_stride, vsip_length); vsip_cvview_d* vsip_cvcreate_d( vsip_length, vsip_memory_hint); vsip_cvview_d* vsip_cvcloneview_d( const vsip_cvview_d*); vsip_cvview_d* vsip_cvbind_d( const vsip_cblock_d*, vsip_offset, vsip_stride, vsip_length); vsip_cscalar_d vsip_cadd_d ( vsip_cscalar_d, vsip_cscalar_d ) ; vsip_cscalar_d vsip_cdiv_d ( vsip_cscalar_d, vsip_cscalar_d ) ; vsip_cscalar_d vsip_cexp_d ( vsip_cscalar_d ) ; vsip_cscalar_d vsip_cjmul_d ( vsip_cscalar_d, vsip_cscalar_d ) ; vsip_cscalar_d vsip_clog_d ( vsip_cscalar_d ) ; vsip_cscalar_d vsip_cmget_d ( const vsip_cmview_d*, vsip_index, vsip_index ) ; vsip_cscalar_d vsip_cmmeanval_d ( const vsip_cmview_d* ) ; vsip_cscalar_d vsip_cmplx_d ( vsip_scalar_d, vsip_scalar_d ) ; vsip_cscalar_d vsip_cmsumval_d ( const vsip_cmview_d* ) ; vsip_cscalar_d vsip_cmul_d ( vsip_cscalar_d, vsip_cscalar_d ) ; vsip_cscalar_d vsip_cneg_d ( vsip_cscalar_d ) ; vsip_cscalar_d vsip_conj_d ( vsip_cscalar_d ) ; vsip_cscalar_d vsip_crandn_d ( vsip_randstate* ) ; vsip_cscalar_d vsip_crandu_d ( vsip_randstate* ) ; vsip_cscalar_d vsip_crdiv_d ( vsip_cscalar_d, vsip_scalar_d ) ; vsip_cscalar_d vsip_crecip_d ( vsip_cscalar_d ) ; vsip_cscalar_d vsip_crsub_d ( vsip_cscalar_d, vsip_scalar_d ) ; vsip_cscalar_d vsip_csqrt_d ( vsip_cscalar_d ) ; vsip_cscalar_d vsip_csub_d ( vsip_cscalar_d, vsip_cscalar_d ) ; vsip_cscalar_d vsip_ctget_d ( const vsip_ctview_d*, vsip_index, vsip_index, vsip_index ) ; vsip_cscalar_d vsip_cvdot_d ( const vsip_cvview_d*, const vsip_cvview_d* ) ; vsip_cscalar_d vsip_cvget_d ( const vsip_cvview_d*, vsip_index ) ; vsip_cscalar_d vsip_cvjdot_d ( const vsip_cvview_d*, const vsip_cvview_d* ) ; vsip_cscalar_d vsip_cvmeanval_d ( const vsip_cvview_d* ) ; vsip_cscalar_d vsip_cvsumval_d ( const vsip_cvview_d* ) ; vsip_cscalar_d vsip_rcadd_d ( vsip_scalar_d, vsip_cscalar_d ) ; vsip_cscalar_d vsip_rcmul_d ( vsip_scalar_d, vsip_cscalar_d ) ; vsip_cscalar_d vsip_rcsub_d ( vsip_scalar_d, vsip_cscalar_d ) ; vsip_cscalar_d vsip_rect_d ( vsip_scalar_d, vsip_scalar_d ) ; vsip_cscalar_f vsip_cadd_f ( vsip_cscalar_f, vsip_cscalar_f ) ; vsip_cscalar_f vsip_cdiv_f ( vsip_cscalar_f, vsip_cscalar_f ) ; vsip_cscalar_f vsip_cexp_f ( vsip_cscalar_f ) ; vsip_cscalar_f vsip_cjmul_f ( vsip_cscalar_f, vsip_cscalar_f ) ; vsip_cscalar_f vsip_clog_f ( vsip_cscalar_f ) ; vsip_cscalar_f vsip_cmget_f ( const vsip_cmview_f*, vsip_index, vsip_index ) ; vsip_cscalar_f vsip_cmmeanval_f ( const vsip_cmview_f* ) ; vsip_cscalar_f vsip_cmplx_f ( vsip_scalar_f, vsip_scalar_f ) ; vsip_cscalar_f vsip_cmsumval_f ( const vsip_cmview_f* ) ; vsip_cscalar_f vsip_cmul_f ( vsip_cscalar_f, vsip_cscalar_f ) ; vsip_cscalar_f vsip_cneg_f ( vsip_cscalar_f ) ; vsip_cscalar_f vsip_conj_f ( vsip_cscalar_f ) ; vsip_cscalar_f vsip_crandn_f ( vsip_randstate* ) ; vsip_cscalar_f vsip_crandu_f ( vsip_randstate* ) ; vsip_cscalar_f vsip_crdiv_f ( vsip_cscalar_f, vsip_scalar_f ) ; vsip_cscalar_f vsip_crecip_f ( vsip_cscalar_f ) ; vsip_cscalar_f vsip_crsub_f ( vsip_cscalar_f, vsip_scalar_f ) ; vsip_cscalar_f vsip_csqrt_f ( vsip_cscalar_f ) ; vsip_cscalar_f vsip_csub_f ( vsip_cscalar_f, vsip_cscalar_f ) ; vsip_cscalar_f vsip_ctget_f ( const vsip_ctview_f*, vsip_index, vsip_index, vsip_index ) ; vsip_cscalar_f vsip_cvdot_f ( const vsip_cvview_f*, const vsip_cvview_f* ) ; vsip_cscalar_f vsip_cvget_f ( const vsip_cvview_f*, vsip_index ) ; vsip_cscalar_f vsip_cvjdot_f ( const vsip_cvview_f*, const vsip_cvview_f* ) ; vsip_cscalar_f vsip_cvmeanval_f ( const vsip_cvview_f* ) ; vsip_cscalar_f vsip_cvsumval_f ( const vsip_cvview_f* ) ; vsip_cscalar_f vsip_rcadd_f ( vsip_scalar_f, vsip_cscalar_f ) ; vsip_cscalar_f vsip_rcmul_f ( vsip_scalar_f, vsip_cscalar_f ) ; vsip_cscalar_f vsip_rcsub_f ( vsip_scalar_f, vsip_cscalar_f ) ; vsip_cscalar_f vsip_rect_f ( vsip_scalar_f r, vsip_scalar_f ) ; vsip_scalar_bl vsip_malltrue_bl ( const vsip_mview_bl* ) ; vsip_scalar_bl vsip_manytrue_bl ( const vsip_mview_bl* ) ; vsip_scalar_bl vsip_mget_bl ( const vsip_mview_bl*, vsip_index, vsip_index ) ; vsip_scalar_bl vsip_valltrue_bl ( const vsip_vview_bl* ) ; vsip_scalar_bl vsip_vanytrue_bl ( const vsip_vview_bl* ) ; vsip_scalar_bl vsip_vget_bl ( const vsip_vview_bl*, vsip_index ) ; vsip_scalar_d vsip_arg_d ( vsip_cscalar_d ) ; vsip_scalar_d vsip_cmag_d ( vsip_cscalar_d ) ; vsip_scalar_d vsip_cmagsq_d ( vsip_cscalar_d ) ; vsip_scalar_d vsip_cmmeansqval_d ( const vsip_cmview_d* ) ; vsip_scalar_d vsip_cvmeansqval_d ( const vsip_cvview_d* ) ; vsip_scalar_d vsip_cvmodulate_d ( const vsip_cvview_d*, vsip_scalar_d, vsip_scalar_d, const vsip_cvview_d* ) ; vsip_scalar_d vsip_mcmaxmgsqval_d ( const vsip_cmview_d*, vsip_scalar_mi* ) ; vsip_scalar_d vsip_mcminmgsqval_d ( const vsip_cmview_d*, vsip_scalar_mi* ) ; vsip_scalar_d vsip_mget_d ( const vsip_mview_d*, vsip_index, vsip_index ) ; vsip_scalar_d vsip_mmaxmgval_d ( const vsip_mview_d*, vsip_scalar_mi* ) ; vsip_scalar_d vsip_mmaxval_d ( const vsip_mview_d*, vsip_scalar_mi* ) ; vsip_scalar_d vsip_mmeansqval_d ( const vsip_mview_d* ) ; vsip_scalar_d vsip_mmeanval_d ( const vsip_mview_d* ) ; vsip_scalar_d vsip_mminmgval_d ( const vsip_mview_d*, vsip_scalar_mi* ) ; vsip_scalar_d vsip_mminval_d ( const vsip_mview_d*, vsip_scalar_mi* ) ; vsip_scalar_d vsip_msumsqval_d ( const vsip_mview_d* ) ; vsip_scalar_d vsip_msumval_d ( const vsip_mview_d* ) ; vsip_scalar_d vsip_randn_d ( vsip_randstate* ) ; vsip_scalar_d vsip_randu_d ( vsip_randstate* ) ; vsip_scalar_d vsip_tget_d ( const vsip_tview_d*, vsip_index, vsip_index, vsip_index ) ; vsip_scalar_d vsip_vcmaxmgsqval_d ( const vsip_cvview_d*, vsip_index* ) ; vsip_scalar_d vsip_vcminmgsqval_d ( const vsip_cvview_d*, vsip_index* ) ; vsip_scalar_d vsip_vdot_d ( const vsip_vview_d*, const vsip_vview_d* ) ; vsip_scalar_d vsip_vget_d ( const vsip_vview_d*, vsip_index ) ; vsip_scalar_d vsip_vmaxmgval_d ( const vsip_vview_d*, vsip_index * ) ; vsip_scalar_d vsip_vmaxval_d ( const vsip_vview_d*, vsip_index* ) ; vsip_scalar_d vsip_vmeansqval_d ( const vsip_vview_d* ) ; vsip_scalar_d vsip_vmeanval_d ( const vsip_vview_d* ) ; vsip_scalar_d vsip_vminmgval_d ( const vsip_vview_d*, vsip_index * ) ; vsip_scalar_d vsip_vminval_d ( const vsip_vview_d*, vsip_index* ) ; vsip_scalar_d vsip_vmodulate_d ( const vsip_vview_d*, vsip_scalar_d, vsip_scalar_d, const vsip_cvview_d* ) ; vsip_scalar_d vsip_vsumsqval_d ( const vsip_vview_d* ) ; vsip_scalar_d vsip_vsumval_d ( const vsip_vview_d* ) ; vsip_scalar_f vsip_arg_f ( vsip_cscalar_f ) ; vsip_scalar_f vsip_cmag_f ( vsip_cscalar_f ) ; vsip_scalar_f vsip_cmagsq_f ( vsip_cscalar_f ) ; vsip_scalar_f vsip_cmmeansqval_f ( const vsip_cmview_f* ) ; vsip_scalar_f vsip_cvmeansqval_f ( const vsip_cvview_f* ) ; vsip_scalar_f vsip_cvmodulate_f ( const vsip_cvview_f*, vsip_scalar_f, vsip_scalar_f, const vsip_cvview_f* ) ; vsip_scalar_f vsip_mcmaxmgsqval_f ( const vsip_cmview_f*, vsip_scalar_mi* ) ; vsip_scalar_f vsip_mcminmgsqval_f ( const vsip_cmview_f*, vsip_scalar_mi* ) ; vsip_scalar_f vsip_mget_f ( const vsip_mview_f*, vsip_index, vsip_index ) ; vsip_scalar_f vsip_mmaxmgval_f ( const vsip_mview_f*, vsip_scalar_mi* ) ; vsip_scalar_f vsip_mmaxval_f ( const vsip_mview_f*, vsip_scalar_mi* ) ; vsip_scalar_f vsip_mmeansqval_f ( const vsip_mview_f* ) ; vsip_scalar_f vsip_mmeanval_f ( const vsip_mview_f* ) ; vsip_scalar_f vsip_mminmgval_f ( const vsip_mview_f*, vsip_scalar_mi* ) ; vsip_scalar_f vsip_mminval_f ( const vsip_mview_f*, vsip_scalar_mi* ) ; vsip_scalar_f vsip_msumsqval_f ( const vsip_mview_f* ) ; vsip_scalar_f vsip_msumval_f ( const vsip_mview_f* ) ; vsip_scalar_f vsip_randn_f ( vsip_randstate* ) ; vsip_scalar_f vsip_randu_f ( vsip_randstate* ) ; vsip_scalar_f vsip_tget_f ( const vsip_tview_f*, vsip_index, vsip_index, vsip_index ) ; vsip_scalar_f vsip_vcmaxmgsqval_f ( const vsip_cvview_f*, vsip_index * ) ; vsip_scalar_f vsip_vcminmgsqval_f ( const vsip_cvview_f*, vsip_index * ) ; vsip_scalar_f vsip_vdot_f ( const vsip_vview_f*, const vsip_vview_f* ) ; vsip_scalar_f vsip_vget_f ( const vsip_vview_f*, vsip_index ) ; vsip_scalar_f vsip_vmaxmgval_f ( const vsip_vview_f*, vsip_index * ) ; vsip_scalar_f vsip_vmaxval_f ( const vsip_vview_f*, vsip_index* ) ; vsip_scalar_f vsip_vmeansqval_f ( const vsip_vview_f* ) ; vsip_scalar_f vsip_vmeanval_f ( const vsip_vview_f* ) ; vsip_scalar_f vsip_vminmgval_f ( const vsip_vview_f*, vsip_index * ) ; vsip_scalar_f vsip_vminval_f ( const vsip_vview_f*, vsip_index* ) ; vsip_scalar_f vsip_vmodulate_f ( const vsip_vview_f*, vsip_scalar_f, vsip_scalar_f, const vsip_cvview_f* ) ; vsip_scalar_f vsip_vsumsqval_f ( const vsip_vview_f* ) ; vsip_scalar_f vsip_vsumval_f ( const vsip_vview_f* ) ; vsip_scalar_i vsip_mget_i ( const vsip_mview_i*, vsip_index, vsip_index ) ; vsip_scalar_i vsip_mmaxval_i ( const vsip_mview_i*, vsip_scalar_mi* ) ; vsip_scalar_i vsip_mminval_i ( const vsip_mview_i*, vsip_scalar_mi* ) ; vsip_scalar_i vsip_tget_i ( const vsip_tview_i*, vsip_index, vsip_index, vsip_index ) ; vsip_scalar_i vsip_vget_i ( const vsip_vview_i*, vsip_index ) ; vsip_scalar_i vsip_vmaxval_i ( const vsip_vview_i*, vsip_index* ) ; vsip_scalar_i vsip_vminval_i ( const vsip_vview_i*, vsip_index* ) ; vsip_scalar_i vsip_vsumval_i ( const vsip_vview_i* ) ; vsip_scalar_li vsip_mget_li ( const vsip_mview_li*, vsip_index, vsip_index ) ; vsip_scalar_li vsip_mmaxval_li ( const vsip_mview_li*, vsip_scalar_mi* ) ; vsip_scalar_li vsip_mminval_li ( const vsip_mview_li*, vsip_scalar_mi* ) ; vsip_scalar_li vsip_tget_li ( const vsip_tview_li*, vsip_index, vsip_index, vsip_index ) ; vsip_scalar_li vsip_vget_li ( const vsip_vview_li*, vsip_index ) ; vsip_scalar_li vsip_vmaxval_li ( const vsip_vview_li*, vsip_index* ) ; vsip_scalar_li vsip_vminval_li ( const vsip_vview_li*, vsip_index* ) ; vsip_scalar_li vsip_vsumval_li ( const vsip_vview_li* ) ; vsip_scalar_mi vsip_matindex ( vsip_scalar_vi r, vsip_scalar_vi c ) ; vsip_scalar_mi vsip_vget_mi ( const vsip_vview_mi*, vsip_index ) ; vsip_scalar_si vsip_mget_si ( const vsip_mview_si*, vsip_index, vsip_index ) ; vsip_scalar_si vsip_mmaxval_si ( const vsip_mview_si*, vsip_scalar_mi* ) ; vsip_scalar_si vsip_mminval_si ( const vsip_mview_si*, vsip_scalar_mi* ) ; vsip_scalar_si vsip_tget_si ( const vsip_tview_si*, vsip_index, vsip_index, vsip_index ) ; vsip_scalar_si vsip_vget_si ( const vsip_vview_si*, vsip_index ) ; vsip_scalar_si vsip_vmaxval_si ( const vsip_vview_si*, vsip_index* ) ; vsip_scalar_si vsip_vminval_si ( const vsip_vview_si*, vsip_index* ) ; vsip_scalar_si vsip_vsumval_si ( const vsip_vview_si* ) ; vsip_scalar_uc vsip_mget_uc ( const vsip_mview_uc*, vsip_index, vsip_index ) ; vsip_scalar_uc vsip_tget_uc ( const vsip_tview_uc*, vsip_index, vsip_index, vsip_index ) ; vsip_scalar_uc vsip_vget_uc ( const vsip_vview_uc*, vsip_index ) ; vsip_scalar_uc vsip_vsumval_uc ( const vsip_vview_uc* ) ; vsip_scalar_vi vsip_msumval_bl ( const vsip_mview_bl* ) ; vsip_scalar_vi vsip_vget_vi ( const vsip_vview_vi*, vsip_index ) ; vsip_scalar_vi vsip_vsumval_bl ( const vsip_vview_bl* ) ; vsip_scalar_vi vsip_vmaxval_vi ( const vsip_vview_vi*, vsip_index* ) ; vsip_scalar_vi vsip_vminval_vi ( const vsip_vview_vi*, vsip_index* ) ; void vsip_vgetattrib_bl ( const vsip_vview_bl*, vsip_vattr_bl* ) ; void vsip_CDIV_d ( vsip_cscalar_d, vsip_cscalar_d, vsip_cscalar_d* ) ; void vsip_CDIV_f ( vsip_cscalar_f, vsip_cscalar_f, vsip_cscalar_f* ) ; void vsip_CEXP_d ( vsip_cscalar_d, vsip_cscalar_d* ) ; void vsip_CEXP_f ( vsip_cscalar_f, vsip_cscalar_f* ) ; void vsip_CRECIP_d ( vsip_cscalar_d, vsip_cscalar_d* ) ; void vsip_CRECIP_f ( vsip_cscalar_f, vsip_cscalar_f* ) ; void vsip_CSQRT_d ( vsip_cscalar_d, vsip_cscalar_d* ) ; void vsip_CSQRT_f ( vsip_cscalar_f, vsip_cscalar_f* ) ; void vsip_MATINDEX ( vsip_scalar_vi, vsip_scalar_vi, vsip_scalar_mi* ) ; void vsip_blockdestroy_bl ( vsip_block_bl* ) ; void vsip_blockdestroy_d ( vsip_block_d* ) ; void vsip_blockdestroy_f ( vsip_block_f* ) ; void vsip_blockdestroy_i ( vsip_block_i* ) ; void vsip_blockdestroy_li ( vsip_block_li* ) ; void vsip_blockdestroy_mi ( vsip_block_mi* ) ; void vsip_blockdestroy_si ( vsip_block_si* ) ; void vsip_blockdestroy_uc ( vsip_block_uc* ) ; void vsip_blockdestroy_vi ( vsip_block_vi * ) ; void vsip_cblockdestroy_d ( vsip_cblock_d* ) ; void vsip_cblockdestroy_f ( vsip_cblock_f* ) ; void vsip_cblockfind_d ( const vsip_cblock_d*, vsip_scalar_d**, vsip_scalar_d** ) ; void vsip_cblockfind_f ( const vsip_cblock_f*, vsip_scalar_f**, vsip_scalar_f** ) ; void vsip_cblockrebind_d ( vsip_cblock_d*, vsip_scalar_d* const, vsip_scalar_d* const, vsip_scalar_d**, vsip_scalar_d** ) ; void vsip_cblockrebind_f ( vsip_cblock_f*, vsip_scalar_f* const, vsip_scalar_f* const, vsip_scalar_f**, vsip_scalar_f** ) ; void vsip_cblockrelease_d ( vsip_cblock_d*, vsip_scalar_bl, vsip_scalar_d**, vsip_scalar_d** ) ; void vsip_cblockrelease_f ( vsip_cblock_f*, vsip_scalar_bl, vsip_scalar_f**, vsip_scalar_f** ) ; void vsip_ccfftip_d ( const vsip_fft_d*, const vsip_cvview_d* ) ; void vsip_ccfftip_f ( const vsip_fft_f*, const vsip_cvview_f* ) ; void vsip_ccfftmip_d ( const vsip_fftm_d*, const vsip_cmview_d* ) ; void vsip_ccfftmip_f ( const vsip_fftm_f*, const vsip_cmview_f* ) ; void vsip_ccfftmop_d ( const vsip_fftm_d*, const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_ccfftmop_f ( const vsip_fftm_f*, const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_ccfftop_d ( const vsip_fft_d*, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_ccfftop_f ( const vsip_fft_f*, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_cchold_getattr_d ( const vsip_cchol_d *, vsip_cchol_attr_d * ) ; void vsip_cchold_getattr_f ( const vsip_cchol_f *, vsip_cchol_attr_f * ) ; void vsip_ccorr1d_getattr_d ( const vsip_ccorr1d_d*, vsip_corr1d_attr* ) ; void vsip_ccorr1d_getattr_f ( const vsip_ccorr1d_f*, vsip_corr1d_attr* ) ; void vsip_ccorrelate1d_d ( const vsip_ccorr1d_d*, vsip_bias bias, const vsip_cvview_d*, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_ccorrelate1d_f ( const vsip_ccorr1d_f*, vsip_bias, const vsip_cvview_f*, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_rcfir_getattr_d ( const vsip_rcfir_d*, vsip_rcfir_attr* ) ; void vsip_rcfir_getattr_f ( const vsip_rcfir_f*, vsip_rcfir_attr* ) ; void vsip_cfir_getattr_d ( const vsip_cfir_d*, vsip_cfir_attr* ) ; void vsip_cfir_getattr_f ( const vsip_cfir_f*, vsip_cfir_attr* ) ; void vsip_rcfir_reset_d ( vsip_rcfir_d* ) ; void vsip_rcfir_reset_f ( vsip_rcfir_f* ) ; void vsip_cfir_reset_d ( vsip_cfir_d* ) ; void vsip_cfir_reset_f ( vsip_cfir_f* ) ; void vsip_cgemp_d ( vsip_cscalar_d, const vsip_cmview_d *, vsip_mat_op, const vsip_cmview_d *, vsip_mat_op, vsip_cscalar_d, const vsip_cmview_d * ) ; void vsip_cgemp_f ( vsip_cscalar_f, const vsip_cmview_f *, vsip_mat_op, const vsip_cmview_f *, vsip_mat_op, vsip_cscalar_f, const vsip_cmview_f * ) ; void vsip_cgems_d ( vsip_cscalar_d, const vsip_cmview_d *, vsip_mat_op, vsip_cscalar_d, const vsip_cmview_d * ) ; void vsip_cgems_f ( vsip_cscalar_f, const vsip_cmview_f *, vsip_mat_op, vsip_cscalar_f, const vsip_cmview_f * ) ; void vsip_chold_getattr_d ( const vsip_chol_d *, vsip_chol_attr_d * ) ; void vsip_chold_getattr_f ( const vsip_chol_f *, vsip_chol_attr_f * ) ; void vsip_clud_getattr_d ( const vsip_clu_d*, vsip_clu_attr_d* ) ; void vsip_clud_getattr_f ( const vsip_clu_f*, vsip_clu_attr_f* ) ; void vsip_cmadd_d ( const vsip_cmview_d*, const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_cmadd_f ( const vsip_cmview_f*, const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_cmalldestroy_d ( vsip_cmview_d* ) ; void vsip_cmalldestroy_f ( vsip_cmview_f* ) ; void vsip_cmconj_d ( const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_cmconj_f ( const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_cmcopy_d_d ( const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_cmcopy_d_f ( const vsip_cmview_d*, const vsip_cmview_f* ) ; void vsip_cmcopy_f_d ( const vsip_cmview_f*, const vsip_cmview_d* ) ; void vsip_cmcopy_f_f ( const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_cmcopyfrom_user_d ( vsip_scalar_d* const, vsip_scalar_d* const, vsip_major, const vsip_cmview_d* ) ; void vsip_cmcopyfrom_user_f ( vsip_scalar_f* const, vsip_scalar_f* const, vsip_major, const vsip_cmview_f* ) ; void vsip_cmcopyto_user_d ( const vsip_cmview_d*, vsip_major, vsip_scalar_d* const, vsip_scalar_d* const ) ; void vsip_cmcopyto_user_f ( const vsip_cmview_f*, vsip_major, vsip_scalar_f* const, vsip_scalar_f* const ) ; void vsip_cmdiv_d ( const vsip_cmview_d*, const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_cmdiv_f ( const vsip_cmview_f*, const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_cmexp_d ( const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_cmexp_f ( const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_cmexpoavg_d ( vsip_scalar_d, const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_cmexpoavg_f ( vsip_scalar_f, const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_cmfill_d ( vsip_cscalar_d, const vsip_cmview_d* ) ; void vsip_cmfill_f ( vsip_cscalar_f, const vsip_cmview_f* ) ; void vsip_cmgather_d ( const vsip_cmview_d*, const vsip_vview_mi*, const vsip_cvview_d* ) ; void vsip_cmgather_f ( const vsip_cmview_f*, const vsip_vview_mi*, const vsip_cvview_f* ) ; void vsip_cmgetattrib_d ( const vsip_cmview_d*, vsip_cmattr_d* ) ; void vsip_cmgetattrib_f ( const vsip_cmview_f*, vsip_cmattr_f* ) ; void vsip_cmherm_d ( const vsip_cmview_d *, const vsip_cmview_d * ) ; void vsip_cmherm_f ( const vsip_cmview_f *, const vsip_cmview_f * ) ; void vsip_cmjmul_d ( const vsip_cmview_d*, const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_cmjmul_f ( const vsip_cmview_f*, const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_cmkron_d ( vsip_cscalar_d, const vsip_cmview_d *, const vsip_cmview_d *, const vsip_cmview_d * ) ; void vsip_cmkron_f ( vsip_cscalar_f, const vsip_cmview_f *, const vsip_cmview_f *, const vsip_cmview_f * ) ; void vsip_cmlog_d ( const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_cmlog_f ( const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_cmmag_d ( const vsip_cmview_d*, const vsip_mview_d* ) ; void vsip_cmmag_f ( const vsip_cmview_f*, const vsip_mview_f* ) ; void vsip_cmmul_d ( const vsip_cmview_d*, const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_cmmul_f ( const vsip_cmview_f*, const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_cmneg_d ( const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_cmneg_f ( const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_cmprod3_d ( const vsip_cmview_d *, const vsip_cmview_d *, const vsip_cmview_d * ) ; void vsip_cmprod3_f ( const vsip_cmview_f *, const vsip_cmview_f *, const vsip_cmview_f * ) ; void vsip_cmprod4_d ( const vsip_cmview_d *, const vsip_cmview_d *, const vsip_cmview_d * ) ; void vsip_cmprod4_f ( const vsip_cmview_f *, const vsip_cmview_f *, const vsip_cmview_f * ) ; void vsip_cmprod_d ( const vsip_cmview_d *, const vsip_cmview_d *, const vsip_cmview_d * ) ; void vsip_cmprod_f ( const vsip_cmview_f *, const vsip_cmview_f *, const vsip_cmview_f * ) ; void vsip_cmprodh_d ( const vsip_cmview_d *, const vsip_cmview_d *, const vsip_cmview_d * ) ; void vsip_cmprodh_f ( const vsip_cmview_f *, const vsip_cmview_f *, const vsip_cmview_f * ) ; void vsip_cmprodj_d ( const vsip_cmview_d *, const vsip_cmview_d *, const vsip_cmview_d * ) ; void vsip_cmprodj_f ( const vsip_cmview_f *, const vsip_cmview_f *, const vsip_cmview_f * ) ; void vsip_cmprodt_d ( const vsip_cmview_d *, const vsip_cmview_d *, const vsip_cmview_d * ) ; void vsip_cmprodt_f ( const vsip_cmview_f *, const vsip_cmview_f *, const vsip_cmview_f * ) ; void vsip_cmput_d ( const vsip_cmview_d*, vsip_index, vsip_index, vsip_cscalar_d ) ; void vsip_cmput_f ( const vsip_cmview_f*, vsip_index, vsip_index, vsip_cscalar_f ) ; void vsip_cmrecip_d ( const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_cmrecip_f ( const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_cmrsdiv_d ( const vsip_cmview_d*, vsip_scalar_d, const vsip_cmview_d* ) ; void vsip_cmrsdiv_f ( const vsip_cmview_f*, vsip_scalar_f, const vsip_cmview_f* ) ; void vsip_cmscatter_d ( const vsip_cvview_d*, const vsip_cmview_d*, const vsip_vview_mi* ) ; void vsip_cmscatter_f ( const vsip_cvview_f*, const vsip_cmview_f*, const vsip_vview_mi* ) ; void vsip_cmsqrt_d ( const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_cmsqrt_f ( const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_cmsub_d ( const vsip_cmview_d*, const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_cmsub_f ( const vsip_cmview_f*, const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_cmswap_d ( const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_cmswap_f ( const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_cmtrans_d ( const vsip_cmview_d *, const vsip_cmview_d * ) ; void vsip_cmtrans_f ( const vsip_cmview_f *, const vsip_cmview_f * ) ; void vsip_cmvprod3_d ( const vsip_cmview_d *, const vsip_cvview_d *, const vsip_cvview_d * ) ; void vsip_cmvprod3_f ( const vsip_cmview_f *, const vsip_cvview_f *, const vsip_cvview_f * ) ; void vsip_cmvprod4_d ( const vsip_cmview_d *, const vsip_cvview_d *, const vsip_cvview_d * ) ; void vsip_cmvprod4_f ( const vsip_cmview_f *, const vsip_cvview_f *, const vsip_cvview_f * ) ; void vsip_cmvprod_d ( const vsip_cmview_d *, const vsip_cvview_d *, const vsip_cvview_d * ) ; void vsip_cmvprod_f ( const vsip_cmview_f *, const vsip_cvview_f *, const vsip_cvview_f * ) ; void vsip_conv1d_getattr_d ( const vsip_conv1d_d*, vsip_conv1d_attr* ) ; void vsip_conv1d_getattr_f ( const vsip_conv1d_f*, vsip_conv1d_attr* ) ; void vsip_convolve1d_d ( const vsip_conv1d_d*, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_convolve1d_f ( const vsip_conv1d_f*, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_corr1d_getattr_d ( const vsip_corr1d_d*, vsip_corr1d_attr* ) ; void vsip_corr1d_getattr_f ( const vsip_corr1d_f*, vsip_corr1d_attr* ) ; void vsip_correlate1d_d ( const vsip_corr1d_d*, vsip_bias bias, const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_correlate1d_f ( const vsip_corr1d_f*, vsip_bias, const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_cqrd_getattr_d ( const vsip_cqr_d *, vsip_cqr_attr_d * ) ; void vsip_cqrd_getattr_f ( const vsip_cqr_f *, vsip_cqr_attr_f * ) ; void vsip_crfftmop_d ( const vsip_fftm_d*, const vsip_cmview_d*, const vsip_mview_d* ) ; void vsip_crfftmop_f ( const vsip_fftm_f*, const vsip_cmview_f*, const vsip_mview_f* ) ; void vsip_crfftop_d ( const vsip_fft_d*, const vsip_cvview_d*, const vsip_vview_d* ) ; void vsip_crfftop_f ( const vsip_fft_f*, const vsip_cvview_f*, const vsip_vview_f* ) ; void vsip_crmdiv_d ( const vsip_cmview_d*, const vsip_mview_d*, const vsip_cmview_d* ) ; void vsip_crmdiv_f ( const vsip_cmview_f*, const vsip_mview_f*, const vsip_cmview_f* ) ; void vsip_crmsub_d ( const vsip_cmview_d*, const vsip_mview_d*, const vsip_cmview_d* ) ; void vsip_crmsub_f ( const vsip_cmview_f*, const vsip_mview_f*, const vsip_cmview_f* ) ; void vsip_crvdiv_d ( const vsip_cvview_d*, const vsip_vview_d*, const vsip_cvview_d* ) ; void vsip_crvdiv_f ( const vsip_cvview_f*, const vsip_vview_f*, const vsip_cvview_f* ) ; void vsip_crvsub_d ( const vsip_cvview_d*, const vsip_vview_d*, const vsip_cvview_d* ) ; void vsip_crvsub_f ( const vsip_cvview_f*, const vsip_vview_f*, const vsip_cvview_f* ) ; void vsip_csmadd_d ( vsip_cscalar_d, const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_csmadd_f ( vsip_cscalar_f, const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_csmdiv_d ( vsip_cscalar_d, const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_csmdiv_f ( vsip_cscalar_f, const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_csmmul_d ( vsip_cscalar_d, const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_csmmul_f ( vsip_cscalar_f, const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_csmsub_d ( vsip_cscalar_d, const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_csmsub_f ( vsip_cscalar_f, const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_csvadd_d ( vsip_cscalar_d, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_csvadd_f ( vsip_cscalar_f, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_csvdiv_d ( vsip_cscalar_d, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_csvdiv_f ( vsip_cscalar_f, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_csvmul_d ( vsip_cscalar_d, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_csvmul_f ( vsip_cscalar_f, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_csvsub_d ( vsip_cscalar_d, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_csvsub_f ( vsip_cscalar_f, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_ctalldestroy_d ( vsip_ctview_d* ) ; void vsip_ctalldestroy_f ( vsip_ctview_f* ) ; void vsip_ctgetattrib_d ( const vsip_ctview_d*, vsip_ctattr_d* ) ; void vsip_ctgetattrib_f ( const vsip_ctview_f*, vsip_ctattr_f* ) ; void vsip_ctput_d ( const vsip_ctview_d*, vsip_index, vsip_index, vsip_index, vsip_cscalar_d ) ; void vsip_ctput_f ( const vsip_ctview_f*, vsip_index, vsip_index, vsip_index, vsip_cscalar_f ) ; void vsip_ctputattrib_d ( vsip_ctview_d*, const vsip_ctattr_d* ) ; void vsip_ctputattrib_f ( vsip_ctview_f*, const vsip_ctattr_f* ) ; void vsip_cvadd_d ( const vsip_cvview_d*, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_cvadd_f ( const vsip_cvview_f*, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_cvalldestroy_d ( vsip_cvview_d* ) ; void vsip_cvalldestroy_f ( vsip_cvview_f* ) ; void vsip_cvam_d ( const vsip_cvview_d*, const vsip_cvview_d*, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_cvam_f ( const vsip_cvview_f*, const vsip_cvview_f*, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_cvconj_d ( const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_cvconj_f ( const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_cvcopy_d_d ( const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_cvcopy_d_f ( const vsip_cvview_d*, const vsip_cvview_f* ) ; void vsip_cvcopy_f_d ( const vsip_cvview_f*, const vsip_cvview_d* ) ; void vsip_cvcopy_f_f ( const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_cvcopyfrom_user_d ( vsip_scalar_d* const, vsip_scalar_d* const, const vsip_cvview_d* ) ; void vsip_cvcopyfrom_user_f ( vsip_scalar_f* const, vsip_scalar_f* const, const vsip_cvview_f* ) ; void vsip_cvcopyto_user_d ( const vsip_cvview_d*, vsip_scalar_d* const, vsip_scalar_d* const ) ; void vsip_cvcopyto_user_f ( const vsip_cvview_f*, vsip_scalar_f* const, vsip_scalar_f* const ) ; void vsip_cvdiv_d ( const vsip_cvview_d*, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_cvdiv_f ( const vsip_cvview_f*, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_cvexp_d ( const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_cvexp_f ( const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_cvexpoavg_d ( vsip_scalar_d, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_cvexpoavg_f ( vsip_scalar_f, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_cvfill_d ( vsip_cscalar_d, const vsip_cvview_d* ) ; void vsip_cvfill_f ( vsip_cscalar_f, const vsip_cvview_f* ) ; void vsip_cvgather_d ( const vsip_cvview_d*, const vsip_vview_vi*, const vsip_cvview_d* ) ; void vsip_cvgather_f ( const vsip_cvview_f*, const vsip_vview_vi*, const vsip_cvview_f* ) ; void vsip_cvgetattrib_d ( const vsip_cvview_d*, vsip_cvattr_d* ) ; void vsip_cvgetattrib_f ( const vsip_cvview_f*, vsip_cvattr_f* ) ; void vsip_cvjmul_d ( const vsip_cvview_d*, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_cvjmul_f ( const vsip_cvview_f*, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_cvkron_d ( vsip_cscalar_d, const vsip_cvview_d *, const vsip_cvview_d *, const vsip_cmview_d * ) ; void vsip_cvkron_f ( vsip_cscalar_f, const vsip_cvview_f *, const vsip_cvview_f *, const vsip_cmview_f * ) ; void vsip_cvlog_d ( const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_cvlog_f ( const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_cvma_d ( const vsip_cvview_d*, const vsip_cvview_d*, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_cvma_f ( const vsip_cvview_f*, const vsip_cvview_f*, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_cvmag_d ( const vsip_cvview_d*, const vsip_vview_d* ) ; void vsip_cvmag_f ( const vsip_cvview_f*, const vsip_vview_f* ) ; void vsip_cvmmul_d ( const vsip_cvview_d*, const vsip_cmview_d*, vsip_major, const vsip_cmview_d* ) ; void vsip_cvmmul_f ( const vsip_cvview_f*, const vsip_cmview_f*, vsip_major, const vsip_cmview_f* ) ; void vsip_cvmprod_d ( const vsip_cvview_d *, const vsip_cmview_d *, const vsip_cvview_d * ) ; void vsip_cvmprod_f ( const vsip_cvview_f *, const vsip_cmview_f *, const vsip_cvview_f * ) ; void vsip_cvmsa_d ( const vsip_cvview_d*, const vsip_cvview_d*, vsip_cscalar_d, const vsip_cvview_d* ) ; void vsip_cvmsa_f ( const vsip_cvview_f*, const vsip_cvview_f*, vsip_cscalar_f, const vsip_cvview_f* ) ; void vsip_cvmsb_d ( const vsip_cvview_d*, const vsip_cvview_d*, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_cvmsb_f ( const vsip_cvview_f*, const vsip_cvview_f*, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_cvmul_d ( const vsip_cvview_d*, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_cvmul_f ( const vsip_cvview_f*, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_cvneg_d ( const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_cvneg_f ( const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_cvouter_d ( vsip_cscalar_d, const vsip_cvview_d *, const vsip_cvview_d *, const vsip_cmview_d * ) ; void vsip_cvouter_f ( vsip_cscalar_f, const vsip_cvview_f *, const vsip_cvview_f *, const vsip_cmview_f * ) ; void vsip_cvput_d ( const vsip_cvview_d*, vsip_index, vsip_cscalar_d ) ; void vsip_cvput_f ( const vsip_cvview_f*, vsip_index, vsip_cscalar_f ) ; void vsip_cvrandn_d ( vsip_randstate *, const vsip_cvview_d* ) ; void vsip_cvrandn_f ( vsip_randstate *, const vsip_cvview_f* ) ; void vsip_cvrandu_d ( vsip_randstate *, const vsip_cvview_d* ) ; void vsip_cvrandu_f ( vsip_randstate *, const vsip_cvview_f* ) ; void vsip_cmrandn_d ( vsip_randstate*, const vsip_cmview_d* ) ; void vsip_cmrandn_f ( vsip_randstate*, const vsip_cmview_f* ) ; void vsip_cmrandu_d ( vsip_randstate*, const vsip_cmview_d* ) ; void vsip_cmrandu_f ( vsip_randstate*, const vsip_cmview_f* ) ; void vsip_cvrecip_d ( const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_cvrecip_f ( const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_cvrsdiv_d ( const vsip_cvview_d*, vsip_scalar_d, const vsip_cvview_d* ) ; void vsip_cvrsdiv_f ( const vsip_cvview_f*, vsip_scalar_f, const vsip_cvview_f* ) ; void vsip_cvsam_d ( const vsip_cvview_d*, vsip_cscalar_d, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_cvsam_f ( const vsip_cvview_f*, vsip_cscalar_f, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_cvsbm_d ( const vsip_cvview_d*, const vsip_cvview_d*, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_cvsbm_f ( const vsip_cvview_f*, const vsip_cvview_f*, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_cvscatter_d ( const vsip_cvview_d*, const vsip_cvview_d*, const vsip_vview_vi* ) ; void vsip_cvscatter_f ( const vsip_cvview_f*, const vsip_cvview_f*, const vsip_vview_vi* ) ; void vsip_cvsma_d ( const vsip_cvview_d*, vsip_cscalar_d, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_cvsma_f ( const vsip_cvview_f*, vsip_cscalar_f, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_cvsmsa_d ( const vsip_cvview_d*, vsip_cscalar_d, vsip_cscalar_d, const vsip_cvview_d* ) ; void vsip_cvsmsa_f ( const vsip_cvview_f*, vsip_cscalar_f, vsip_cscalar_f, const vsip_cvview_f* ) ; void vsip_cvsqrt_d ( const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_cvsqrt_f ( const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_cvsub_d ( const vsip_cvview_d*, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_cvsub_f ( const vsip_cvview_f*, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_cvswap_d ( const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_cvswap_f ( const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_fft_getattr_d ( const vsip_fft_d*, vsip_fft_attr_d* ) ; void vsip_fft_getattr_f ( const vsip_fft_f*, vsip_fft_attr_f* ) ; void vsip_fftm_getattr_d ( const vsip_fftm_d*, vsip_fftm_attr_d* ) ; void vsip_fftm_getattr_f ( const vsip_fftm_f*, vsip_fftm_attr_f* ) ; void vsip_fir_getattr_d ( const vsip_fir_d*, vsip_fir_attr* ) ; void vsip_fir_getattr_f ( const vsip_fir_f*, vsip_fir_attr* ) ; void vsip_fir_reset_d ( vsip_fir_d* ) ; void vsip_fir_reset_f ( vsip_fir_f* ) ; void vsip_gemp_d ( vsip_scalar_d, const vsip_mview_d *, vsip_mat_op, const vsip_mview_d *, vsip_mat_op, vsip_scalar_d, const vsip_mview_d * ) ; void vsip_gemp_f ( vsip_scalar_f, const vsip_mview_f *, vsip_mat_op, const vsip_mview_f *, vsip_mat_op, vsip_scalar_f, const vsip_mview_f * ) ; void vsip_gems_d ( vsip_scalar_d, const vsip_mview_d *, vsip_mat_op, vsip_scalar_d, const vsip_mview_d * ) ; void vsip_gems_f ( vsip_scalar_f, const vsip_mview_f *, vsip_mat_op, vsip_scalar_f, const vsip_mview_f * ) ; void vsip_lud_getattr_d ( const vsip_lu_d*, vsip_lu_attr_d* ) ; void vsip_lud_getattr_f ( const vsip_lu_f*, vsip_lu_attr_f* ) ; void vsip_macos_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_macos_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_madd_d ( const vsip_mview_d*, const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_madd_f ( const vsip_mview_f*, const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_madd_i ( const vsip_mview_i*, const vsip_mview_i*, const vsip_mview_i* ) ; void vsip_madd_li ( const vsip_mview_li*, const vsip_mview_li*, const vsip_mview_li* ) ; void vsip_madd_si ( const vsip_mview_si*, const vsip_mview_si*, const vsip_mview_si* ) ; void vsip_malldestroy_bl ( vsip_mview_bl* ) ; void vsip_malldestroy_d ( vsip_mview_d* ) ; void vsip_malldestroy_f ( vsip_mview_f* ) ; void vsip_malldestroy_i ( vsip_mview_i* ) ; void vsip_malldestroy_li ( vsip_mview_li* ) ; void vsip_malldestroy_si ( vsip_mview_si* ) ; void vsip_malldestroy_uc ( vsip_mview_uc* ) ; void vsip_mand_i ( const vsip_mview_i*, const vsip_mview_i*, const vsip_mview_i* ) ; void vsip_mand_li ( const vsip_mview_li*, const vsip_mview_li*, const vsip_mview_li* ) ; void vsip_mand_si ( const vsip_mview_si*, const vsip_mview_si*, const vsip_mview_si* ) ; void vsip_marg_d ( const vsip_cmview_d*, const vsip_mview_d* ) ; void vsip_marg_f ( const vsip_cmview_f*, const vsip_mview_f* ) ; void vsip_mceil_d_d(const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mceil_d_i(const vsip_mview_d*, const vsip_mview_i* ) ; void vsip_mceil_d_li(const vsip_mview_d*, const vsip_mview_li* ) ; void vsip_mceil_f_f(const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mceil_f_i(const vsip_mview_f*, const vsip_mview_i* ) ; void vsip_mceil_f_li(const vsip_mview_f*, const vsip_mview_li* ) ; void vsip_mfloor_d_d(const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mfloor_d_i(const vsip_mview_d*, const vsip_mview_i* ) ; void vsip_mfloor_d_li(const vsip_mview_d*, const vsip_mview_li* ) ; void vsip_mround_d_d(const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mround_d_i(const vsip_mview_d*, const vsip_mview_i* ) ; void vsip_mround_d_li(const vsip_mview_d*, const vsip_mview_li* ) ; void vsip_mround_f_f(const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mround_f_i(const vsip_mview_f*, const vsip_mview_i* ) ; void vsip_mround_f_li(const vsip_mview_f*, const vsip_mview_li* ) ; void vsip_vround_d_d(const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vround_d_i(const vsip_vview_d*, const vsip_vview_i* ) ; void vsip_vround_d_li(const vsip_vview_d*, const vsip_vview_li* ) ; void vsip_vround_f_f(const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vround_f_i(const vsip_vview_f*, const vsip_vview_i* ) ; void vsip_vround_f_li(const vsip_vview_f*, const vsip_vview_li* ) ; void vsip_mfloor_f_f(const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mfloor_f_i(const vsip_mview_f*, const vsip_mview_i* ) ; void vsip_mfloor_f_li(const vsip_mview_f*, const vsip_mview_li* ) ; void vsip_masin_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_masin_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_matan2_d ( const vsip_mview_d*, const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_matan2_f ( const vsip_mview_f*, const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_matan_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_matan_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mclip_d ( const vsip_mview_d*, vsip_scalar_d, vsip_scalar_d, vsip_scalar_d, vsip_scalar_d, const vsip_mview_d* ) ; void vsip_mclip_f ( const vsip_mview_f*, vsip_scalar_f, vsip_scalar_f, vsip_scalar_f, vsip_scalar_f, const vsip_mview_f* ) ; void vsip_mclip_i ( const vsip_mview_i*, vsip_scalar_i, vsip_scalar_i, vsip_scalar_i, vsip_scalar_i, const vsip_mview_i* ) ; void vsip_mclip_li ( const vsip_mview_li*, vsip_scalar_li , vsip_scalar_li , vsip_scalar_li , vsip_scalar_li , const vsip_mview_li* ) ; void vsip_mclip_si ( const vsip_mview_si*, vsip_scalar_si, vsip_scalar_si, vsip_scalar_si, vsip_scalar_si, const vsip_mview_si* ) ; void vsip_mcmagsq_d ( const vsip_cmview_d*, const vsip_mview_d* ) ; void vsip_mcmagsq_f ( const vsip_cmview_f*, const vsip_mview_f* ) ; void vsip_mcmaxmgsq_d ( const vsip_cmview_d*, const vsip_cmview_d*, const vsip_mview_d* ) ; void vsip_mcmaxmgsq_f ( const vsip_cmview_f*, const vsip_cmview_f*, const vsip_mview_f* ) ; void vsip_mcminmgsq_d ( const vsip_cmview_d*, const vsip_cmview_d*, const vsip_mview_d* ) ; void vsip_mcminmgsq_f ( const vsip_cmview_f*, const vsip_cmview_f*, const vsip_mview_f* ) ; void vsip_mcopy_bl_bl ( const vsip_mview_bl*, const vsip_mview_bl* ) ; void vsip_mcopy_bl_d ( const vsip_mview_bl*, const vsip_mview_d* ) ; void vsip_mcopy_bl_f ( const vsip_mview_bl*, const vsip_mview_f* ) ; void vsip_mcopy_d_bl ( const vsip_mview_d*, const vsip_mview_bl* ) ; void vsip_mcopy_d_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mcopy_d_f ( const vsip_mview_d*, const vsip_mview_f* ) ; void vsip_mcopy_d_i ( const vsip_mview_d*, const vsip_mview_i* ) ; void vsip_mcopy_d_li ( const vsip_mview_d*, const vsip_mview_li* ) ; void vsip_mcopy_d_uc ( const vsip_mview_d*, const vsip_mview_uc* ) ; void vsip_mcopy_f_bl ( const vsip_mview_f*, const vsip_mview_bl* ) ; void vsip_mcopy_f_d ( const vsip_mview_f*, const vsip_mview_d* ) ; void vsip_mcopy_f_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mcopy_f_i ( const vsip_mview_f*, const vsip_mview_i* ) ; void vsip_mcopy_f_li ( const vsip_mview_f*, const vsip_mview_li* ) ; void vsip_mcopy_f_uc ( const vsip_mview_f*, const vsip_mview_uc* ) ; void vsip_mcopy_i_f ( const vsip_mview_i*, const vsip_mview_f* ) ; void vsip_mcopy_i_i ( const vsip_mview_i*, const vsip_mview_i* ) ; void vsip_mcopy_i_li ( const vsip_mview_i*, const vsip_mview_li* ) ; void vsip_mcopy_li_f ( const vsip_mview_li*, const vsip_mview_f* ) ; void vsip_mcopy_li_li ( const vsip_mview_li*, const vsip_mview_li* ) ; void vsip_mcopy_si_f ( const vsip_mview_si*, const vsip_mview_f* ) ; void vsip_mcopyfrom_user_d ( vsip_scalar_d* const, vsip_major, const vsip_mview_d* ) ; void vsip_mcopyfrom_user_f ( vsip_scalar_f* const, vsip_major, const vsip_mview_f* ) ; void vsip_mcopyto_user_d ( const vsip_mview_d*, vsip_major, vsip_scalar_d* const ) ; void vsip_mcopyto_user_f ( const vsip_mview_f*, vsip_major, vsip_scalar_f* const ) ; void vsip_mcos_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mcos_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mcosh_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mcosh_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mcumsum_d ( const vsip_mview_d*, vsip_major, const vsip_mview_d* ) ; void vsip_mcumsum_f ( const vsip_mview_f*, vsip_major, const vsip_mview_f* ) ; void vsip_mcumsum_i ( const vsip_mview_i*, vsip_major, const vsip_mview_i* ) ; void vsip_mcumsum_li ( const vsip_mview_li*, vsip_major, const vsip_mview_li* ) ; void vsip_mcumsum_si ( const vsip_mview_si*, vsip_major, const vsip_mview_si* ) ; void vsip_mdiv_d ( const vsip_mview_d*, const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mdiv_f ( const vsip_mview_f*, const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_meuler_d ( const vsip_mview_d*, const vsip_cmview_d* ) ; void vsip_meuler_f ( const vsip_mview_f*, const vsip_cmview_f* ) ; void vsip_mexp10_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mexp10_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mexp_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mexp_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mexpoavg_d ( vsip_scalar_d, const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mexpoavg_f ( vsip_scalar_f, const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mfill_d ( vsip_scalar_d, const vsip_mview_d* ) ; void vsip_mfill_f ( vsip_scalar_f, const vsip_mview_f* ) ; void vsip_mfill_i ( vsip_scalar_i, const vsip_mview_i* ) ; void vsip_mfill_li ( vsip_scalar_li , const vsip_mview_li* ) ; void vsip_mfill_si ( vsip_scalar_si, const vsip_mview_si* ) ; void vsip_mfill_uc ( vsip_scalar_uc, const vsip_mview_uc* ) ; void vsip_mgather_d ( const vsip_mview_d*, const vsip_vview_mi*, const vsip_vview_d* ) ; void vsip_mgather_f ( const vsip_mview_f*, const vsip_vview_mi*, const vsip_vview_f* ) ; void vsip_mgetattrib_bl ( const vsip_mview_bl*, vsip_mattr_bl* ) ; void vsip_mgetattrib_d ( const vsip_mview_d*, vsip_mattr_d* ) ; void vsip_mgetattrib_f ( const vsip_mview_f*, vsip_mattr_f* ) ; void vsip_mgetattrib_i ( const vsip_mview_i*, vsip_mattr_i* ) ; void vsip_mgetattrib_li ( const vsip_mview_li*, vsip_mattr_li* ) ; void vsip_mgetattrib_si ( const vsip_mview_si*, vsip_mattr_si* ) ; void vsip_mgetattrib_uc ( const vsip_mview_uc*, vsip_mattr_uc* ) ; void vsip_mhisto_d ( const vsip_mview_d*, vsip_scalar_d, vsip_scalar_d, vsip_hist_opt, const vsip_vview_d* ) ; void vsip_mhisto_f ( const vsip_mview_f*, vsip_scalar_f, vsip_scalar_f, vsip_hist_opt, const vsip_vview_f* ) ; void vsip_mhisto_i ( const vsip_mview_i*, vsip_scalar_i, vsip_scalar_i, vsip_hist_opt, const vsip_vview_i* ) ; void vsip_mhisto_li ( const vsip_mview_li*, vsip_scalar_li , vsip_scalar_li , vsip_hist_opt, const vsip_vview_li* ) ; void vsip_mhisto_si ( const vsip_mview_si*, vsip_scalar_si, vsip_scalar_si, vsip_hist_opt, const vsip_vview_si* ) ; void vsip_mhypot_d ( const vsip_mview_d*, const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mhypot_f ( const vsip_mview_f*, const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_minterp_linear_f ( const vsip_vview_f *, const vsip_mview_f *, vsip_major, const vsip_vview_f *, const vsip_mview_f * ) ; void vsip_minterp_nearest_f ( const vsip_vview_f *, const vsip_mview_f *, vsip_major, const vsip_vview_f *, const vsip_mview_f * ) ; void vsip_minterp_spline_d ( const vsip_vview_d *, const vsip_mview_d *, vsip_spline_d *, vsip_major, const vsip_vview_d *, const vsip_mview_d * ) ; void vsip_minterp_spline_f ( const vsip_vview_f *, const vsip_mview_f *, vsip_spline_f *, vsip_major, const vsip_vview_f *, const vsip_mview_f * ) ; void vsip_minvclip_d ( const vsip_mview_d*, vsip_scalar_d, vsip_scalar_d, vsip_scalar_d, vsip_scalar_d, vsip_scalar_d, const vsip_mview_d* ) ; void vsip_minvclip_f ( const vsip_mview_f*, vsip_scalar_f, vsip_scalar_f, vsip_scalar_f, vsip_scalar_f, vsip_scalar_f, const vsip_mview_f* ) ; void vsip_mkron_d ( vsip_scalar_d, const vsip_mview_d *, const vsip_mview_d *, const vsip_mview_d * ) ; void vsip_mkron_f ( vsip_scalar_f, const vsip_mview_f *, const vsip_mview_f *, const vsip_mview_f * ) ; void vsip_mleq_d ( const vsip_mview_d*, const vsip_mview_d*, const vsip_mview_bl* ) ; void vsip_mleq_f ( const vsip_mview_f*, const vsip_mview_f*, const vsip_mview_bl* ) ; void vsip_mlge_d ( const vsip_mview_d*, const vsip_mview_d*, const vsip_mview_bl* ) ; void vsip_mlge_f ( const vsip_mview_f*, const vsip_mview_f*, const vsip_mview_bl* ) ; void vsip_mlgt_d ( const vsip_mview_d*, const vsip_mview_d*, const vsip_mview_bl* ) ; void vsip_mlgt_f ( const vsip_mview_f*, const vsip_mview_f*, const vsip_mview_bl* ) ; void vsip_mlle_d ( const vsip_mview_d*, const vsip_mview_d*, const vsip_mview_bl* ) ; void vsip_mlle_f ( const vsip_mview_f*, const vsip_mview_f*, const vsip_mview_bl* ) ; void vsip_mllt_d ( const vsip_mview_d*, const vsip_mview_d*, const vsip_mview_bl* ) ; void vsip_mllt_f ( const vsip_mview_f*, const vsip_mview_f*, const vsip_mview_bl* ) ; void vsip_mlne_d ( const vsip_mview_d*, const vsip_mview_d*, const vsip_mview_bl* ) ; void vsip_mlne_f ( const vsip_mview_f*, const vsip_mview_f*, const vsip_mview_bl* ) ; void vsip_mlog10_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mlog10_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mlog_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mlog_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mmag_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mmag_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mmax_d ( const vsip_mview_d*, const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mmax_f ( const vsip_mview_f*, const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mmaxmg_d ( const vsip_mview_d*, const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mmaxmg_f ( const vsip_mview_f*, const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mmin_d ( const vsip_mview_d*, const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mmin_f ( const vsip_mview_f*, const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mminmg_d ( const vsip_mview_d*, const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mminmg_f ( const vsip_mview_f*, const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mmul_d ( const vsip_mview_d*, const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mmul_f ( const vsip_mview_f*, const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mneg_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mneg_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mpermute_d ( const vsip_mview_d*, const vsip_permute*, const vsip_mview_d* ) ; void vsip_mpermute_f ( const vsip_mview_f*, const vsip_permute*, const vsip_mview_f* ) ; void vsip_mpermute_once_d ( const vsip_mview_d*, vsip_major, const vsip_vview_vi*, const vsip_mview_d* ) ; void vsip_mpermute_once_f ( const vsip_mview_f*, vsip_major, const vsip_vview_vi*, const vsip_mview_f* ) ; void vsip_cmpermute_once_d ( const vsip_cmview_d*, vsip_major, const vsip_vview_vi*, const vsip_cmview_d* ) ; void vsip_cmpermute_once_f ( const vsip_cmview_f*, vsip_major, const vsip_vview_vi*, const vsip_cmview_f* ) ; void vsip_mprod3_d ( const vsip_mview_d *, const vsip_mview_d *, const vsip_mview_d * ) ; void vsip_mprod3_f ( const vsip_mview_f *, const vsip_mview_f *, const vsip_mview_f * ) ; void vsip_mprod4_d ( const vsip_mview_d *, const vsip_mview_d *, const vsip_mview_d * ) ; void vsip_mprod4_f ( const vsip_mview_f *, const vsip_mview_f *, const vsip_mview_f * ) ; void vsip_mprod_d ( const vsip_mview_d *, const vsip_mview_d *, const vsip_mview_d * ) ; void vsip_mprod_f ( const vsip_mview_f *, const vsip_mview_f *, const vsip_mview_f * ) ; void vsip_mprodt_d ( const vsip_mview_d *, const vsip_mview_d *, const vsip_mview_d * ) ; void vsip_mprodt_f ( const vsip_mview_f *, const vsip_mview_f *, const vsip_mview_f * ) ; void vsip_mput_bl ( const vsip_mview_bl*, vsip_index, vsip_index, vsip_scalar_bl ) ; void vsip_mput_d ( const vsip_mview_d*, vsip_index, vsip_index, vsip_scalar_d ) ; void vsip_mput_f ( const vsip_mview_f*, vsip_index, vsip_index, vsip_scalar_f ) ; void vsip_mput_i ( const vsip_mview_i*, vsip_index, vsip_index, vsip_scalar_i ) ; void vsip_mput_li ( const vsip_mview_li*, vsip_index, vsip_index, vsip_scalar_li ) ; void vsip_mput_si ( const vsip_mview_si*, vsip_index, vsip_index, vsip_scalar_si ) ; void vsip_mput_uc ( const vsip_mview_uc*, vsip_index, vsip_index, vsip_scalar_uc ) ; void vsip_mrecip_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mrecip_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mrsqrt_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mrsqrt_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mscatter_d ( const vsip_vview_d*, const vsip_mview_d*, const vsip_vview_mi* ) ; void vsip_mscatter_f ( const vsip_vview_f*, const vsip_mview_f*, const vsip_vview_mi* ) ; void vsip_msdiv_d ( const vsip_mview_d*, vsip_scalar_d, const vsip_mview_d* ) ; void vsip_msdiv_f ( const vsip_mview_f*, vsip_scalar_f, const vsip_mview_f* ) ; void vsip_msin_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_msin_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_msinh_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_msinh_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_msq_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_msq_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_msqrt_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_msqrt_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_msub_d ( const vsip_mview_d*, const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_msub_f ( const vsip_mview_f*, const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_msub_i ( const vsip_mview_i*, const vsip_mview_i*, const vsip_mview_i* ) ; void vsip_msub_li ( const vsip_mview_li*, const vsip_mview_li*, const vsip_mview_li* ) ; void vsip_msub_si ( const vsip_mview_si*, const vsip_mview_si*, const vsip_mview_si* ) ; void vsip_mswap_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mswap_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mtan_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mtan_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mtanh_d ( const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_mtanh_f ( const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_mtrans_d ( const vsip_mview_d *, const vsip_mview_d * ) ; void vsip_mtrans_f ( const vsip_mview_f *, const vsip_mview_f * ) ; void vsip_mvprod3_d ( const vsip_mview_d *, const vsip_vview_d *, const vsip_vview_d * ) ; void vsip_mvprod3_f ( const vsip_mview_f *, const vsip_vview_f *, const vsip_vview_f * ) ; void vsip_mvprod4_d ( const vsip_mview_d *, const vsip_vview_d *, const vsip_vview_d * ) ; void vsip_mvprod4_f ( const vsip_mview_f *, const vsip_vview_f *, const vsip_vview_f * ) ; void vsip_mvprod_d ( const vsip_mview_d *, const vsip_vview_d *, const vsip_vview_d * ) ; void vsip_mvprod_f ( const vsip_mview_f *, const vsip_vview_f *, const vsip_vview_f * ) ; void vsip_permute_destroy ( vsip_permute* ) ; void vsip_polar_d ( vsip_cscalar_d, vsip_scalar_d*, vsip_scalar_d* ) ; void vsip_polar_f ( vsip_cscalar_f a, vsip_scalar_f*, vsip_scalar_f* ) ; void vsip_qrd_getattr_d ( const vsip_qr_d *, vsip_qr_attr_d * ) ; void vsip_qrd_getattr_f ( const vsip_qr_f *, vsip_qr_attr_f * ) ; void vsip_rcfftmop_d ( const vsip_fftm_d*, const vsip_mview_d*, const vsip_cmview_d* ) ; void vsip_rcfftmop_f ( const vsip_fftm_f*, const vsip_mview_f*, const vsip_cmview_f* ) ; void vsip_rcfftop_d ( const vsip_fft_d*, const vsip_vview_d*, const vsip_cvview_d* ) ; void vsip_rcfftop_f ( const vsip_fft_f*, const vsip_vview_f*, const vsip_cvview_f* ) ; void vsip_rcmadd_d ( const vsip_mview_d*, const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_rcmadd_f ( const vsip_mview_f*, const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_rcmdiv_d ( const vsip_mview_d*, const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_rcmdiv_f ( const vsip_mview_f*, const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_rcmmul_d ( const vsip_mview_d*, const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_rcmmul_f ( const vsip_mview_f*, const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_rcmsub_d ( const vsip_mview_d*, const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_rcmsub_f ( const vsip_mview_f*, const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_rcvadd_d ( const vsip_vview_d*, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_rcvadd_f ( const vsip_vview_f*, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_rcvdiv_d ( const vsip_vview_d*, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_rcvdiv_f ( const vsip_vview_f*, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_rcvmul_d ( const vsip_vview_d*, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_rcvmul_f ( const vsip_vview_f*, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_rcvsub_d ( const vsip_vview_d*, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_rcvsub_f ( const vsip_vview_f*, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_rscmadd_d ( vsip_scalar_d, const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_rscmadd_f ( vsip_scalar_f, const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_rscmdiv_d ( vsip_scalar_d, const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_rscmdiv_f ( vsip_scalar_f, const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_rscmmul_d ( vsip_scalar_d, const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_rscmmul_f ( vsip_scalar_f, const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_rscmsub_d ( vsip_scalar_d, const vsip_cmview_d*, const vsip_cmview_d* ) ; void vsip_rscmsub_f ( vsip_scalar_f, const vsip_cmview_f*, const vsip_cmview_f* ) ; void vsip_rscvadd_d ( vsip_scalar_d, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_rscvadd_f ( vsip_scalar_f, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_rscvdiv_d ( vsip_scalar_d, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_rscvdiv_f ( vsip_scalar_f, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_rscvmul_d ( vsip_scalar_d, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_rscvmul_f ( vsip_scalar_f, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_rscvsub_d ( vsip_scalar_d, const vsip_cvview_d*, const vsip_cvview_d* ) ; void vsip_rscvsub_f ( vsip_scalar_f, const vsip_cvview_f*, const vsip_cvview_f* ) ; void vsip_rvcmmul_d ( const vsip_vview_d*, const vsip_cmview_d*, vsip_major, const vsip_cmview_d* ) ; void vsip_rvcmmul_f ( const vsip_vview_f*, const vsip_cmview_f*, vsip_major, const vsip_cmview_f* ) ; void vsip_smadd_d ( vsip_scalar_d, const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_smadd_f ( vsip_scalar_f, const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_smdiv_d ( vsip_scalar_d, const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_smdiv_f ( vsip_scalar_f, const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_smmul_d ( vsip_scalar_d, const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_smmul_f ( vsip_scalar_f, const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_smsub_d ( vsip_scalar_d, const vsip_mview_d*, const vsip_mview_d* ) ; void vsip_smsub_f ( vsip_scalar_f, const vsip_mview_f*, const vsip_mview_f* ) ; void vsip_smsub_i ( vsip_scalar_i, const vsip_mview_i*, const vsip_mview_i* ) ; void vsip_smsub_li ( vsip_scalar_li , const vsip_mview_li*, const vsip_mview_li* ) ; void vsip_smsub_si ( vsip_scalar_si, const vsip_mview_si*, const vsip_mview_si* ) ; void vsip_smsub_si ( vsip_scalar_si, const vsip_mview_si*, const vsip_mview_si* ) ; void vsip_spline_destroy_d ( vsip_spline_d * ) ; void vsip_spline_destroy_f ( vsip_spline_f * ) ; void vsip_svadd_d ( vsip_scalar_d, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_svadd_f ( vsip_scalar_f, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_svadd_i ( vsip_scalar_i, const vsip_vview_i*, const vsip_vview_i* ) ; void vsip_svadd_li ( vsip_scalar_li , const vsip_vview_li*, const vsip_vview_li* ) ; void vsip_svadd_si ( vsip_scalar_si, const vsip_vview_si*, const vsip_vview_si* ) ; void vsip_svadd_uc ( vsip_scalar_uc, const vsip_vview_uc*, const vsip_vview_uc* ) ; void vsip_svadd_vi ( vsip_scalar_vi, const vsip_vview_vi*, const vsip_vview_vi* ) ; void vsip_svdiv_d ( vsip_scalar_d, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_svdiv_f ( vsip_scalar_f, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_svmul_d ( vsip_scalar_d, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_svmul_f ( vsip_scalar_f, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_svmul_i ( vsip_scalar_i, const vsip_vview_i*, const vsip_vview_i* ) ; void vsip_svmul_li ( vsip_scalar_li , const vsip_vview_li*, const vsip_vview_li* ) ; void vsip_svmul_si ( vsip_scalar_si, const vsip_vview_si*, const vsip_vview_si* ) ; void vsip_svmul_uc ( vsip_scalar_uc, const vsip_vview_uc*, const vsip_vview_uc* ) ; void vsip_svsub_d ( vsip_scalar_d, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_svsub_f ( vsip_scalar_f, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_svsub_i ( vsip_scalar_i, const vsip_vview_i*, const vsip_vview_i* ) ; void vsip_svsub_li ( vsip_scalar_li , const vsip_vview_li*, const vsip_vview_li* ) ; void vsip_svsub_si ( vsip_scalar_si, const vsip_vview_si*, const vsip_vview_si* ) ; void vsip_svsub_uc ( vsip_scalar_uc, const vsip_vview_uc*, const vsip_vview_uc* ) ; void vsip_svsub_vi ( vsip_scalar_vi, const vsip_vview_vi*, const vsip_vview_vi* ) ; void vsip_talldestroy_d ( vsip_tview_d* ) ; void vsip_talldestroy_f ( vsip_tview_f* ) ; void vsip_talldestroy_i ( vsip_tview_i* ) ; void vsip_talldestroy_li ( vsip_tview_li* ) ; void vsip_talldestroy_si ( vsip_tview_si* ) ; void vsip_talldestroy_uc ( vsip_tview_uc* ) ; void vsip_tgetattrib_d ( const vsip_tview_d*, vsip_tattr_d* ) ; void vsip_tgetattrib_f ( const vsip_tview_f*, vsip_tattr_f* ) ; void vsip_tgetattrib_i ( const vsip_tview_i*, vsip_tattr_i* ) ; void vsip_tgetattrib_li ( const vsip_tview_li*, vsip_tattr_li* ) ; void vsip_tgetattrib_si ( const vsip_tview_si*, vsip_tattr_si* ) ; void vsip_tgetattrib_uc ( const vsip_tview_uc*, vsip_tattr_uc* ) ; void vsip_tput_d ( const vsip_tview_d*, vsip_index, vsip_index, vsip_index, vsip_scalar_d ) ; void vsip_tput_f ( const vsip_tview_f*, vsip_index, vsip_index, vsip_index, vsip_scalar_f ) ; void vsip_tput_i ( const vsip_tview_i*, vsip_index, vsip_index, vsip_index, vsip_scalar_i ) ; void vsip_tput_li ( const vsip_tview_li*, vsip_index, vsip_index, vsip_index, vsip_scalar_li ) ; void vsip_tput_si ( const vsip_tview_si*, vsip_index, vsip_index, vsip_index, vsip_scalar_si ) ; void vsip_tput_uc ( const vsip_tview_uc*, vsip_index, vsip_index, vsip_index, vsip_scalar_uc ) ; void vsip_tputattrib_d ( vsip_tview_d*, const vsip_tattr_d* ) ; void vsip_tputattrib_f ( vsip_tview_f*, const vsip_tattr_f* ) ; void vsip_tputattrib_i ( vsip_tview_i*, const vsip_tattr_i* ) ; void vsip_tputattrib_li ( vsip_tview_li*, const vsip_tattr_li* ) ; void vsip_tputattrib_si ( vsip_tview_si*, const vsip_tattr_si* ) ; void vsip_tputattrib_uc ( vsip_tview_uc*, const vsip_tattr_uc* ) ; void vsip_vacos_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vacos_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vadd_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vadd_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vadd_i ( const vsip_vview_i*, const vsip_vview_i*, const vsip_vview_i* ) ; void vsip_vadd_li ( const vsip_vview_li*, const vsip_vview_li*, const vsip_vview_li* ) ; void vsip_vadd_si ( const vsip_vview_si*, const vsip_vview_si*, const vsip_vview_si* ) ; void vsip_vadd_uc ( const vsip_vview_uc*, const vsip_vview_uc*, const vsip_vview_uc* ) ; void vsip_vadd_vi ( const vsip_vview_vi*, const vsip_vview_vi*, const vsip_vview_vi* ) ; void vsip_valldestroy_bl ( vsip_vview_bl* ) ; void vsip_valldestroy_d ( vsip_vview_d* ) ; void vsip_valldestroy_f ( vsip_vview_f* ) ; void vsip_valldestroy_i ( vsip_vview_i* ) ; void vsip_valldestroy_li ( vsip_vview_li* ) ; void vsip_valldestroy_mi ( vsip_vview_mi* ) ; void vsip_valldestroy_si ( vsip_vview_si* ) ; void vsip_valldestroy_uc ( vsip_vview_uc* ) ; void vsip_valldestroy_vi ( vsip_vview_vi* ) ; void vsip_vam_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vam_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vand_bl ( const vsip_vview_bl*, const vsip_vview_bl*, const vsip_vview_bl* ) ; void vsip_vand_i ( const vsip_vview_i*, const vsip_vview_i*, const vsip_vview_i* ) ; void vsip_vand_li ( const vsip_vview_li*, const vsip_vview_li*, const vsip_vview_li* ) ; void vsip_vand_si ( const vsip_vview_si*, const vsip_vview_si*, const vsip_vview_si* ) ; void vsip_vand_uc ( const vsip_vview_uc*, const vsip_vview_uc*, const vsip_vview_uc* ) ; void vsip_varg_d ( const vsip_cvview_d*, const vsip_vview_d* ) ; void vsip_vceil_d_d(const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vceil_d_i(const vsip_vview_d*, const vsip_vview_i* ) ; void vsip_vceil_d_li(const vsip_vview_d*, const vsip_vview_li* ) ; void vsip_vfloor_d_d(const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vfloor_d_i(const vsip_vview_d*, const vsip_vview_i* ) ; void vsip_vfloor_d_li(const vsip_vview_d*, const vsip_vview_li* ) ; void vsip_varg_f ( const vsip_cvview_f*, const vsip_vview_f* ) ; void vsip_vceil_f_f(const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vceil_f_i(const vsip_vview_f*, const vsip_vview_i* ) ; void vsip_vceil_f_li(const vsip_vview_f*, const vsip_vview_li* ) ; void vsip_vfloor_f_f(const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vfloor_f_i(const vsip_vview_f*, const vsip_vview_i* ) ; void vsip_vfloor_f_li(const vsip_vview_f*, const vsip_vview_li* ) ; void vsip_vasin_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vasin_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vatan2_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vatan2_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vatan_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vatan_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vclip_d ( const vsip_vview_d*, vsip_scalar_d, vsip_scalar_d, vsip_scalar_d, vsip_scalar_d, const vsip_vview_d* ) ; void vsip_vclip_f ( const vsip_vview_f*, vsip_scalar_f, vsip_scalar_f, vsip_scalar_f, vsip_scalar_f, const vsip_vview_f* ) ; void vsip_vclip_i ( const vsip_vview_i*, vsip_scalar_i, vsip_scalar_i, vsip_scalar_i, vsip_scalar_i, const vsip_vview_i* ) ; void vsip_vclip_li ( const vsip_vview_li*, vsip_scalar_li , vsip_scalar_li , vsip_scalar_li , vsip_scalar_li , const vsip_vview_li* ) ; void vsip_vclip_si ( const vsip_vview_si*, vsip_scalar_si, vsip_scalar_si, vsip_scalar_si, vsip_scalar_si, const vsip_vview_si* ) ; void vsip_vclip_uc ( const vsip_vview_uc*, vsip_scalar_uc, vsip_scalar_uc, vsip_scalar_uc, vsip_scalar_uc, const vsip_vview_uc* ) ; void vsip_vcmagsq_d ( const vsip_cvview_d*, const vsip_vview_d* ) ; void vsip_vcmagsq_f ( const vsip_cvview_f*, const vsip_vview_f* ) ; void vsip_vcmaxmgsq_d ( const vsip_cvview_d*, const vsip_cvview_d*, const vsip_vview_d* ) ; void vsip_vcmaxmgsq_f ( const vsip_cvview_f*, const vsip_cvview_f*, const vsip_vview_f* ) ; void vsip_vcminmgsq_d ( const vsip_cvview_d*, const vsip_cvview_d*, const vsip_vview_d* ) ; void vsip_vcminmgsq_f ( const vsip_cvview_f*, const vsip_cvview_f*, const vsip_vview_f* ) ; void vsip_vcmplx_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_cvview_d* ) ; void vsip_vcmplx_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_cvview_f* ) ; void vsip_mcmplx_d ( const vsip_mview_d*, const vsip_mview_d*, const vsip_cmview_d* ) ; void vsip_mcmplx_f ( const vsip_mview_f*, const vsip_mview_f*, const vsip_cmview_f* ) ; void vsip_vcopy_bl_bl ( const vsip_vview_bl*, const vsip_vview_bl* ) ; void vsip_vcopy_bl_d ( const vsip_vview_bl*, const vsip_vview_d* ) ; void vsip_vcopy_bl_f ( const vsip_vview_bl*, const vsip_vview_f* ) ; void vsip_vcopy_d_bl ( const vsip_vview_d*, const vsip_vview_bl* ) ; void vsip_vcopy_d_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vcopy_d_f ( const vsip_vview_d*, const vsip_vview_f* ) ; void vsip_vcopy_d_i ( const vsip_vview_d*, const vsip_vview_i* ) ; void vsip_vcopy_d_li ( const vsip_vview_d*, const vsip_vview_li* ) ; void vsip_vcopy_d_si ( const vsip_vview_d*, const vsip_vview_si* ) ; void vsip_vcopy_d_uc ( const vsip_vview_d*, const vsip_vview_uc* ) ; void vsip_vcopy_d_vi ( const vsip_vview_d*, const vsip_vview_vi* ) ; void vsip_vcopy_f_bl ( const vsip_vview_f*, const vsip_vview_bl* ) ; void vsip_vcopy_f_d ( const vsip_vview_f*, const vsip_vview_d* ) ; void vsip_vcopy_f_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vcopy_f_i ( const vsip_vview_f*, const vsip_vview_i* ) ; void vsip_vcopy_f_li ( const vsip_vview_f*, const vsip_vview_li* ) ; void vsip_vcopy_f_si ( const vsip_vview_f*, const vsip_vview_si* ) ; void vsip_vcopy_f_uc ( const vsip_vview_f*, const vsip_vview_uc* ) ; void vsip_vcopy_f_vi ( const vsip_vview_f*, const vsip_vview_vi* ) ; void vsip_vcopy_i_d ( const vsip_vview_i*, const vsip_vview_d* ) ; void vsip_vcopy_i_f ( const vsip_vview_i*, const vsip_vview_f* ) ; void vsip_vcopy_i_i ( const vsip_vview_i*, const vsip_vview_i* ) ; void vsip_vcopy_i_li ( const vsip_vview_i*, const vsip_vview_li* ) ; void vsip_vcopy_li_li ( const vsip_vview_li*, const vsip_vview_li* ) ; void vsip_vcopy_i_uc ( const vsip_vview_i*, const vsip_vview_uc* ) ; void vsip_vcopy_i_vi ( const vsip_vview_i*, const vsip_vview_vi* ) ; void vsip_vcopy_mi_mi ( const vsip_vview_mi*, const vsip_vview_mi* ) ; void vsip_vcopy_si_d ( const vsip_vview_si*, const vsip_vview_d* ) ; void vsip_vcopy_si_f ( const vsip_vview_si*, const vsip_vview_f* ) ; void vsip_vcopy_si_si ( const vsip_vview_si*, const vsip_vview_si* ) ; void vsip_vcopy_vi_i ( const vsip_vview_vi*, const vsip_vview_i* ) ; void vsip_vcopy_vi_li ( const vsip_vview_vi*, const vsip_vview_li* ) ; void vsip_vcopy_vi_vi ( const vsip_vview_vi*, const vsip_vview_vi* ) ; void vsip_vcopy_vi_d ( const vsip_vview_vi*, const vsip_vview_d* ) ; void vsip_vcopy_vi_f ( const vsip_vview_vi*, const vsip_vview_f* ) ; void vsip_vcopyfrom_user_d ( vsip_scalar_d* const, const vsip_vview_d* ) ; void vsip_vcopyfrom_user_f ( vsip_scalar_f* const, const vsip_vview_f* ) ; void vsip_vcopyfrom_user_i ( vsip_scalar_i* const, const vsip_vview_i* ) ; void vsip_vcopyfrom_user_li ( vsip_scalar_li * const, const vsip_vview_li* ) ; void vsip_vcopyfrom_user_si ( vsip_scalar_si* const, const vsip_vview_si* ) ; void vsip_vcopyfrom_user_vi ( vsip_scalar_vi* const, const vsip_vview_vi* ) ; void vsip_vcopyto_user_d ( const vsip_vview_d*, vsip_scalar_d* const ) ; void vsip_vcopyto_user_f ( const vsip_vview_f*, vsip_scalar_f* const ) ; void vsip_vcopyto_user_i ( const vsip_vview_i*, vsip_scalar_i* const ) ; void vsip_vcopyto_user_li ( const vsip_vview_li*, vsip_scalar_li * const ) ; void vsip_vcopyto_user_si ( const vsip_vview_si*, vsip_scalar_si* const ) ; void vsip_vcopyto_user_vi ( const vsip_vview_vi*, vsip_scalar_vi* const ) ; void vsip_vcos_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vcos_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vcosh_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vcosh_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vcumsum_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vcumsum_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vcumsum_i ( const vsip_vview_i*, const vsip_vview_i* ) ; void vsip_vcumsum_li ( const vsip_vview_li*, const vsip_vview_li* ) ; void vsip_vcumsum_si ( const vsip_vview_si*, const vsip_vview_si* ) ; void vsip_vdiv_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vdiv_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_veuler_d ( const vsip_vview_d*, const vsip_cvview_d* ) ; void vsip_veuler_f ( const vsip_vview_f*, const vsip_cvview_f* ) ; void vsip_vexp10_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vexp10_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vexp_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vexp_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vexpoavg_d ( vsip_scalar_d, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vexpoavg_f ( vsip_scalar_f, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vfill_d ( vsip_scalar_d, const vsip_vview_d* ) ; void vsip_vfill_f ( vsip_scalar_f, const vsip_vview_f* ) ; void vsip_vfill_i ( vsip_scalar_i, const vsip_vview_i* ) ; void vsip_vfill_li ( vsip_scalar_li, const vsip_vview_li* ) ; void vsip_vfill_si ( vsip_scalar_si, const vsip_vview_si* ) ; void vsip_vfill_uc ( vsip_scalar_uc, const vsip_vview_uc* ) ; void vsip_vfill_vi ( vsip_scalar_vi, const vsip_vview_vi* ) ; void vsip_vgather_d ( const vsip_vview_d*, const vsip_vview_vi*, const vsip_vview_d* ) ; void vsip_vgather_f ( const vsip_vview_f*, const vsip_vview_vi*, const vsip_vview_f* ) ; void vsip_vgather_i ( const vsip_vview_i*, const vsip_vview_vi*, const vsip_vview_i* ) ; void vsip_vgather_li ( const vsip_vview_li*, const vsip_vview_vi*, const vsip_vview_li* ) ; void vsip_vgather_si ( const vsip_vview_si*, const vsip_vview_vi*, const vsip_vview_si* ) ; void vsip_vgather_uc ( const vsip_vview_uc*, const vsip_vview_vi*, const vsip_vview_uc* ) ; void vsip_vgetattrib_d ( const vsip_vview_d*, vsip_vattr_d* ) ; void vsip_vgetattrib_f ( const vsip_vview_f*, vsip_vattr_f* ) ; void vsip_vgetattrib_i ( const vsip_vview_i*, vsip_vattr_i* ) ; void vsip_vgetattrib_li ( const vsip_vview_li*, vsip_vattr_li* ) ; void vsip_vgetattrib_mi ( const vsip_vview_mi*, vsip_vattr_mi* ) ; void vsip_vgetattrib_si ( const vsip_vview_si*, vsip_vattr_si* ) ; void vsip_vgetattrib_uc ( const vsip_vview_uc*, vsip_vattr_uc* ) ; void vsip_vgetattrib_vi ( const vsip_vview_vi*, vsip_vattr_vi* ) ; void vsip_vhisto_d ( const vsip_vview_d*, vsip_scalar_d, vsip_scalar_d, vsip_hist_opt, const vsip_vview_d* ) ; void vsip_vhisto_f ( const vsip_vview_f*, vsip_scalar_f min, vsip_scalar_f max, vsip_hist_opt opt, const vsip_vview_f* ) ; void vsip_vhisto_i ( const vsip_vview_i*, vsip_scalar_i, vsip_scalar_i, vsip_hist_opt, const vsip_vview_i* ) ; void vsip_vhisto_li ( const vsip_vview_li*, vsip_scalar_li, vsip_scalar_li, vsip_hist_opt, const vsip_vview_li* ) ; void vsip_vhisto_si ( const vsip_vview_si*, vsip_scalar_si, vsip_scalar_si, vsip_hist_opt, const vsip_vview_si* ) ; void vsip_vhypot_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vhypot_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vimag_d ( const vsip_cvview_d*, const vsip_vview_d* ) ; void vsip_vimag_f ( const vsip_cvview_f*, const vsip_vview_f* ) ; void vsip_mimag_d ( const vsip_cmview_d*, const vsip_mview_d* ) ; void vsip_mimag_f ( const vsip_cmview_f*, const vsip_mview_f* ) ; void vsip_vinterp_linear_f ( const vsip_vview_f *, const vsip_vview_f *, const vsip_vview_f *, const vsip_vview_f * ) ; void vsip_vinterp_nearest_f ( const vsip_vview_f *, const vsip_vview_f *, const vsip_vview_f *, const vsip_vview_f * ) ; void vsip_vinterp_spline_d ( const vsip_vview_d *, const vsip_vview_d *, vsip_spline_d *, const vsip_vview_d *, const vsip_vview_d * ) ; void vsip_vinterp_spline_f ( const vsip_vview_f *, const vsip_vview_f *, vsip_spline_f *, const vsip_vview_f *, const vsip_vview_f * ) ; void vsip_vinvclip_d ( const vsip_vview_d*, vsip_scalar_d, vsip_scalar_d, vsip_scalar_d, vsip_scalar_d, vsip_scalar_d, const vsip_vview_d* ) ; void vsip_vinvclip_f ( const vsip_vview_f*, vsip_scalar_f, vsip_scalar_f, vsip_scalar_f, vsip_scalar_f, vsip_scalar_f, const vsip_vview_f* ) ; void vsip_vinvclip_i ( const vsip_vview_i*, vsip_scalar_i, vsip_scalar_i, vsip_scalar_i, vsip_scalar_i, vsip_scalar_i, const vsip_vview_i* ) ; void vsip_vinvclip_li ( const vsip_vview_li*, vsip_scalar_li, vsip_scalar_li, vsip_scalar_li, vsip_scalar_li, vsip_scalar_li, const vsip_vview_li* ) ; void vsip_vinvclip_si ( const vsip_vview_si*, vsip_scalar_si, vsip_scalar_si, vsip_scalar_si, vsip_scalar_si, vsip_scalar_si, const vsip_vview_si* ) ; void vsip_vinvclip_uc ( const vsip_vview_uc*, vsip_scalar_uc, vsip_scalar_uc, vsip_scalar_uc, vsip_scalar_uc, vsip_scalar_uc, const vsip_vview_uc* ) ; void vsip_vkron_d ( vsip_scalar_d, const vsip_vview_d *, const vsip_vview_d *, const vsip_mview_d * ) ; void vsip_vkron_f ( vsip_scalar_f, const vsip_vview_f *, const vsip_vview_f *, const vsip_mview_f * ) ; void vsip_svlne_f (vsip_scalar_f, const vsip_vview_f*, const vsip_vview_bl* ) ; void vsip_svlne_d (vsip_scalar_d, const vsip_vview_d*, const vsip_vview_bl* ) ; void vsip_svllt_f (vsip_scalar_f, const vsip_vview_f*, const vsip_vview_bl* ) ; void vsip_svllt_d (vsip_scalar_d, const vsip_vview_d*, const vsip_vview_bl* ) ; void vsip_svlle_f (vsip_scalar_f, const vsip_vview_f*, const vsip_vview_bl* ) ; void vsip_svlle_d (vsip_scalar_d, const vsip_vview_d*, const vsip_vview_bl* ) ; void vsip_svlgt_f (vsip_scalar_f, const vsip_vview_f*, const vsip_vview_bl* ) ; void vsip_svlgt_d (vsip_scalar_d, const vsip_vview_d*, const vsip_vview_bl* ) ; void vsip_svlge_f (vsip_scalar_f, const vsip_vview_f*, const vsip_vview_bl* ) ; void vsip_svlge_d (vsip_scalar_d, const vsip_vview_d*, const vsip_vview_bl* ) ; void vsip_svleq_f (vsip_scalar_f, const vsip_vview_f*, const vsip_vview_bl* ) ; void vsip_svleq_d (vsip_scalar_d, const vsip_vview_d*, const vsip_vview_bl* ) ; void vsip_vleq_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_bl* ) ; void vsip_vleq_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_bl* ) ; void vsip_vleq_i ( const vsip_vview_i*, const vsip_vview_i*, const vsip_vview_bl* ) ; void vsip_vleq_li ( const vsip_vview_li*, const vsip_vview_li*, const vsip_vview_bl* ) ; void vsip_vleq_si ( const vsip_vview_si*, const vsip_vview_si*, const vsip_vview_bl* ) ; void vsip_vleq_uc ( const vsip_vview_uc*, const vsip_vview_uc*, const vsip_vview_bl* ) ; void vsip_vlge_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_bl* ) ; void vsip_vlge_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_bl* ) ; void vsip_vlge_i ( const vsip_vview_i*, const vsip_vview_i*, const vsip_vview_bl* ) ; void vsip_vlge_li ( const vsip_vview_li*, const vsip_vview_li*, const vsip_vview_bl* ) ; void vsip_vlge_si ( const vsip_vview_si*, const vsip_vview_si*, const vsip_vview_bl* ) ; void vsip_vlge_uc ( const vsip_vview_uc*, const vsip_vview_uc*, const vsip_vview_bl* ) ; void vsip_vlgt_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_bl* ) ; void vsip_vlgt_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_bl* ) ; void vsip_vlgt_i ( const vsip_vview_i*, const vsip_vview_i*, const vsip_vview_bl* ) ; void vsip_vlgt_li ( const vsip_vview_li*, const vsip_vview_li*, const vsip_vview_bl* ) ; void vsip_vlgt_si ( const vsip_vview_si*, const vsip_vview_si*, const vsip_vview_bl* ) ; void vsip_vlgt_uc ( const vsip_vview_uc*, const vsip_vview_uc*, const vsip_vview_bl* ) ; void vsip_vlle_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_bl* ) ; void vsip_vlle_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_bl* ) ; void vsip_vlle_i ( const vsip_vview_i*, const vsip_vview_i*, const vsip_vview_bl* ) ; void vsip_vlle_li ( const vsip_vview_li*, const vsip_vview_li*, const vsip_vview_bl* ) ; void vsip_vlle_si ( const vsip_vview_si*, const vsip_vview_si*, const vsip_vview_bl* ) ; void vsip_vlle_uc ( const vsip_vview_uc*, const vsip_vview_uc*, const vsip_vview_bl* ) ; void vsip_vllt_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_bl* ) ; void vsip_vllt_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_bl* ) ; void vsip_vllt_i ( const vsip_vview_i*, const vsip_vview_i*, const vsip_vview_bl* ) ; void vsip_vllt_li ( const vsip_vview_li*, const vsip_vview_li*, const vsip_vview_bl* ) ; void vsip_vllt_si ( const vsip_vview_si*, const vsip_vview_si*, const vsip_vview_bl* ) ; void vsip_vllt_uc ( const vsip_vview_uc*, const vsip_vview_uc*, const vsip_vview_bl* ) ; void vsip_vlne_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_bl* ) ; void vsip_vlne_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_bl* ) ; void vsip_vlne_i ( const vsip_vview_i*, const vsip_vview_i*, const vsip_vview_bl* ) ; void vsip_vlne_li ( const vsip_vview_li*, const vsip_vview_li*, const vsip_vview_bl* ) ; void vsip_vlne_si ( const vsip_vview_si*, const vsip_vview_si*, const vsip_vview_bl* ) ; void vsip_vlne_uc ( const vsip_vview_uc*, const vsip_vview_uc*, const vsip_vview_bl* ) ; void vsip_vlog10_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vlog10_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vlog_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vlog_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vma_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vma_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vmag_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vmag_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vmag_i ( const vsip_vview_i*, const vsip_vview_i* ) ; void vsip_vmag_li ( const vsip_vview_li*, const vsip_vview_li* ) ; void vsip_vmag_si ( const vsip_vview_si*, const vsip_vview_si* ) ; void vsip_vmax_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vmax_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vmaxmg_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vmaxmg_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vmin_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vmin_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vminmg_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vminmg_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vmmul_d ( const vsip_vview_d*, const vsip_mview_d*, vsip_major, const vsip_mview_d* ) ; void vsip_vmmul_f ( const vsip_vview_f*, const vsip_mview_f*, vsip_major, const vsip_mview_f* ) ; void vsip_vmprod_d ( const vsip_vview_d *, const vsip_mview_d *, const vsip_vview_d * ) ; void vsip_vmprod_f ( const vsip_vview_f *, const vsip_mview_f *, const vsip_vview_f * ) ; void vsip_vmsa_d ( const vsip_vview_d*, const vsip_vview_d*, vsip_scalar_d, const vsip_vview_d* ) ; void vsip_vmsa_f ( const vsip_vview_f*, const vsip_vview_f*, vsip_scalar_f, const vsip_vview_f* ) ; void vsip_vmsb_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vmsb_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vmul_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vmul_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vmul_i ( const vsip_vview_i*, const vsip_vview_i*, const vsip_vview_i* ) ; void vsip_vmul_li ( const vsip_vview_li*, const vsip_vview_li*, const vsip_vview_li* ) ; void vsip_vmul_si ( const vsip_vview_si*, const vsip_vview_si*, const vsip_vview_si* ) ; void vsip_vmul_uc ( const vsip_vview_uc*, const vsip_vview_uc*, const vsip_vview_uc* ) ; void vsip_vneg_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vneg_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vneg_i ( const vsip_vview_i*, const vsip_vview_i* ) ; void vsip_vneg_li ( const vsip_vview_li*, const vsip_vview_li* ) ; void vsip_vneg_si ( const vsip_vview_si*, const vsip_vview_si* ) ; void vsip_vnot_bl ( const vsip_vview_bl*, const vsip_vview_bl* ) ; void vsip_vnot_i ( const vsip_vview_i*, const vsip_vview_i* ) ; void vsip_vnot_li ( const vsip_vview_li*, const vsip_vview_li* ) ; void vsip_vnot_si ( const vsip_vview_si*, const vsip_vview_si* ) ; void vsip_vnot_uc ( const vsip_vview_uc*, const vsip_vview_uc* ) ; void vsip_vor_bl ( const vsip_vview_bl*, const vsip_vview_bl*, const vsip_vview_bl* ) ; void vsip_vor_i ( const vsip_vview_i*, const vsip_vview_i*, const vsip_vview_i* ) ; void vsip_vor_li ( const vsip_vview_li*, const vsip_vview_li*, const vsip_vview_li* ) ; void vsip_vor_si ( const vsip_vview_si*, const vsip_vview_si*, const vsip_vview_si* ) ; void vsip_vor_uc ( const vsip_vview_uc*, const vsip_vview_uc*, const vsip_vview_uc* ) ; void vsip_vouter_d ( vsip_scalar_d, const vsip_vview_d*, const vsip_vview_d*, const vsip_mview_d* ) ; void vsip_vouter_f ( vsip_scalar_f, const vsip_vview_f*, const vsip_vview_f*, const vsip_mview_f* ) ; void vsip_vpolar_d ( const vsip_cvview_d*, const vsip_vview_d*, const vsip_vview_d*); void vsip_vpolar_f ( const vsip_cvview_f*, const vsip_vview_f*, const vsip_vview_f*); void vsip_mpolar_d ( const vsip_cmview_d*, const vsip_mview_d*, const vsip_mview_d*); void vsip_mpolar_f ( const vsip_cmview_f*, const vsip_mview_f*, const vsip_mview_f*); void vsip_vput_bl ( const vsip_vview_bl*, vsip_index, vsip_scalar_bl ) ; void vsip_vput_d ( const vsip_vview_d*, vsip_index, vsip_scalar_d ) ; void vsip_vput_f ( const vsip_vview_f*, vsip_index, vsip_scalar_f ) ; void vsip_vput_i ( const vsip_vview_i*, vsip_index, vsip_scalar_i ) ; void vsip_vput_li ( const vsip_vview_li*, vsip_index, vsip_scalar_li ) ; void vsip_vput_mi ( const vsip_vview_mi*, vsip_index, vsip_scalar_mi ) ; void vsip_vput_si ( const vsip_vview_si*, vsip_index, vsip_scalar_si ) ; void vsip_vput_uc ( const vsip_vview_uc*, vsip_index, vsip_scalar_uc ) ; void vsip_vput_vi ( const vsip_vview_vi*, vsip_index, vsip_scalar_vi ) ; void vsip_vramp_d ( vsip_scalar_d, vsip_scalar_d, const vsip_vview_d* ) ; void vsip_vramp_f ( vsip_scalar_f, vsip_scalar_f, const vsip_vview_f* ) ; void vsip_vramp_i ( vsip_scalar_i, vsip_scalar_i, const vsip_vview_i* ) ; void vsip_vramp_li ( vsip_scalar_li, vsip_scalar_li, const vsip_vview_li* ) ; void vsip_vramp_si ( vsip_scalar_si, vsip_scalar_si, const vsip_vview_si* ) ; void vsip_vramp_uc ( vsip_scalar_uc, vsip_scalar_uc, const vsip_vview_uc* ) ; void vsip_vramp_vi ( vsip_scalar_vi, vsip_scalar_vi, const vsip_vview_vi* ) ; void vsip_vrandn_d ( vsip_randstate*, const vsip_vview_d* ) ; void vsip_vrandn_f ( vsip_randstate*, const vsip_vview_f* ) ; void vsip_vrandu_d ( vsip_randstate*, const vsip_vview_d* ) ; void vsip_vrandu_f ( vsip_randstate*, const vsip_vview_f* ) ; void vsip_mrandn_d ( vsip_randstate*, const vsip_mview_d* ) ; void vsip_mrandn_f ( vsip_randstate*, const vsip_mview_f* ) ; void vsip_mrandu_d ( vsip_randstate*, const vsip_mview_d* ) ; void vsip_mrandu_f ( vsip_randstate*, const vsip_mview_f* ) ; void vsip_vreal_d ( const vsip_cvview_d*, const vsip_vview_d* ) ; void vsip_vreal_f ( const vsip_cvview_f*, const vsip_vview_f* ) ; void vsip_mreal_d ( const vsip_cmview_d*, const vsip_mview_d* ) ; void vsip_mreal_f ( const vsip_cmview_f*, const vsip_mview_f* ) ; void vsip_vrecip_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vrecip_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vrect_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_cvview_d* ) ; void vsip_vrect_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_cvview_f* ) ; void vsip_mrect_d ( const vsip_mview_d*, const vsip_mview_d*, const vsip_cmview_d* ) ; void vsip_mrect_f ( const vsip_mview_f*, const vsip_mview_f*, const vsip_cmview_f* ) ; void vsip_vrsqrt_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vrsqrt_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vsam_d ( const vsip_vview_d*, vsip_scalar_d, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vsam_f ( const vsip_vview_f*, vsip_scalar_f, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vsbm_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vsbm_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vscatter_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_vi* ) ; void vsip_vscatter_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_vi* ) ; void vsip_vscatter_i ( const vsip_vview_i*, const vsip_vview_i*, const vsip_vview_vi* ) ; void vsip_vscatter_li ( const vsip_vview_li*, const vsip_vview_li*, const vsip_vview_vi* ) ; void vsip_vscatter_si ( const vsip_vview_si*, const vsip_vview_si*, const vsip_vview_vi* ) ; void vsip_vscatter_uc ( const vsip_vview_uc*, const vsip_vview_uc*, const vsip_vview_vi* ) ; void vsip_vsdiv_d ( const vsip_vview_d*, vsip_scalar_d, const vsip_vview_d* ) ; void vsip_vsdiv_f ( const vsip_vview_f*, vsip_scalar_f, const vsip_vview_f* ) ; void vsip_vsin_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vsin_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vsinh_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vsinh_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vsma_d ( const vsip_vview_d*, vsip_scalar_d, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vsma_f ( const vsip_vview_f*, vsip_scalar_f, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vsmsa_d ( const vsip_vview_d*, vsip_scalar_d, vsip_scalar_d, const vsip_vview_d* ) ; void vsip_vsmsa_f ( const vsip_vview_f*, vsip_scalar_f, vsip_scalar_f, const vsip_vview_f* ) ; void vsip_vsortip_d ( const vsip_vview_d*, vsip_sort_mode, vsip_sort_dir, vsip_bool, const vsip_vview_vi* ) ; void vsip_vsortip_f ( const vsip_vview_f*, vsip_sort_mode, vsip_sort_dir, vsip_bool, const vsip_vview_vi* ) ; void vsip_vsortip_vi ( const vsip_vview_vi*, vsip_sort_mode, vsip_sort_dir, vsip_bool, const vsip_vview_vi* ) ; void vsip_vsortip_i ( const vsip_vview_i*, vsip_sort_mode, vsip_sort_dir, vsip_bool, const vsip_vview_vi* ) ; void vsip_vsortip_li ( const vsip_vview_li*, vsip_sort_mode, vsip_sort_dir, vsip_bool, const vsip_vview_vi* ) ; void vsip_vsq_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vsq_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vsqrt_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vsqrt_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vsub_d ( const vsip_vview_d*, const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vsub_f ( const vsip_vview_f*, const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vsub_i ( const vsip_vview_i*, const vsip_vview_i*, const vsip_vview_i* ) ; void vsip_vsub_li ( const vsip_vview_li*, const vsip_vview_li*, const vsip_vview_li* ) ; void vsip_vsub_si ( const vsip_vview_si*, const vsip_vview_si*, const vsip_vview_si* ) ; void vsip_vsub_uc ( const vsip_vview_uc*, const vsip_vview_uc*, const vsip_vview_uc* ) ; void vsip_vswap_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vswap_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vswap_i ( const vsip_vview_i*, const vsip_vview_i* ) ; void vsip_vswap_li ( const vsip_vview_li*, const vsip_vview_li* ) ; void vsip_vswap_si ( const vsip_vview_si*, const vsip_vview_si* ) ; void vsip_vswap_uc ( const vsip_vview_uc*, const vsip_vview_uc* ) ; void vsip_vtan_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vtan_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vtanh_d ( const vsip_vview_d*, const vsip_vview_d* ) ; void vsip_vtanh_f ( const vsip_vview_f*, const vsip_vview_f* ) ; void vsip_vxor_bl ( const vsip_vview_bl*, const vsip_vview_bl*, const vsip_vview_bl* ) ; void vsip_vxor_i ( const vsip_vview_i*, const vsip_vview_i*, const vsip_vview_i* ) ; void vsip_vxor_li ( const vsip_vview_li*, const vsip_vview_li*, const vsip_vview_li* ) ; void vsip_vxor_si ( const vsip_vview_si*, const vsip_vview_si*, const vsip_vview_si* ) ; void vsip_vxor_uc ( const vsip_vview_uc*, const vsip_vview_uc*, const vsip_vview_uc* ) ; vsip_offset vsip_cmgetoffset_d ( const vsip_cmview_d* ) ; vsip_offset vsip_cmgetoffset_f ( const vsip_cmview_f* ) ; vsip_offset vsip_ctgetoffset_d ( const vsip_ctview_d* ) ; vsip_offset vsip_ctgetoffset_f ( const vsip_ctview_f* ) ; vsip_offset vsip_cvgetoffset_d ( const vsip_cvview_d* ) ; vsip_offset vsip_cvgetoffset_f ( const vsip_cvview_f* ) ; vsip_offset vsip_mgetoffset_bl ( const vsip_mview_bl* ) ; vsip_offset vsip_mgetoffset_d ( const vsip_mview_d* ) ; vsip_offset vsip_mgetoffset_f ( const vsip_mview_f* ) ; vsip_offset vsip_mgetoffset_i ( const vsip_mview_i* ) ; vsip_offset vsip_mgetoffset_li ( const vsip_mview_li* ) ; vsip_offset vsip_mgetoffset_si ( const vsip_mview_si* ) ; vsip_offset vsip_mgetoffset_uc ( const vsip_mview_uc* ) ; vsip_offset vsip_tgetoffset_d ( const vsip_tview_d* ) ; vsip_offset vsip_tgetoffset_f ( const vsip_tview_f* ) ; vsip_offset vsip_tgetoffset_i ( const vsip_tview_i* ) ; vsip_offset vsip_tgetoffset_li ( const vsip_tview_li* ) ; vsip_offset vsip_tgetoffset_si ( const vsip_tview_si* ) ; vsip_offset vsip_tgetoffset_uc ( const vsip_tview_uc* ) ; vsip_offset vsip_vgetoffset_bl ( const vsip_vview_bl* ) ; vsip_offset vsip_vgetoffset_d ( const vsip_vview_d* ) ; vsip_offset vsip_vgetoffset_f ( const vsip_vview_f* ) ; vsip_offset vsip_vgetoffset_i ( const vsip_vview_i* ) ; vsip_offset vsip_vgetoffset_li ( const vsip_vview_li* ) ; vsip_offset vsip_vgetoffset_mi ( const vsip_vview_mi* ) ; vsip_offset vsip_vgetoffset_si ( const vsip_vview_si* ) ; vsip_offset vsip_vgetoffset_uc ( const vsip_vview_uc* ) ; vsip_offset vsip_vgetoffset_vi ( const vsip_vview_vi* ) ; vsip_stride vsip_cmgetcolstride_d ( const vsip_cmview_d* ) ; vsip_stride vsip_cmgetcolstride_f ( const vsip_cmview_f* ) ; vsip_stride vsip_cmgetrowstride_d ( const vsip_cmview_d* ) ; vsip_stride vsip_cmgetrowstride_f ( const vsip_cmview_f* ) ; vsip_stride vsip_ctgetxstride_d ( const vsip_ctview_d* ) ; vsip_stride vsip_ctgetxstride_f ( const vsip_ctview_f* ) ; vsip_stride vsip_ctgetystride_d ( const vsip_ctview_d* ) ; vsip_stride vsip_ctgetystride_f ( const vsip_ctview_f* ) ; vsip_stride vsip_ctgetzstride_d ( const vsip_ctview_d* ) ; vsip_stride vsip_ctgetzstride_f ( const vsip_ctview_f* ) ; vsip_stride vsip_cvgetstride_d ( const vsip_cvview_d* ) ; vsip_stride vsip_cvgetstride_f ( const vsip_cvview_f* ) ; vsip_stride vsip_mgetcolstride_bl ( const vsip_mview_bl* ) ; vsip_stride vsip_mgetcolstride_d ( const vsip_mview_d* ) ; vsip_stride vsip_mgetcolstride_f ( const vsip_mview_f* ) ; vsip_stride vsip_mgetcolstride_i ( const vsip_mview_i* ) ; vsip_stride vsip_mgetcolstride_li ( const vsip_mview_li* ) ; vsip_stride vsip_mgetcolstride_si ( const vsip_mview_si* ) ; vsip_stride vsip_mgetcolstride_uc ( const vsip_mview_uc* ) ; vsip_stride vsip_mgetrowstride_bl ( const vsip_mview_bl* ) ; vsip_stride vsip_mgetrowstride_d ( const vsip_mview_d* ) ; vsip_stride vsip_mgetrowstride_f ( const vsip_mview_f* ) ; vsip_stride vsip_mgetrowstride_i ( const vsip_mview_i* ) ; vsip_stride vsip_mgetrowstride_li ( const vsip_mview_li* ) ; vsip_stride vsip_mgetrowstride_si ( const vsip_mview_si* ) ; vsip_stride vsip_mgetrowstride_uc ( const vsip_mview_uc* ) ; vsip_stride vsip_tgetxstride_d ( const vsip_tview_d* ) ; vsip_stride vsip_tgetxstride_f ( const vsip_tview_f* ) ; vsip_stride vsip_tgetxstride_i ( const vsip_tview_i* ) ; vsip_stride vsip_tgetxstride_li ( const vsip_tview_li* ) ; vsip_stride vsip_tgetxstride_si ( const vsip_tview_si* ) ; vsip_stride vsip_tgetxstride_uc ( const vsip_tview_uc* ) ; vsip_stride vsip_tgetystride_d ( const vsip_tview_d* ) ; vsip_stride vsip_tgetystride_f ( const vsip_tview_f* ) ; vsip_stride vsip_tgetystride_i ( const vsip_tview_i* ) ; vsip_stride vsip_tgetystride_li ( const vsip_tview_li* ) ; vsip_stride vsip_tgetystride_si ( const vsip_tview_si* ) ; vsip_stride vsip_tgetystride_uc ( const vsip_tview_uc* ) ; vsip_stride vsip_tgetzstride_d ( const vsip_tview_d* ) ; vsip_stride vsip_tgetzstride_f ( const vsip_tview_f* ) ; vsip_stride vsip_tgetzstride_i ( const vsip_tview_i* ) ; vsip_stride vsip_tgetzstride_li ( const vsip_tview_li* ) ; vsip_stride vsip_tgetzstride_si ( const vsip_tview_si* ) ; vsip_stride vsip_tgetzstride_uc ( const vsip_tview_uc* ) ; vsip_stride vsip_vgetstride_bl ( const vsip_vview_bl* ) ; vsip_stride vsip_vgetstride_d ( const vsip_vview_d* ) ; vsip_stride vsip_vgetstride_f ( const vsip_vview_f* ) ; vsip_stride vsip_vgetstride_i ( const vsip_vview_i* ) ; vsip_stride vsip_vgetstride_li ( const vsip_vview_li* ) ; vsip_stride vsip_vgetstride_mi ( const vsip_vview_mi* ) ; vsip_stride vsip_vgetstride_si ( const vsip_vview_si* ) ; vsip_stride vsip_vgetstride_uc ( const vsip_vview_uc* ) ; vsip_stride vsip_vgetstride_vi ( const vsip_vview_vi* ) ; vsip_length vsip_cmgetcollength_d ( const vsip_cmview_d* ) ; vsip_length vsip_cmgetcollength_f ( const vsip_cmview_f* ) ; vsip_length vsip_cmgetrowlength_d ( const vsip_cmview_d* ) ; vsip_length vsip_cmgetrowlength_f ( const vsip_cmview_f* ) ; vsip_length vsip_ctgetxlength_d ( const vsip_ctview_d* ) ; vsip_length vsip_ctgetxlength_f ( const vsip_ctview_f* ) ; vsip_length vsip_ctgetylength_d ( const vsip_ctview_d* ) ; vsip_length vsip_ctgetylength_f ( const vsip_ctview_f* ) ; vsip_length vsip_ctgetzlength_d ( const vsip_ctview_d* ) ; vsip_length vsip_ctgetzlength_f ( const vsip_ctview_f* ) ; vsip_length vsip_cvgetlength_d ( const vsip_cvview_d* ) ; vsip_length vsip_cvgetlength_f ( const vsip_cvview_f* ) ; vsip_length vsip_mgetcollength_bl ( const vsip_mview_bl* ) ; vsip_length vsip_mgetcollength_d ( const vsip_mview_d* ) ; vsip_length vsip_mgetcollength_f ( const vsip_mview_f* ) ; vsip_length vsip_mgetcollength_i ( const vsip_mview_i* ) ; vsip_length vsip_mgetcollength_li ( const vsip_mview_li* ) ; vsip_length vsip_mgetcollength_si ( const vsip_mview_si* ) ; vsip_length vsip_mgetcollength_uc ( const vsip_mview_uc* ) ; vsip_length vsip_mgetrowlength_bl ( const vsip_mview_bl* ) ; vsip_length vsip_mgetrowlength_d ( const vsip_mview_d* ) ; vsip_length vsip_mgetrowlength_f ( const vsip_mview_f* ) ; vsip_length vsip_mgetrowlength_i ( const vsip_mview_i* ) ; vsip_length vsip_mgetrowlength_li ( const vsip_mview_li* ) ; vsip_length vsip_mgetrowlength_si ( const vsip_mview_si* ) ; vsip_length vsip_mgetrowlength_uc ( const vsip_mview_uc* ) ; vsip_length vsip_mindexbool ( const vsip_mview_bl*, vsip_vview_mi* ) ; vsip_length vsip_tgetxlength_d ( const vsip_tview_d* ) ; vsip_length vsip_tgetxlength_f ( const vsip_tview_f* ) ; vsip_length vsip_tgetxlength_i ( const vsip_tview_i* ) ; vsip_length vsip_tgetxlength_li ( const vsip_tview_li* ) ; vsip_length vsip_tgetxlength_si ( const vsip_tview_si* ) ; vsip_length vsip_tgetxlength_uc ( const vsip_tview_uc* ) ; vsip_length vsip_tgetylength_d ( const vsip_tview_d* ) ; vsip_length vsip_tgetylength_f ( const vsip_tview_f* ) ; vsip_length vsip_tgetylength_i ( const vsip_tview_i* ) ; vsip_length vsip_tgetylength_li ( const vsip_tview_li* ) ; vsip_length vsip_tgetylength_si ( const vsip_tview_si* ) ; vsip_length vsip_tgetylength_uc ( const vsip_tview_uc* ) ; vsip_length vsip_tgetzlength_d ( const vsip_tview_d* ) ; vsip_length vsip_tgetzlength_f ( const vsip_tview_f* ) ; vsip_length vsip_tgetzlength_i ( const vsip_tview_i* ) ; vsip_length vsip_tgetzlength_li ( const vsip_tview_li* ) ; vsip_length vsip_tgetzlength_si ( const vsip_tview_si* ) ; vsip_length vsip_tgetzlength_uc ( const vsip_tview_uc* ) ; vsip_length vsip_vgetlength_bl ( const vsip_vview_bl* ) ; vsip_length vsip_vgetlength_d ( const vsip_vview_d* ) ; vsip_length vsip_vgetlength_f ( const vsip_vview_f* ) ; vsip_length vsip_vgetlength_i ( const vsip_vview_i* ) ; vsip_length vsip_vgetlength_li ( const vsip_vview_li* ) ; vsip_length vsip_vgetlength_mi ( const vsip_vview_mi* ) ; vsip_length vsip_vgetlength_si ( const vsip_vview_si* ) ; vsip_length vsip_vgetlength_uc ( const vsip_vview_uc* ) ; vsip_length vsip_vgetlength_vi ( const vsip_vview_vi* ) ; vsip_length vsip_vindexbool ( const vsip_vview_bl*, vsip_vview_vi* ) ; vsip_index vsip_vfirst_d ( vsip_index, vsip_bool ( * ) ( vsip_scalar_d, vsip_scalar_d ), const vsip_vview_d*, const vsip_vview_d* ) ; vsip_index vsip_vfirst_f ( vsip_index, vsip_bool ( * ) ( vsip_scalar_f, vsip_scalar_f ), const vsip_vview_f*, const vsip_vview_f* ) ; vsip_index vsip_vfirst_i ( vsip_index, vsip_bool ( * ) ( vsip_scalar_i, vsip_scalar_i ), const vsip_vview_i*, const vsip_vview_i* ) ; vsip_index vsip_vfirst_li ( vsip_index, vsip_bool ( * ) ( vsip_scalar_li, vsip_scalar_li ), const vsip_vview_li*, const vsip_vview_li* ) ; vsip_index vsip_vfirst_mi ( vsip_index, vsip_bool ( * ) ( vsip_scalar_mi, vsip_scalar_mi ), const vsip_vview_mi*, const vsip_vview_mi* ) ; vsip_index vsip_vfirst_vi ( vsip_index, vsip_bool ( * ) ( vsip_scalar_vi, vsip_scalar_vi ), const vsip_vview_vi*, const vsip_vview_vi* ) ; vsip_cchol_d* vsip_cchold_create_d ( const vsip_mat_uplo, vsip_length ) ; vsip_cchol_f* vsip_cchold_create_f ( const vsip_mat_uplo, vsip_length ) ; vsip_ccorr1d_d* vsip_ccorr1d_create_d ( vsip_length, vsip_length, vsip_support_region, unsigned int, vsip_alg_hint ) ; vsip_ccorr1d_f* vsip_ccorr1d_create_f ( vsip_length, vsip_length, vsip_support_region, unsigned int, vsip_alg_hint ) ; vsip_rcfir_d* vsip_rcfir_create_d ( const vsip_vview_d*, vsip_symmetry, vsip_length, vsip_length, vsip_obj_state, unsigned int, vsip_alg_hint ) ; vsip_rcfir_f* vsip_rcfir_create_f ( const vsip_vview_f*, vsip_symmetry, vsip_length, vsip_length, vsip_obj_state, unsigned int, vsip_alg_hint ) ; vsip_cfir_d* vsip_cfir_create_d ( const vsip_cvview_d*, vsip_symmetry, vsip_length, vsip_length, vsip_obj_state, unsigned int, vsip_alg_hint ) ; vsip_cfir_f* vsip_cfir_create_f ( const vsip_cvview_f*, vsip_symmetry, vsip_length, vsip_length, vsip_obj_state, unsigned int, vsip_alg_hint ) ; vsip_chol_d* vsip_chold_create_d ( const vsip_mat_uplo, vsip_length ) ; vsip_chol_f* vsip_chold_create_f ( const vsip_mat_uplo, vsip_length ) ; vsip_clu_d* vsip_clud_create_d ( vsip_length ) ; vsip_clu_f* vsip_clud_create_f ( vsip_length ) ; vsip_cmplx_mem vsip_cstorage ( void ) ; vsip_conv1d_d *vsip_conv1d_create_d ( const vsip_vview_d*, vsip_symmetry, vsip_length, int, vsip_support_region, unsigned int, vsip_alg_hint ) ; vsip_conv1d_f *vsip_conv1d_create_f ( const vsip_vview_f*, vsip_symmetry, vsip_length, int, vsip_support_region, unsigned int, vsip_alg_hint ) ; vsip_corr1d_d *vsip_corr1d_create_d ( vsip_length, vsip_length, vsip_support_region, unsigned int, vsip_alg_hint ) ; vsip_corr1d_f *vsip_corr1d_create_f ( vsip_length, vsip_length, vsip_support_region, unsigned int, vsip_alg_hint ) ; vsip_cqr_d* vsip_cqrd_create_d ( vsip_length, vsip_length, vsip_qrd_qopt ) ; vsip_cqr_f* vsip_cqrd_create_f ( vsip_length, vsip_length, vsip_qrd_qopt ) ; vsip_fft_d* vsip_ccfftip_create_d ( vsip_length, vsip_scalar_d, vsip_fft_dir, unsigned int, vsip_alg_hint ) ; vsip_fft_d* vsip_ccfftop_create_d ( vsip_length, vsip_scalar_d, vsip_fft_dir, unsigned int, vsip_alg_hint ) ; vsip_fft_d* vsip_crfftop_create_d ( vsip_length, vsip_scalar_d, unsigned int, vsip_alg_hint ) ; vsip_fft_d* vsip_rcfftop_create_d ( vsip_length, vsip_scalar_d, unsigned int, vsip_alg_hint ) ; vsip_fft_f* vsip_ccfftip_create_f ( vsip_length, vsip_scalar_f, vsip_fft_dir, unsigned int, vsip_alg_hint ) ; vsip_fft_f* vsip_ccfftop_create_f ( vsip_length, vsip_scalar_f, vsip_fft_dir, unsigned int, vsip_alg_hint ) ; vsip_fft_f* vsip_crfftop_create_f ( vsip_length, vsip_scalar_f, unsigned int, vsip_alg_hint ) ; vsip_fft_f* vsip_rcfftop_create_f ( vsip_length, vsip_scalar_f, unsigned int, vsip_alg_hint ) ; vsip_fftm_d* vsip_ccfftmip_create_d ( vsip_length, vsip_length, vsip_scalar_d, vsip_fft_dir, vsip_major, unsigned int, vsip_alg_hint ) ; vsip_fftm_d* vsip_ccfftmop_create_d ( vsip_length, vsip_length, vsip_scalar_d, vsip_fft_dir, vsip_major, unsigned int, vsip_alg_hint ) ; vsip_fftm_d* vsip_crfftmop_create_d ( vsip_length, vsip_length, vsip_scalar_d, vsip_major, unsigned int, vsip_alg_hint ) ; vsip_fftm_d* vsip_rcfftmop_create_d ( vsip_length, vsip_length, vsip_scalar_d, vsip_major, unsigned int, vsip_alg_hint ) ; vsip_fftm_f* vsip_ccfftmip_create_f ( vsip_length, vsip_length, vsip_scalar_f, vsip_fft_dir, vsip_major, unsigned int, vsip_alg_hint ) ; vsip_fftm_f* vsip_ccfftmop_create_f ( vsip_length, vsip_length, vsip_scalar_f, vsip_fft_dir, vsip_major, unsigned int, vsip_alg_hint ) ; vsip_fftm_f* vsip_crfftmop_create_f ( vsip_length, vsip_length, vsip_scalar_f, vsip_major, unsigned int, vsip_alg_hint ) ; vsip_fftm_f* vsip_rcfftmop_create_f ( vsip_length, vsip_length, vsip_scalar_f, vsip_major, unsigned int, vsip_alg_hint ) ; vsip_fir_d* vsip_fir_create_d ( const vsip_vview_d*, vsip_symmetry, vsip_length, vsip_length, vsip_obj_state, unsigned int, vsip_alg_hint ) ; vsip_fir_f* vsip_fir_create_f ( const vsip_vview_f*, vsip_symmetry, vsip_length, vsip_length, vsip_obj_state, unsigned int, vsip_alg_hint ) ; vsip_lu_d* vsip_lud_create_d ( vsip_length ) ; vsip_lu_f* vsip_lud_create_f ( vsip_length ) ; vsip_permute* vsip_mpermute_create_d ( vsip_length, vsip_length, vsip_major ) ; vsip_permute* vsip_mpermute_create_f ( vsip_length, vsip_length, vsip_major ) ; vsip_permute* vsip_permute_init ( vsip_permute*, const vsip_vview_vi* ) ; vsip_qr_d* vsip_qrd_create_d ( vsip_length, vsip_length, vsip_qrd_qopt ) ; vsip_qr_f* vsip_qrd_create_f ( vsip_length, vsip_length, vsip_qrd_qopt ) ; vsip_randstate *vsip_randcreate ( vsip_index, vsip_index, vsip_index, vsip_rng ) ; vsip_scalar_bl* vsip_blockfind_bl ( const vsip_block_bl* ) ; vsip_scalar_bl* vsip_blockrebind_bl ( vsip_block_bl*, vsip_scalar_bl* const ) ; vsip_scalar_bl* vsip_blockrelease_bl ( vsip_block_bl*, vsip_scalar_bl ) ; vsip_scalar_d* vsip_blockfind_d ( const vsip_block_d* ) ; vsip_scalar_d* vsip_blockrebind_d ( vsip_block_d*, vsip_scalar_d* const ) ; vsip_scalar_d* vsip_blockrelease_d ( vsip_block_d*, vsip_scalar_bl ) ; vsip_scalar_f* vsip_blockfind_f ( const vsip_block_f* ) ; vsip_scalar_f* vsip_blockrebind_f ( vsip_block_f*, vsip_scalar_f* const ) ; vsip_scalar_f* vsip_blockrelease_f ( vsip_block_f*, vsip_scalar_bl ) ; vsip_scalar_i* vsip_blockfind_i ( const vsip_block_i* ) ; vsip_scalar_i* vsip_blockrebind_i ( vsip_block_i*, vsip_scalar_i* const ) ; vsip_scalar_i* vsip_blockrelease_i ( vsip_block_i*, vsip_scalar_bl ) ; vsip_scalar_li * vsip_blockfind_li ( const vsip_block_li* ) ; vsip_scalar_li * vsip_blockrebind_li ( vsip_block_li*, vsip_scalar_li * const ) ; vsip_scalar_li * vsip_blockrelease_li ( vsip_block_li*, vsip_scalar_bl ) ; vsip_scalar_si* vsip_blockfind_si ( const vsip_block_si* ) ; vsip_scalar_si* vsip_blockrebind_si ( vsip_block_si*, vsip_scalar_si* const ) ; vsip_scalar_si* vsip_blockrelease_si ( vsip_block_si*, vsip_scalar_bl ) ; vsip_scalar_uc* vsip_blockfind_uc ( const vsip_block_uc* ) ; vsip_scalar_uc* vsip_blockrebind_uc ( vsip_block_uc*, vsip_scalar_uc* const ) ; vsip_scalar_uc* vsip_blockrelease_uc ( vsip_block_uc*, vsip_scalar_bl ) ; vsip_scalar_vi* vsip_blockfind_mi ( const vsip_block_mi* ) ; vsip_scalar_vi* vsip_blockfind_vi ( const vsip_block_vi* ) ; vsip_scalar_vi* vsip_blockrebind_mi ( vsip_block_mi*, vsip_scalar_vi* const ) ; vsip_scalar_vi* vsip_blockrebind_vi ( vsip_block_vi*, vsip_scalar_vi* const ) ; vsip_scalar_vi* vsip_blockrelease_mi ( vsip_block_mi*, vsip_scalar_bl ) ; vsip_scalar_vi* vsip_blockrelease_vi ( vsip_block_vi*, vsip_scalar_bl ) ; vsip_spline_d* vsip_spline_create_d ( vsip_length ) ; vsip_spline_f* vsip_spline_create_f ( vsip_length ) ; vsip_vview_vi* vsip_vsubview_vi( const vsip_vview_vi*, vsip_index, vsip_length); vsip_vview_mi* vsip_vsubview_mi( const vsip_vview_mi*, vsip_index, vsip_length); vsip_vview_bl* vsip_vsubview_bl( const vsip_vview_bl*, vsip_index, vsip_length); vsip_vview_d* vsip_vsubview_d( const vsip_vview_d*, vsip_index, vsip_length); vsip_vview_f* vsip_vsubview_f( const vsip_vview_f*, vsip_index, vsip_length); vsip_vview_i* vsip_vsubview_i( const vsip_vview_i*, vsip_index, vsip_length); vsip_vview_li* vsip_vsubview_li( const vsip_vview_li*, vsip_index, vsip_length); vsip_vview_si* vsip_vsubview_si( const vsip_vview_si*, vsip_index, vsip_length); vsip_vview_uc* vsip_vsubview_uc( const vsip_vview_uc*, vsip_index, vsip_length); vsip_cvview_d* vsip_cvsubview_d( const vsip_cvview_d*, vsip_index, vsip_length); vsip_cvview_f* vsip_cvsubview_f( const vsip_cvview_f*, vsip_index, vsip_length); vsip_mview_d* vsip_msubview_d( const vsip_mview_d*, vsip_index, vsip_index, vsip_length m, vsip_length); vsip_mview_f* vsip_msubview_f( const vsip_mview_f*, vsip_index, vsip_index, vsip_length m, vsip_length); vsip_vview_i* vsip_mrowview_i( const vsip_mview_i*, vsip_index); vsip_vview_li* vsip_mrowview_li( const vsip_mview_li*, vsip_index); vsip_vview_si* vsip_mrowview_si( const vsip_mview_si*, vsip_index); vsip_vview_uc* vsip_mrowview_uc( const vsip_mview_uc*, vsip_index); vsip_cvview_d* vsip_cmrowview_d( const vsip_cmview_d*, vsip_index); vsip_cvview_f* vsip_cmrowview_f( const vsip_cmview_f*, vsip_index); vsip_vview_d* vsip_mrowview_d( const vsip_mview_d*, vsip_index); vsip_vview_f* vsip_mrowview_f( const vsip_mview_f*, vsip_index); vsip_vview_bl* vsip_mrowview_bl( const vsip_mview_bl*, vsip_index); vsip_vview_uc* vsip_mcolview_uc( const vsip_mview_uc*, vsip_index); vsip_cvview_d* vsip_cmcolview_d( const vsip_cmview_d*, vsip_index); vsip_cvview_f* vsip_cmcolview_f( const vsip_cmview_f*, vsip_index); vsip_vview_d* vsip_mcolview_d( const vsip_mview_d*, vsip_index); vsip_vview_f* vsip_mcolview_f( const vsip_mview_f*, vsip_index); vsip_vview_bl* vsip_mcolview_bl( const vsip_mview_bl*, vsip_index); vsip_vview_i* vsip_mcolview_i( const vsip_mview_i*, vsip_index); vsip_vview_li* vsip_mcolview_li( const vsip_mview_li*, vsip_index); vsip_vview_si* vsip_mcolview_si( const vsip_mview_si*, vsip_index); vsip_vview_i* vsip_mdiagview_i( const vsip_mview_i*, vsip_stride); vsip_vview_li* vsip_mdiagview_li( const vsip_mview_li*, vsip_stride); vsip_vview_si* vsip_mdiagview_si( const vsip_mview_si*, vsip_stride); vsip_vview_uc* vsip_mdiagview_uc( const vsip_mview_uc*, vsip_stride); vsip_cvview_d* vsip_cmdiagview_d( const vsip_cmview_d*, vsip_stride); vsip_cvview_f* vsip_cmdiagview_f( const vsip_cmview_f*, vsip_stride); vsip_vview_d* vsip_mdiagview_d( const vsip_mview_d*, vsip_stride); vsip_vview_bl* vsip_mdiagview_bl( const vsip_mview_bl*, vsip_stride); vsip_vview_f* vsip_mdiagview_f( const vsip_mview_f*, vsip_stride); vsip_mview_bl* vsip_mtransview_bl( const vsip_mview_bl*); vsip_mview_i* vsip_mtransview_i( const vsip_mview_i*); vsip_mview_li* vsip_mtransview_li( const vsip_mview_li*); vsip_mview_si* vsip_mtransview_si( const vsip_mview_si*); vsip_mview_uc* vsip_mtransview_uc( const vsip_mview_uc*); vsip_cmview_d* vsip_cmtransview_d( const vsip_cmview_d*); vsip_cmview_f* vsip_cmtransview_f( const vsip_cmview_f*); vsip_tview_f* vsip_ttransview_f( const vsip_tview_f*, vsip_ttrans); vsip_tview_d* vsip_ttransview_d( const vsip_tview_d*, vsip_ttrans); vsip_tview_i* vsip_ttransview_i( const vsip_tview_i*, vsip_ttrans); vsip_tview_li* vsip_ttransview_li( const vsip_tview_li*, vsip_ttrans); vsip_tview_si* vsip_ttransview_si( const vsip_tview_si*, vsip_ttrans); vsip_tview_uc* vsip_ttransview_uc( const vsip_tview_uc*, vsip_ttrans); vsip_ctview_f* vsip_cttransview_f( const vsip_ctview_f*, vsip_ttrans); vsip_ctview_d* vsip_cttransview_d( const vsip_ctview_d*, vsip_ttrans); vsip_mview_d* vsip_mtransview_d( const vsip_mview_d*); vsip_mview_f* vsip_mtransview_f( const vsip_mview_f*); vsip_mview_d* vsip_mrealview_d( const vsip_cmview_d*); vsip_mview_f* vsip_mrealview_f( const vsip_cmview_f*); vsip_tview_f *vsip_trealview_f( const vsip_ctview_f*); vsip_tview_d *vsip_trealview_d( const vsip_ctview_d*); vsip_vview_d* vsip_vrealview_d( const vsip_cvview_d*); vsip_vview_f* vsip_vrealview_f( const vsip_cvview_f*); vsip_tview_f *vsip_timagview_f( const vsip_ctview_f*); vsip_tview_d *vsip_timagview_d( const vsip_ctview_d*); vsip_vview_d* vsip_vimagview_d( const vsip_cvview_d*); vsip_vview_f* vsip_vimagview_f( const vsip_cvview_f*); vsip_mview_d* vsip_mimagview_d( const vsip_cmview_d*); vsip_mview_f* vsip_mimagview_f( const vsip_cmview_f*); vsip_vview_bl* vsip_vcreate_bl(vsip_length, vsip_memory_hint); vsip_vview_i* vsip_vcreate_i(vsip_length, vsip_memory_hint); vsip_vview_li* vsip_vcreate_li(vsip_length, vsip_memory_hint); vsip_vview_mi* vsip_vcreate_mi(vsip_length, vsip_memory_hint); vsip_vview_si* vsip_vcreate_si(vsip_length, vsip_memory_hint); vsip_vview_uc* vsip_vcreate_uc(vsip_length, vsip_memory_hint); vsip_cmview_d* vsip_cmputattrib_d( vsip_cmview_d*, const vsip_cmattr_d*); vsip_cmview_f* vsip_cmputattrib_f( vsip_cmview_f*, const vsip_cmattr_f*); vsip_mview_bl* vsip_mputattrib_bl( vsip_mview_bl*, const vsip_mattr_bl*); vsip_mview_d* vsip_mputattrib_d( vsip_mview_d*, const vsip_mattr_d*); vsip_mview_f* vsip_mputattrib_f( vsip_mview_f*, const vsip_mattr_f*); vsip_mview_i* vsip_mputattrib_i( vsip_mview_i*, const vsip_mattr_i*); vsip_mview_li* vsip_mputattrib_li( vsip_mview_li*, const vsip_mattr_li*); vsip_mview_si* vsip_mputattrib_si( vsip_mview_si*, const vsip_mattr_si*); vsip_mview_uc* vsip_mputattrib_uc( vsip_mview_uc*, const vsip_mattr_uc*); vsip_vview_bl* vsip_vputattrib_bl( vsip_vview_bl*, const vsip_vattr_bl*); vsip_vview_i* vsip_vputattrib_i( vsip_vview_i*, const vsip_vattr_i*); vsip_vview_li* vsip_vputattrib_li( vsip_vview_li*, const vsip_vattr_li*); vsip_vview_mi* vsip_vputattrib_mi( vsip_vview_mi*, const vsip_vattr_mi*); vsip_vview_uc* vsip_vputattrib_uc( vsip_vview_uc*, const vsip_vattr_uc*); vsip_vview_vi* vsip_vputattrib_vi( vsip_vview_vi*, const vsip_vattr_vi*); vsip_cmview_d* vsip_cmcloneview_d( const vsip_cmview_d*); vsip_cmview_f* vsip_cmcloneview_f( const vsip_cmview_f*); vsip_cmview_d* vsip_cmputcollength_d( vsip_cmview_d*, vsip_length); vsip_cmview_f* vsip_cmputcollength_f( vsip_cmview_f*, vsip_length); vsip_cmview_d* vsip_cmputcolstride_d( vsip_cmview_d*, vsip_stride); vsip_cmview_f* vsip_cmputcolstride_f( vsip_cmview_f*, vsip_stride); vsip_cmview_d* vsip_cmputoffset_d( vsip_cmview_d*, vsip_offset); vsip_cmview_f* vsip_cmputoffset_f( vsip_cmview_f*, vsip_offset); vsip_cmview_d* vsip_cmputrowlength_d( vsip_cmview_d*, vsip_length); vsip_cmview_f* vsip_cmputrowlength_f( vsip_cmview_f*, vsip_length); vsip_cmview_d* vsip_cmputrowstride_d( vsip_cmview_d*, vsip_stride); vsip_cmview_f* vsip_cmputrowstride_f( vsip_cmview_f*, vsip_stride); vsip_cmview_d* vsip_cmsubview_d( const vsip_cmview_d*, vsip_index, vsip_index, vsip_length, vsip_length); vsip_cmview_f* vsip_cmsubview_f( const vsip_cmview_f*, vsip_index, vsip_index, vsip_length, vsip_length); vsip_mview_bl* vsip_mcloneview_bl( const vsip_mview_bl*); vsip_mview_d* vsip_mcloneview_d( const vsip_mview_d*); vsip_mview_f* vsip_mcloneview_f( const vsip_mview_f*); vsip_mview_i* vsip_mcloneview_i( const vsip_mview_i*); vsip_mview_li* vsip_mcloneview_li( const vsip_mview_li*); vsip_mview_si* vsip_mcloneview_si( const vsip_mview_si*); vsip_mview_uc* vsip_mcloneview_uc( const vsip_mview_uc*); vsip_ctview_d *vsip_ctbind_d( const vsip_cblock_d*, vsip_offset, vsip_stride, vsip_length, vsip_stride, vsip_length, vsip_stride, vsip_length); vsip_ctview_f *vsip_ctbind_f( const vsip_cblock_f*, vsip_offset, vsip_stride, vsip_length, vsip_stride, vsip_length, vsip_stride, vsip_length); vsip_ctview_d *vsip_ctcloneview_d( const vsip_ctview_d*); vsip_ctview_f *vsip_ctcloneview_f( const vsip_ctview_f*); vsip_ctview_d* vsip_ctcreate_d( vsip_length, vsip_length, vsip_length, vsip_tmajor, vsip_memory_hint); vsip_ctview_f* vsip_ctcreate_f( vsip_length, vsip_length, vsip_length, vsip_tmajor, vsip_memory_hint); vsip_ctview_d *vsip_ctsubview_d( const vsip_ctview_d*, vsip_index, vsip_index, vsip_index, vsip_length, vsip_length, vsip_length); vsip_ctview_f *vsip_ctsubview_f( const vsip_ctview_f*, vsip_index, vsip_index, vsip_index, vsip_length, vsip_length, vsip_length); vsip_cvview_d *vsip_ctvectview_d( const vsip_ctview_d*, vsip_tvslice, vsip_index, vsip_index); vsip_cvview_f *vsip_ctvectview_f( const vsip_ctview_f*, vsip_tvslice, vsip_index, vsip_index); vsip_cmview_d *vsip_ctmatrixview_d( const vsip_ctview_d*, vsip_tmslice, vsip_index); vsip_cmview_f *vsip_ctmatrixview_f( const vsip_ctview_f*, vsip_tmslice, vsip_index); vsip_vview_vi* vsip_vputstride_vi( vsip_vview_vi*, vsip_stride); vsip_vview_uc* vsip_vputstride_uc( vsip_vview_uc*, vsip_stride); vsip_vview_si* vsip_vputstride_si( vsip_vview_si*, vsip_stride); vsip_vview_mi* vsip_vputstride_mi( vsip_vview_mi*, vsip_stride); vsip_vview_i* vsip_vputstride_i( vsip_vview_i*, vsip_stride); vsip_vview_li* vsip_vputstride_li( vsip_vview_li*, vsip_stride); vsip_vview_bl* vsip_vputstride_bl( vsip_vview_bl*, vsip_stride); vsip_vview_vi* vsip_vputoffset_vi( vsip_vview_vi*, vsip_offset); vsip_vview_uc* vsip_vputoffset_uc( vsip_vview_uc*, vsip_offset); vsip_vview_si* vsip_vputoffset_si( vsip_vview_si*, vsip_offset); vsip_vview_mi* vsip_vputoffset_mi( vsip_vview_mi*, vsip_offset); vsip_vview_i* vsip_vputoffset_i( vsip_vview_i*, vsip_offset); vsip_vview_li* vsip_vputoffset_li( vsip_vview_li*, vsip_offset); vsip_vview_bl* vsip_vputoffset_bl( vsip_vview_bl*, vsip_offset); vsip_vview_vi* vsip_vputlength_vi( vsip_vview_vi*, vsip_length); vsip_vview_mi* vsip_vputlength_mi( vsip_vview_mi*, vsip_length); vsip_vview_bl* vsip_vputlength_bl( vsip_vview_bl*, vsip_length); vsip_vview_i* vsip_vputlength_i( vsip_vview_i*, vsip_length); vsip_vview_li* vsip_vputlength_li( vsip_vview_li*, vsip_length); vsip_vview_si* vsip_vputlength_si( vsip_vview_si*, vsip_length); vsip_vview_uc* vsip_vputlength_uc( vsip_vview_uc*, vsip_length); vsip_vview_bl* vsip_vputoffset_bl( vsip_vview_bl*, vsip_offset); vsip_vview_vi* vsip_vputlength_vi( vsip_vview_vi*, vsip_length); vsip_vview_mi* vsip_vputlength_mi( vsip_vview_mi*, vsip_length); vsip_vview_bl* vsip_vputlength_bl( vsip_vview_bl*, vsip_length); vsip_vview_i* vsip_vputlength_i( vsip_vview_i*, vsip_length); vsip_vview_li* vsip_vputlength_li( vsip_vview_li*, vsip_length); vsip_vview_si* vsip_vputlength_si( vsip_vview_si*, vsip_length); vsip_vview_uc* vsip_vputlength_uc( vsip_vview_uc*, vsip_length); void vsip_vinterp_nearest_d( const vsip_vview_d *, const vsip_vview_d *, const vsip_vview_d *, const vsip_vview_d *); void vsip_minterp_linear_d ( const vsip_vview_d *, const vsip_mview_d *, vsip_major, const vsip_vview_d *, const vsip_mview_d * ) ; void vsip_vgather_mi (const vsip_vview_mi*, const vsip_vview_vi*, const vsip_vview_mi* ) ; void vsip_vgather_vi (const vsip_vview_vi*, const vsip_vview_vi*, const vsip_vview_vi* ) ; vsip_vview_bl* vsip_vcloneview_bl( const vsip_vview_bl*); vsip_vview_i* vsip_vcloneview_i( const vsip_vview_i*); vsip_vview_li* vsip_vcloneview_li( const vsip_vview_li*); vsip_vview_mi* vsip_vcloneview_mi( const vsip_vview_mi*); vsip_vview_si* vsip_vcloneview_si( const vsip_vview_si*); vsip_vview_uc* vsip_vcloneview_uc( const vsip_vview_uc*); vsip_vview_vi* vsip_vcloneview_vi( const vsip_vview_vi*); vsip_ctview_f *vsip_ctputoffset_f ( vsip_ctview_f*, vsip_offset); vsip_ctview_d *vsip_ctputoffset_d ( vsip_ctview_d*, vsip_offset); vsip_tview_i *vsip_tputoffset_i ( vsip_tview_i*, vsip_offset); vsip_tview_li *vsip_tputoffset_li ( vsip_tview_li*, vsip_offset); vsip_tview_si *vsip_tputoffset_si ( vsip_tview_si*, vsip_offset); vsip_tview_uc *vsip_tputoffset_uc ( vsip_tview_uc*, vsip_offset); vsip_tview_f *vsip_tputxlength_f( vsip_tview_f*, vsip_length); vsip_tview_d *vsip_tputxlength_d( vsip_tview_d*, vsip_length); vsip_tview_i *vsip_tputxlength_i( vsip_tview_i*, vsip_length); vsip_tview_li *vsip_tputxlength_li( vsip_tview_li*, vsip_length); vsip_tview_si *vsip_tputxlength_si( vsip_tview_si*, vsip_length); vsip_tview_uc *vsip_tputxlength_uc( vsip_tview_uc*, vsip_length); vsip_ctview_f *vsip_ctputxlength_f( vsip_ctview_f*, vsip_length); vsip_ctview_d *vsip_ctputxlength_d( vsip_ctview_d*, vsip_length); vsip_tview_f *vsip_tputzstride_f( vsip_tview_f*, vsip_stride); vsip_tview_d *vsip_tputzstride_d( vsip_tview_d*, vsip_stride); vsip_tview_i *vsip_tputzstride_i( vsip_tview_i*, vsip_stride); vsip_tview_li *vsip_tputzstride_li( vsip_tview_li*, vsip_stride); vsip_tview_si *vsip_tputzstride_si( vsip_tview_si*, vsip_stride); vsip_tview_uc *vsip_tputzstride_uc( vsip_tview_uc*, vsip_stride); vsip_ctview_f *vsip_ctputzstride_f( vsip_ctview_f*, vsip_stride); vsip_ctview_d *vsip_ctputzstride_d( vsip_ctview_d*, vsip_stride); vsip_tview_f *vsip_tputystride_f( vsip_tview_f*, vsip_stride); vsip_tview_d *vsip_tputystride_d( vsip_tview_d*, vsip_stride); vsip_tview_i *vsip_tputystride_i( vsip_tview_i*, vsip_stride); vsip_tview_li *vsip_tputystride_li( vsip_tview_li*, vsip_stride); vsip_tview_si *vsip_tputystride_si( vsip_tview_si*, vsip_stride); vsip_tview_uc *vsip_tputystride_uc( vsip_tview_uc*, vsip_stride); vsip_vview_f *vsip_tvectview_f( const vsip_tview_f*, vsip_tvslice, vsip_index, vsip_index); vsip_vview_d *vsip_tvectview_d( const vsip_tview_d*, vsip_tvslice, vsip_index, vsip_index); vsip_vview_i *vsip_tvectview_i( const vsip_tview_i*, vsip_tvslice, vsip_index, vsip_index); vsip_vview_li *vsip_tvectview_li( const vsip_tview_li*, vsip_tvslice, vsip_index, vsip_index); vsip_vview_si *vsip_tvectview_si( const vsip_tview_si*, vsip_tvslice, vsip_index, vsip_index); vsip_vview_uc *vsip_tvectview_uc( const vsip_tview_uc*, vsip_tvslice, vsip_index, vsip_index); vsip_tview_f *vsip_tsubview_f( const vsip_tview_f*, vsip_index, vsip_index, vsip_index, vsip_length, vsip_length, vsip_length); vsip_tview_d *vsip_tsubview_d( const vsip_tview_d*, vsip_index, vsip_index, vsip_index, vsip_length, vsip_length, vsip_length); vsip_tview_i *vsip_tsubview_i( const vsip_tview_i*, vsip_index, vsip_index, vsip_index, vsip_length, vsip_length, vsip_length); vsip_tview_li *vsip_tsubview_li( const vsip_tview_li*, vsip_index, vsip_index, vsip_index, vsip_length, vsip_length, vsip_length); vsip_tview_si *vsip_tsubview_si( const vsip_tview_si*, vsip_index, vsip_index, vsip_index, vsip_length, vsip_length, vsip_length); vsip_tview_uc *vsip_tsubview_uc( const vsip_tview_uc*, vsip_index, vsip_index, vsip_index, vsip_length, vsip_length, vsip_length); vsip_mview_si *vsip_tmatrixview_si( const vsip_tview_si*, vsip_tmslice, vsip_index); vsip_mview_uc *vsip_tmatrixview_uc( const vsip_tview_uc*, vsip_tmslice, vsip_index); vsip_mview_i *vsip_tmatrixview_i( const vsip_tview_i*, vsip_tmslice, vsip_index); vsip_mview_li *vsip_tmatrixview_li( const vsip_tview_li*, vsip_tmslice, vsip_index); vsip_mview_f *vsip_tmatrixview_f( const vsip_tview_f*, vsip_tmslice, vsip_index); vsip_mview_d *vsip_tmatrixview_d( const vsip_tview_d*, vsip_tmslice, vsip_index); vsip_tview_i *vsip_tbind_i( const vsip_block_i*, vsip_offset, vsip_stride, vsip_length, vsip_stride, vsip_length, vsip_stride, vsip_length); vsip_tview_li *vsip_tbind_li( const vsip_block_li*, vsip_offset, vsip_stride, vsip_length, vsip_stride, vsip_length, vsip_stride, vsip_length); vsip_tview_si *vsip_tbind_si( const vsip_block_si*, vsip_offset, vsip_stride, vsip_length, vsip_stride, vsip_length, vsip_stride, vsip_length); vsip_tview_uc *vsip_tbind_uc( const vsip_block_uc*, vsip_offset, vsip_stride, vsip_length, vsip_stride, vsip_length, vsip_stride, vsip_length); vsip_ctview_f *vsip_ctputxstride_f( vsip_ctview_f*, vsip_stride); vsip_ctview_d *vsip_ctputxstride_d( vsip_ctview_d*, vsip_stride); vsip_ctview_f *vsip_ctputystride_f( vsip_ctview_f*, vsip_stride); vsip_ctview_d *vsip_ctputystride_d( vsip_ctview_d*, vsip_stride); vsip_ctview_f *vsip_ctputylength_f( vsip_ctview_f*, vsip_length); vsip_ctview_d *vsip_ctputylength_d( vsip_ctview_d*, vsip_length); vsip_ctview_f *vsip_ctputzlength_f( vsip_ctview_f*, vsip_length); vsip_ctview_d *vsip_ctputzlength_d( vsip_ctview_d*, vsip_length); void vsip_minterp_nearest_d ( const vsip_vview_d*, const vsip_mview_d*, vsip_major, const vsip_vview_d*, const vsip_mview_d* ) ; vsip_mview_bl* vsip_mputcollength_bl( vsip_mview_bl*, vsip_length); vsip_mview_d* vsip_mputcollength_d( vsip_mview_d*, vsip_length m); vsip_mview_f* vsip_mputcollength_f( vsip_mview_f*, vsip_length m); vsip_mview_d* vsip_mputcolstride_d( vsip_mview_d*, vsip_stride); vsip_mview_si* vsip_mputcollength_si( vsip_mview_si*, vsip_length); vsip_mview_bl* vsip_mputcolstride_bl( vsip_mview_bl*, vsip_stride); vsip_mview_uc* vsip_mputoffset_uc( vsip_mview_uc*, vsip_offset); vsip_mview_uc* vsip_mputrowstride_uc( vsip_mview_uc*, vsip_stride); vsip_mview_uc* vsip_mputrowlength_uc( vsip_mview_uc*, vsip_length); vsip_mview_uc* vsip_mputcolstride_uc( vsip_mview_uc*, vsip_stride); vsip_mview_uc* vsip_mputcollength_uc( vsip_mview_uc*, vsip_length); vsip_mview_d* vsip_mputoffset_d( vsip_mview_d*, vsip_offset); vsip_mview_f* vsip_mputoffset_f( vsip_mview_f*, vsip_offset); vsip_mview_bl* vsip_mputoffset_bl( vsip_mview_bl*, vsip_offset); vsip_mview_i* vsip_mputoffset_i( vsip_mview_i*, vsip_offset); vsip_mview_li* vsip_mputoffset_li( vsip_mview_li*, vsip_offset); vsip_mview_si* vsip_mputoffset_si( vsip_mview_si*, vsip_offset); vsip_mview_f* vsip_mputrowlength_f( vsip_mview_f*, vsip_length); vsip_mview_d* vsip_mputrowlength_d( vsip_mview_d*, vsip_length); vsip_mview_bl* vsip_mputrowlength_bl( vsip_mview_bl*, vsip_length); vsip_mview_li* vsip_mputrowlength_li( vsip_mview_li*, vsip_length); vsip_mview_si* vsip_mputrowlength_si( vsip_mview_si*, vsip_length); vsip_mview_i* vsip_mputrowlength_i( vsip_mview_i*, vsip_length); vsip_mview_bl* vsip_msubview_bl( const vsip_mview_bl*, vsip_index, vsip_index, vsip_length, vsip_length); vsip_mview_i* vsip_msubview_i( const vsip_mview_i*, vsip_index, vsip_index, vsip_length, vsip_length); vsip_mview_li* vsip_msubview_li( const vsip_mview_li*, vsip_index, vsip_index, vsip_length, vsip_length); vsip_mview_si* vsip_msubview_si( const vsip_mview_si*, vsip_index, vsip_index, vsip_length, vsip_length); vsip_mview_uc* vsip_msubview_uc( const vsip_mview_uc*, vsip_index, vsip_index, vsip_length, vsip_length); vsip_tview_d* vsip_tcloneview_d( const vsip_tview_d*); vsip_tview_f* vsip_tcloneview_f( const vsip_tview_f*); vsip_tview_i* vsip_tcloneview_i( const vsip_tview_i*); vsip_tview_li* vsip_tcloneview_li( const vsip_tview_li*); vsip_tview_si* vsip_tcloneview_si( const vsip_tview_si*); vsip_tview_uc* vsip_tcloneview_uc( const vsip_tview_uc*); vsip_tview_f* vsip_tcreate_f( vsip_length, vsip_length, vsip_length, vsip_tmajor, vsip_memory_hint); vsip_tview_d* vsip_tcreate_d( vsip_length, vsip_length, vsip_length, vsip_tmajor, vsip_memory_hint); vsip_tview_i* vsip_tcreate_i( vsip_length, vsip_length, vsip_length, vsip_tmajor, vsip_memory_hint); vsip_tview_li* vsip_tcreate_li( vsip_length, vsip_length, vsip_length, vsip_tmajor, vsip_memory_hint); vsip_tview_si* vsip_tcreate_si( vsip_length, vsip_length, vsip_length, vsip_tmajor, vsip_memory_hint); vsip_tview_uc* vsip_tcreate_uc( vsip_length, vsip_length, vsip_length, vsip_tmajor, vsip_memory_hint); vsip_tview_f* vsip_tputoffset_f ( vsip_tview_f*, vsip_offset); vsip_tview_d* vsip_tputoffset_d ( vsip_tview_d*, vsip_offset); vsip_tview_f* vsip_tputxstride_f( vsip_tview_f*, vsip_stride); vsip_tview_d* vsip_tputxstride_d( vsip_tview_d*, vsip_stride); vsip_tview_i* vsip_tputxstride_i( vsip_tview_i*, vsip_stride); vsip_tview_li* vsip_tputxstride_li( vsip_tview_li*, vsip_stride); vsip_tview_si* vsip_tputxstride_si( vsip_tview_si*, vsip_stride); vsip_tview_uc* vsip_tputxstride_uc( vsip_tview_uc*, vsip_stride); vsip_tview_f* vsip_tputylength_f( vsip_tview_f*, vsip_length); vsip_tview_d* vsip_tputylength_d( vsip_tview_d*, vsip_length); vsip_tview_i* vsip_tputylength_i( vsip_tview_i*, vsip_length); vsip_tview_li* vsip_tputylength_li( vsip_tview_li*, vsip_length); vsip_tview_si *vsip_tputylength_si( vsip_tview_si*, vsip_length); vsip_tview_uc *vsip_tputylength_uc( vsip_tview_uc*, vsip_length); vsip_tview_f *vsip_tputzlength_f( vsip_tview_f*, vsip_length); vsip_tview_d *vsip_tputzlength_d( vsip_tview_d*, vsip_length); vsip_tview_i *vsip_tputzlength_i( vsip_tview_i*, vsip_length); vsip_tview_li *vsip_tputzlength_li( vsip_tview_li*, vsip_length); vsip_tview_si *vsip_tputzlength_si( vsip_tview_si*, vsip_length); vsip_tview_uc *vsip_tputzlength_uc( vsip_tview_uc*, vsip_length); void vsip_vinterp_linear_d( const vsip_vview_d *, const vsip_vview_d *, const vsip_vview_d *, const vsip_vview_d *); vsip_vview_si* vsip_vputattrib_si( vsip_vview_si*, const vsip_vattr_si*); vsip_mview_i* vsip_mputcollength_i( vsip_mview_i*, vsip_length); vsip_mview_li* vsip_mputcollength_li( vsip_mview_li*, vsip_length); vsip_mview_f* vsip_mputcolstride_f( vsip_mview_f*, vsip_stride); vsip_mview_si* vsip_mputrowstride_si( vsip_mview_si*, vsip_stride); vsip_mview_si* vsip_mputcolstride_si( vsip_mview_si*, vsip_stride); vsip_mview_i* vsip_mputrowstride_i( vsip_mview_i*, vsip_stride); vsip_mview_li* vsip_mputrowstride_li( vsip_mview_li*, vsip_stride); vsip_mview_bl* vsip_mputrowstride_bl( vsip_mview_bl*, vsip_stride); vsip_mview_d* vsip_mputrowstride_d( vsip_mview_d*, vsip_stride); vsip_mview_f* vsip_mputrowstride_f( vsip_mview_f*, vsip_stride); vsip_mview_i* vsip_mputcolstride_i( vsip_mview_i*, vsip_stride); vsip_mview_li* vsip_mputcolstride_li( vsip_mview_li*, vsip_stride); void vsip_cvfreqswap_d( const vsip_cvview_d*); void vsip_vfreqswap_d( const vsip_vview_d*); void vsip_cmfreqswap_d( const vsip_cmview_d*); void vsip_mfreqswap_d( const vsip_mview_d*); void vsip_cvfreqswap_f( const vsip_cvview_f*); void vsip_vfreqswap_f( const vsip_vview_f*); void vsip_cmfreqswap_f( const vsip_cmview_f*); void vsip_mfreqswap_f( const vsip_mview_f*); /* jvsip developement */ typedef struct vsip_svd vsip_sv_f; typedef struct vsip_svd vsip_csv_f; int vsip_svd_destroy_f(vsip_sv_f* ); vsip_sv_f * vsip_svd_create_f(vsip_length , vsip_length , vsip_svd_uv , vsip_svd_uv ); int vsip_svd_f(vsip_sv_f *, const vsip_mview_f *, vsip_vview_f *); void vsip_svd_getattr_f(const vsip_sv_f *, vsip_sv_attr_f *); int vsip_svdprodu_f(const vsip_sv_f*, vsip_mat_op, vsip_mat_side, const vsip_mview_f*); int vsip_svdprodv_f(const vsip_sv_f*, vsip_mat_op, vsip_mat_side, const vsip_mview_f*); int vsip_svdmatu_f(const vsip_sv_f*, vsip_scalar_vi, vsip_scalar_vi, const vsip_mview_f*); int vsip_svdmatv_f(const vsip_sv_f*, vsip_scalar_vi, vsip_scalar_vi, const vsip_mview_f*); /* Complex */ vsip_csv_f * vsip_csvd_create_f(vsip_length, vsip_length, vsip_svd_uv, vsip_svd_uv); int vsip_csvd_destroy_f(vsip_csv_f* svd); int vsip_csvd_f(vsip_csv_f*, const vsip_cmview_f*, vsip_vview_f *s); void vsip_csvd_getattr_f(const vsip_csv_f*, vsip_csv_attr_f*); int vsip_csvdprodu_f(const vsip_csv_f*, vsip_mat_op, vsip_mat_side, const vsip_cmview_f*); int vsip_csvdprodv_f(const vsip_csv_f*, vsip_mat_op, vsip_mat_side,const vsip_cmview_f*); int vsip_csvdmatu_f(const vsip_csv_f*, vsip_scalar_vi, vsip_scalar_vi, const vsip_cmview_f*); int vsip_csvdmatv_f(const vsip_csv_f*, vsip_scalar_vi, vsip_scalar_vi, const vsip_cmview_f*); typedef struct vsip_svd vsip_sv_d; typedef struct vsip_svd vsip_csv_d; int vsip_svd_destroy_d(vsip_sv_d* ); vsip_sv_d * vsip_svd_create_d(vsip_length , vsip_length , vsip_svd_uv , vsip_svd_uv ); int vsip_svd_d(vsip_sv_d *, const vsip_mview_d *, vsip_vview_d *); void vsip_svd_getattr_d(const vsip_sv_d *, vsip_sv_attr_d *); int vsip_svdprodu_d(const vsip_sv_d*, vsip_mat_op, vsip_mat_side, const vsip_mview_d*); int vsip_svdprodv_d(const vsip_sv_d*, vsip_mat_op, vsip_mat_side, const vsip_mview_d*); int vsip_svdmatu_d(const vsip_sv_d*, vsip_scalar_vi, vsip_scalar_vi, const vsip_mview_d*); int vsip_svdmatv_d(const vsip_sv_d*, vsip_scalar_vi, vsip_scalar_vi, const vsip_mview_d*); /* Complex */ vsip_csv_d * vsip_csvd_create_d(vsip_length, vsip_length, vsip_svd_uv, vsip_svd_uv); int vsip_csvd_destroy_d(vsip_csv_d* svd); int vsip_csvd_d(vsip_csv_d*, const vsip_cmview_d*, vsip_vview_d *s); void vsip_csvd_getattr_d(const vsip_csv_d*, vsip_csv_attr_d*); int vsip_csvdprodu_d(const vsip_csv_d*, vsip_mat_op, vsip_mat_side, const vsip_cmview_d*); int vsip_csvdprodv_d(const vsip_csv_d*, vsip_mat_op, vsip_mat_side,const vsip_cmview_d*); int vsip_csvdmatu_d(const vsip_csv_d*, vsip_scalar_vi, vsip_scalar_vi, const vsip_cmview_d*); int vsip_csvdmatv_d(const vsip_csv_d*, vsip_scalar_vi, vsip_scalar_vi, const vsip_cmview_d*); /* swift function helpers (break VSIPL rules for library) */ double* vsipUnsafeBlockPtr_d(vsip_block_d*, vsip_stride*); float* vsipUnsafeBlockPtr_f(vsip_block_f*, vsip_stride*); double* vsipUnsafeBlockPtr_cdR(vsip_cblock_d*, vsip_stride*); float* vsipUnsafeBlockPtr_cfR(vsip_cblock_f*, vsip_stride*); double* vsipUnsafeBlockPtr_cdI(vsip_cblock_d*, vsip_stride*); float* vsipUnsafeBlockPtr_cfI(vsip_cblock_f*, vsip_stride*); #endif <file_sep>/* Created RJudd January 4, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cvexpoavg_f.c,v 2.0 2003/02/22 15:18:50 judd Exp $ */ /* Modified RJudd June 28, 1998 */ /* to add complex block support */ /* Removed Development Mode RJudd Sept 00 */ #include"vsip.h" #include"vsip_cvviewattributes_f.h" void (vsip_cvexpoavg_f)( vsip_scalar_f alpha, const vsip_cvview_f* b, const vsip_cvview_f* c) { { /* register */ vsip_length n = c->length; vsip_stride cbst = b->block->cstride, ccst = c->block->cstride; vsip_scalar_f *bpr = (vsip_scalar_f*) ((b->block->R->array) + cbst * b->offset), *cpr = (vsip_scalar_f*) ((c->block->R->array) + ccst * c->offset); vsip_scalar_f *bpi = (vsip_scalar_f*) ((b->block->I->array) + cbst * b->offset), *cpi = (vsip_scalar_f*) ((c->block->I->array) + ccst * c->offset); /* register */ vsip_stride bst = (cbst * b->stride), cst = (ccst * c->stride); while(n-- > 0){ *cpr = alpha * *bpr + (1 - alpha) * *cpr; *cpi = alpha * *bpi + (1 - alpha) * *cpi; bpr += bst; bpi += bst; cpr += cst; cpi += cst; } } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mminval_f.h,v 2.0 2003/02/22 15:23:26 judd Exp $ */ #include"VU_mprintm_f.include" static void mminval_f(void){ printf("\n*******\nTEST mminval_f\n\n"); { vsip_scalar_f data1[] = {-1, 2, 0, -5, -6, 3.4, -3.4, 5.6, -.3}; vsip_block_f *block1 = vsip_blockbind_f(data1,9,VSIP_MEM_NONE); vsip_mview_f *a = vsip_mbind_f(block1,0,3,3,1,3); vsip_block_f *block2 = vsip_blockcreate_f(50,VSIP_MEM_NONE); vsip_mview_f *b = vsip_mbind_f(block2,49,-2,3,-8,3); vsip_scalar_mi index; vsip_scalar_mi ind_ans = vsip_matindex(1,1); vsip_scalar_f val; vsip_blockadmit_f(block1,VSIP_TRUE); vsip_mcopy_f_f(a,b); val = vsip_mminval_f(a,&index); printf("val = vsip_mminval_f(a,index)\n matrix a = \n");VU_mprintm_f("8.6",a); printf("val = %f\n",val); printf("index = (%ld, %ld)\n",vsip_colindex(index),vsip_rowindex(index)); if(fabs(-6 - val) > .0001) printf("value error\n"); else printf("value correct\n"); if((vsip_colindex(index) != vsip_colindex(ind_ans)) || (vsip_rowindex(index) != vsip_rowindex(ind_ans))) printf("index error\n"); else printf("index correct\n"); printf("case for non-compact matrix with negative strides\n"); val = vsip_mminval_f(b,&index); printf("val = vsip_mminval_f(b,index)\n matrix b = \n");VU_mprintm_f("8.6",b); printf("val = %f\n",val); printf("index = (%ld, %ld)\n",vsip_colindex(index),vsip_rowindex(index)); if(fabs(-6 - val) > .0001) printf("value error\n"); else printf("value correct\n"); if((vsip_colindex(index) != vsip_colindex(ind_ans)) || (vsip_rowindex(index) != vsip_rowindex(ind_ans))) printf("index error\n"); else printf("index correct\n"); vsip_malldestroy_f(a); vsip_malldestroy_f(b); } return; } <file_sep>// // scalar.cpp // cppJvsip // // Created by <NAME> on 4/21/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #include "scalar.h" //constructors jvsip::Scalar::Scalar(float in){ p="f"; d="r"; s="scalar"; rvalue.re_f=in; cvalue.im_f=0.0f; } jvsip::Scalar::Scalar(double in){ p="d"; d="r"; s="scalar"; rvalue.re_d=in; cvalue.im_d=0.0; } jvsip::Scalar::Scalar(vsip_cscalar_f in){ p="f"; d="c"; s="scalar"; rvalue.re_f=in.r; cvalue.im_f=in.i; } jvsip::Scalar::Scalar(vsip_cscalar_d in){ p="d"; d="c"; s="scalar"; rvalue.re_d=in.r; cvalue.im_d=in.i; } jvsip::Scalar::Scalar(vsip_scalar_i in){ p="i"; d="r"; s="scalar"; rvalue.i=in; } jvsip::Scalar::Scalar(vsip_scalar_vi in){ p="vi"; d="r"; s="scalar"; rvalue.vi=in; } jvsip::Scalar::Scalar(vsip_stride in){ p="l"; d="r"; s="scalar"; rvalue.stride=in; } //getters float jvsip::Scalar::scalar_f() const { assert (this->depth()=="r"); if (this->precision()=="f") { return this->rvalue.re_f; } else if (this->precision()=="d"){ return (float)this->rvalue.re_d; } else if (this->precision()=="i"){ return (float) this->rvalue.i; } else if (this->precision()=="vi"){ return (float) this->rvalue.vi; } else return 0.0f/0.0f; } double jvsip::Scalar::scalar_d() const{ assert (this->depth()=="r"); if (this->precision()=="f") { return (double)this->rvalue.re_f; } else if (this->precision()=="d"){ return (double)this->rvalue.re_d; } else if (this->precision()=="i"){ return (double) this->rvalue.i; } else if (this->precision()=="vi"){ return (double) this->rvalue.vi; } else return 0.0f/0.0f; } vsip_scalar_i jvsip::Scalar::scalar_i() const{ assert (this->depth()=="r"); if (this->precision()=="f") { return (vsip_scalar_i)this->rvalue.re_f; } else if (this->precision()=="d"){ return (vsip_scalar_i)this->rvalue.re_d; } else if (this->precision()=="i"){ return (vsip_scalar_i) this->rvalue.i; } else if (this->precision()=="vi"){ return (vsip_scalar_i) this->rvalue.vi; } else return 0.0f/0.0f; } vsip_scalar_vi jvsip::Scalar::scalar_vi() const{ assert (this->depth()=="r"); if (this->precision()=="f") { return (vsip_scalar_vi)this->rvalue.re_f; } else if (this->precision()=="d"){ return (vsip_scalar_vi)this->rvalue.re_d; } else if (this->precision()=="i"){ return (vsip_scalar_vi) this->rvalue.i; } else if (this->precision()=="vi"){ return (vsip_scalar_vi) this->rvalue.vi; } else return 0.0f/0.0f; } vsip_cscalar_f jvsip::Scalar::scalar_cf() const{ assert(this->depth()=="c"); float re=0.0,im=0.0; if (this->precision()=="f") { re=this->rvalue.re_f;im = this->cvalue.im_f; }else if (this->precision()=="d"){ re=(float)this->rvalue.re_d;im = (float)this->cvalue.im_d; } return vsip_cmplx_f(re, im); } vsip_cscalar_d jvsip::Scalar::scalar_cd() const{ assert(this->depth()=="c"); double re=0.0,im=0.0; if (this->precision()=="f") { re= (double)this->rvalue.re_f;im = (double)this->cvalue.im_f; }else if (this->precision()=="d"){ re=this->rvalue.re_d;im = this->cvalue.im_d; } return vsip_cmplx_d(re, im); } vsip_stride jvsip::Scalar::stride() const{ if (this->precision()=="f") { return (vsip_length)this->rvalue.re_f; } else if (this->precision()=="d"){ return (vsip_length)this->rvalue.re_d; } else if (this->precision()=="i"){ return (vsip_length) this->rvalue.i; } else if (this->precision()=="vi"){ return (vsip_length) this->rvalue.vi; }else if(this->precision()=="l"){ return this->rvalue.stride; } else return 0.0f/0.0f; } std::ostream &operator<<(std::ostream &output, const jvsip::Scalar &in){ std::string prec = in.precision(); if(prec=="f") { output << in.scalar_f(); } else if(prec=="d"){ output << in.scalar_d(); } else if(prec=="i"){ output << in.scalar_i(); } else if(prec=="vi"){ output << in.scalar_vi(); } else output << 0.0/0.0; return output; } <file_sep>#include<vsip.h> #include<math.h> #include<assert.h> void mview_store_d(vsip_mview_d *M, char* fname) { vsip_length RL = vsip_mgetrowlength_d(M); vsip_length CL = vsip_mgetcollength_d(M); FILE *of = fopen(fname,"w"); vsip_length row,col; fprintf(of,"%s\n%ld %ld\n","mview_d",CL,RL); for(row = 0; row<CL; row++) for(col=0; col<RL; col++) fprintf(of,"%ld %ld %e\n", row,col,vsip_mget_d(M,row,col)); fclose(of); return; } vsip_mview_d *mcenter_d(vsip_mview_d *gram) { vsip_index i; vsip_length cl=vsip_mgetcollength_d(gram), rl=vsip_mgetrowlength_d(gram); vsip_stride rs=vsip_mgetrowstride_d(gram), cs=vsip_mgetcolstride_d(gram); vsip_offset o = vsip_mgetoffset_d(gram); assert(rs == 1); assert(cs == (vsip_stride)rl); if (cl & 1){ // odd use freqswap for each column vsip_vview_d *v=vsip_mcolview_d(gram,0); for(i=0; i<rl; i++){ vsip_vfreqswap_d(v); o += cs; vsip_vputoffset_d(v,o); } vsip_vdestroy_d(v); } else { // even number of columns use trick vsip_length lngth = (vsip_length)(cl * rl/2); vsip_vview_d *v1=vsip_mrowview_d(gram,0),*v2; vsip_vputlength_d(v1,lngth); v2=vsip_vcloneview_d(v1); vsip_vputoffset_d(v2,o+lngth); vsip_vswap_d(v1,v2); vsip_vdestroy_d(v1); vsip_vdestroy_d(v2); } return gram; } vsip_mview_d *cmscale_d(vsip_cmview_d *gram_data) { vsip_scalar_mi indx; vsip_length M = vsip_cmgetcollength_d(gram_data); vsip_length N = vsip_cmgetrowlength_d(gram_data); vsip_mview_d *gram = vsip_mcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mcmagsq_d(gram_data,gram); vsip_smadd_d(1.0-vsip_mminval_d(gram,&indx),gram, gram); vsip_mlog10_d(gram,gram); vsip_smmul_d(256.0/vsip_mmaxval_d(gram,&indx),gram,gram); return mcenter_d(gram); } vsip_mview_d *noiseGen( vsip_scalar_d alpha, vsip_length Mp, vsip_length Nn, vsip_length Ns) { vsip_index i,j; vsip_scalar_d kaiser=9.0; vsip_length Nfilter=10, Nnoise=64; vsip_scalar_d cnst1=M_PI/(vsip_scalar_d)Nnoise; vsip_offset offset0 = (vsip_offset)(alpha * Mp + 1); vsip_vview_d *kernel=vsip_vcreate_kaiser_d(Nfilter,kaiser,VSIP_MEM_NONE); vsip_mview_d *data=vsip_mcreate_d(Mp,Ns,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *noise=vsip_mcreate_d(Mp,Nn,VSIP_ROW,VSIP_MEM_NONE); vsip_vview_d *nv = vsip_vcreate_d(2 * Nn,VSIP_MEM_NONE); vsip_fir_d *fir = \ vsip_fir_create_d(kernel,VSIP_NONSYM,2*Nn,2,VSIP_STATE_SAVE,0,0); vsip_randstate *state = vsip_randcreate(15,1,1,VSIP_PRNG); vsip_mfill_d(0.0,data); for(j=0; j<Nnoise; j++){ vsip_vview_d *noise_j=vsip_mrowview_d(noise,j); vsip_vrandn_d(state,nv); vsip_firflt_d(fir,nv,noise_j); vsip_svmul_d(12.0/(float)Nnoise,noise_j,noise_j); vsip_vdestroy_d(noise_j); } vsip_mputrowlength_d(noise,Ns); for(i=0; i<Mp; i++){//for each sensor vsip_vview_d *data_v = vsip_mrowview_d(data,i); for(j=0; j<Nnoise; j++){//for each noise direction vsip_vview_d *noise_j = vsip_mrowview_d(noise,j); vsip_vputoffset_d(noise_j,offset0 +(int)( i * alpha * cos(j * cnst1))); vsip_vadd_d(noise_j,data_v,data_v); vsip_vdestroy_d(noise_j); } vsip_vdestroy_d(data_v); } vsip_valldestroy_d(kernel); vsip_valldestroy_d(nv); vsip_malldestroy_d(noise); return data; } vsip_mview_d *narrowBandGen( vsip_mview_d *data, vsip_scalar_d alpha, void **targets, vsip_scalar_d Fs) { vsip_index i,j; vsip_length M=vsip_mgetcollength_d(data); vsip_length N = vsip_mgetrowlength_d(data); vsip_vview_d *t = vsip_vcreate_d(N,VSIP_MEM_NONE); vsip_vview_d *tt= vsip_vcreate_d(N,VSIP_MEM_NONE); vsip_mview_d *Xim = vsip_mcreate_d(M,M+1,VSIP_ROW,VSIP_MEM_NONE); vsip_vview_d *m = vsip_vcreate_d(M,VSIP_MEM_NONE); vsip_vview_d *Xi = vsip_vcreate_d(M + 1,VSIP_MEM_NONE); vsip_vview_d *freq=(vsip_vview_d*)targets[0]; vsip_vview_vi *bearing=(vsip_vview_vi*)targets[1]; vsip_vview_d *scale=(vsip_vview_d*)targets[2]; vsip_vramp_d(0.0,1.0,t); vsip_vramp_d(0.0,M_PI/(vsip_scalar_d)M,Xi); vsip_vcos_d(Xi,Xi); vsip_vramp_d(0,1.0,m); vsip_vouter_d(alpha,m,Xi,Xim); for(i=0; i<M; i++){//for each sensor vsip_vview_d *data_v = vsip_mrowview_d(data,i); for(j=0; j<vsip_vgetlength_d(freq); j++){//for each noise direction vsip_scalar_d f=vsip_vget_d(freq,j); vsip_scalar_d w0=vsip_vget_d(freq,j) * 2.0 * M_PI/(vsip_scalar_d)Fs; vsip_index Theta=vsip_vget_vi(bearing,j); vsip_scalar_d sc = vsip_vget_d(scale,j); vsip_scalar_d Xim_val = vsip_mget_d(Xim,i,Theta); vsip_vsmsa_d(t,w0,-w0*Xim_val,tt); vsip_vcos_d(tt,tt); vsip_svmul_d(sc,tt,tt); vsip_vadd_d(tt,data_v,data_v); } vsip_vdestroy_d(data_v); } vsip_valldestroy_d(tt); vsip_valldestroy_d(t); vsip_valldestroy_d(m); vsip_malldestroy_d(Xim); vsip_valldestroy_d(Xi); return data; } <file_sep>/* Created RJudd March 18, 2012 */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"vsip.h" #include"vsip_mviewattributes_d.h" #include"vsip_vviewattributes_d.h" #include"vsip_cmviewattributes_d.h" #include"vsip_cvviewattributes_d.h" #include"vsip_scalars.h" #include"VI_mrowview_d.h" #include"VI_mcolview_d.h" #include"VI_cmrowview_d.h" #include"VI_cmcolview_d.h" static void vpolar_d(const vsip_cvview_d* a, const vsip_vview_d* r, const vsip_vview_d* t) { vsip_length n = r->length; vsip_stride cast = a->block->cstride, rrst = r->block->rstride, trst = t->block->rstride; vsip_scalar_d *apr = (vsip_scalar_d*) ((a->block->R->array) + cast * a->offset), *rp = (vsip_scalar_d*) ((r->block->array) + rrst * r->offset), *tp = (vsip_scalar_d*) ((t->block->array) + trst * t->offset); vsip_scalar_d *api = (vsip_scalar_d*) ((a->block->I->array) + cast * a->offset); vsip_scalar_d tmp; vsip_stride ast = (cast * a->stride), rst = rrst * r->stride, tst = trst * t->stride; while(n-- > 0){ tmp = (vsip_scalar_d)atan2(*api,*apr); *rp = (vsip_scalar_d)sqrt(*apr * *apr + *api * *api); *tp = tmp; apr += ast; api += ast; rp += rst; tp += tst; } } void vsip_mpolar_d(const vsip_cmview_d* a, const vsip_mview_d* r, const vsip_mview_d* t){ vsip_index i; vsip_vview_d rv; vsip_vview_d tv; vsip_cvview_d av; if(a->row_stride < a->col_stride){ for(i=0; i < a->col_length; i++){ VI_mrowview_d(r,i,&rv); VI_mrowview_d(t,i,&tv);VI_cmrowview_d(a,i,&av); vpolar_d(&av,&rv,&tv); } } else { for(i=0; i < a->col_length; i++){ VI_mcolview_d(r,i,&rv); VI_mcolview_d(t,i,&tv);VI_cmcolview_d(a,i,&av); vpolar_d(&av,&rv,&tv); } } } <file_sep>/* Created RJudd September 16, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cblockadmit_f.c,v 2.1 2006/06/08 22:19:26 judd Exp $ */ #include"vsip.h" #include"vsip_cblockattributes_f.h" int (vsip_cblockadmit_f)( vsip_cblock_f* b, vsip_scalar_bl update) { int blockadmit = (int)update; /* keep update from warning since don't use */ #if defined(VSIP_DEFAULT_SPLIT) #include"VI_cblockadmit_f_ds.h" #elif defined(VSIP_ALWAYS_SPLIT) #include"VI_cblockadmit_f_as.h" #elif defined(VSIP_ALWAYS_INTERLEAVED) #include"VI_cblockadmit_f_ai.h" #else #include"VI_cblockadmit_f_di.h" #endif return blockadmit; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: varg_f.h,v 2.0 2003/02/22 15:23:28 judd Exp $ */ #include"VU_vprintm_f.include" #include"VU_cvprintm_f.include" static void varg_f(void){ printf("\n*****\nTEST varg_f\n"); { vsip_cvview_f *a = vsip_cvcreate_f(22,VSIP_MEM_NONE); vsip_cvview_f *b = vsip_cvsubview_f(a,2,6); vsip_vview_f *chk = vsip_vcreate_f(6,VSIP_MEM_NONE); vsip_vview_f *b_r, *b_i; vsip_vview_f *arg = vsip_vcreate_f(6,VSIP_MEM_NONE); vsip_scalar_f data[] = {1.5708, 1.4601, 1.3258, 1.1659, .9828, .7854}; vsip_block_f *block = vsip_blockbind_f(data,6,VSIP_MEM_NONE); vsip_vview_f *ans = vsip_vbind_f(block,0,1,6); vsip_blockadmit_f(block,VSIP_TRUE); vsip_cvputstride_f(b,2); b_r = vsip_vrealview_f(b); b_i = vsip_vimagview_f(b); vsip_vramp_f(0,.1,b_r); vsip_vramp_f(1,-.1,b_i); printf("input vector\n"); VU_cvprintm_f("8.6",b); vsip_varg_f(b,arg); printf("varg_f(b,arg)\n"); VU_vprintm_f("8.6",arg); printf("answer to 4 digits\n"); VU_vprintm_f("8.4",ans); vsip_vsub_f(arg,ans,chk); vsip_vmag_f(chk,chk); if(vsip_vsumval_f(chk) > .0006) printf("error\n"); else printf("correct\n"); vsip_cvdestroy_f(b); vsip_vdestroy_f(b_i); vsip_vdestroy_f(b_r); vsip_cvalldestroy_f(a); vsip_valldestroy_f(arg); vsip_valldestroy_f(ans); vsip_valldestroy_f(chk); } return; } <file_sep>/* Created <NAME> */ /* Copyright (c) 2006 <NAME> */ /* MIT style license, see Copyright notice in top level directory */ #include"VU_cmprintm_f.include" static int ccovsol_f(void) { vsip_cmview_f *A = vsip_cmcreate_f(10,6,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *BX = vsip_cmcreate_f(10,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *X = vsip_cmcreate_f(6,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *ANS = vsip_cmcreate_f(6,3,VSIP_ROW,VSIP_MEM_NONE); /* create space for ccovsol data */ vsip_cblock_f *ablock = vsip_cblockcreate_f(500,VSIP_MEM_NONE); vsip_cmview_f *A1 = vsip_cmbind_f(ablock,200,-3,10,-31,6); vsip_cscalar_f a0 = vsip_cmplx_f(0.0,0.0); int i; vsip_cmfill_f(a0,A); vsip_cmfill_f(a0,BX); printf("********\nTEST ccovsol_f\n"); printf("Test covariance solver vsip_ccovsol_f\n"); /* Solving for X in A X = B */ /* A is (M,N) M >= N; X is (N,K), B is (N,K) */ /* need to make up some data */ /* data for matrix A */ for(i=0; i<vsip_cmgetrowlength_f(A); i++){ /* fill by column */ vsip_cvview_f *ac = vsip_cmcolview_f(A,i); vsip_vview_f *ac_r = vsip_vrealview_f(ac); vsip_vview_f *ac_i = vsip_vimagview_f(ac); vsip_vramp_f(-1.3,1.1,ac_r); vsip_vramp_f(+1.3,-1.1,ac_i); vsip_vdestroy_f(ac_r); vsip_vdestroy_f(ac_i); vsip_cvdestroy_f(ac); } { /* make sure diagonal keeps things stable */ vsip_cvview_f *ad = vsip_cmdiagview_f(A,0); vsip_vview_f *ad_r = vsip_vrealview_f(ad); vsip_vview_f *ad_i = vsip_vimagview_f(ad); vsip_vramp_f(3,1.2,ad_r); vsip_vramp_f(3,-1.2,ad_i); vsip_vdestroy_f(ad_r); vsip_vdestroy_f(ad_i); vsip_cvdestroy_f(ad); } /* Data for matrix B */ for(i=0; i<vsip_cmgetcollength_f(BX); i++){ /* fill by row */ vsip_cvview_f *bxr = vsip_cmrowview_f(BX,i); vsip_vview_f *bxr_r = vsip_vrealview_f(bxr); vsip_vview_f *bxr_i = vsip_vimagview_f(bxr); vsip_vramp_f(0.1,(vsip_scalar_f)i/3.0,bxr_r); vsip_vramp_f(0.1,(vsip_scalar_f)i/4.0,bxr_i); vsip_vdestroy_f(bxr_r);vsip_vdestroy_f(bxr_i); vsip_cvdestroy_f(bxr); } printf("Input data \n"); printf("A = ");VU_cmprintm_f("4.2",A); printf("\nB = ");VU_cmprintm_f("4.2",BX); { vsip_cchol_f *chol = vsip_cchold_create_f(VSIP_TR_LOW,6); vsip_cmview_f *B = vsip_cmcreate_f(6,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *AHA = vsip_cmcreate_f(6,6,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *AH = vsip_cmcreate_f(6,10,VSIP_ROW,VSIP_MEM_NONE); /* solve using Cholesky and AHA matrix */ printf("\nSolve using Cholesky"); printf("\nA is input matrix, AT (AH) is transpose (Hermitian) of A\n"); printf("Solve for X least squares using (AH prod A ) prod X = AH prod B\n"); /* calculate matrix AHA = AH * A */ vsip_cmherm_f(A,AH); vsip_cmprod_f(AH,A,AHA); /* calculate AH * B */ vsip_cmprod_f(AH,BX,X); printf("\nAH prod A = ");VU_cmprintm_f("4.2",AHA); printf("\nAH prod B = ");VU_cmprintm_f("4.2",X); vsip_cchold_f(chol,AHA); vsip_ccholsol_f(chol,X);/* B replaced by X */ printf("\nX = ");VU_cmprintm_f("7.5",X); vsip_cchold_destroy_f(chol); /* check */ printf("\ncheck\n (AH prod A) prod X := AH prod B"); /* restore AHA */ vsip_cmprod_f(AH,A,AHA); /* calculate AHA prod X */ vsip_cmprod_f(AHA,X,B); vsip_cmcopy_f_f(X,ANS); /* if correct Need ANSwer */ /* for check place AH * BX into X */ vsip_cmprod_f(AH,BX, X); printf("\nAHA * X ="); VU_cmprintm_f("4.2",B); vsip_cmsub_f(X,B,X); { float check = (float) vsip_cmmeansqval_f(X); if(fabs(check) < .0001) printf("check = %f\ncorrect\n",check); else printf("check = %f\nerror\n",check); } /* restore X for use by covsol */ vsip_cmprod_f(AH,BX, X); vsip_cmalldestroy_f(B); vsip_cmalldestroy_f(AHA); vsip_cmalldestroy_f(AH); } /* solve using ccovsol */ /* copy data so we can solve covariance problem later on */ vsip_cmcopy_f_f(A,A1); printf("\nSolve using ccovsol_f "); vsip_ccovsol_f(A1,X); printf("Expect X to be\n");VU_cmprintm_f("7.5",ANS); printf("\nX = ");VU_cmprintm_f("7.5",X); vsip_cmsub_f(ANS,X,X); { float check = (float) vsip_cmmeansqval_f(X); if(fabs(check) < .0001) printf("check = %f\ncorrect\n",check); else printf("check = %f\nerror\n",check); } vsip_cmdestroy_f(A1); vsip_cblockdestroy_f(ablock); vsip_cmalldestroy_f(A); vsip_cmalldestroy_f(BX); vsip_cmalldestroy_f(X); return 0; } <file_sep>/* Created RJudd October 14, 2000 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_clog_f.c,v 2.0 2003/02/22 15:18:41 judd Exp $ */ #include"vsip.h" vsip_cscalar_f (vsip_clog_f)( vsip_cscalar_f x) { vsip_cscalar_f a; vsip_scalar_f s = ((x.r > 0) ? x.r: -x.r) + ((x.i >0) ? x.i: -x.i); vsip_scalar_f ss = s * s; if(s == 0){ a.i = VSIP_MAX_SCALAR_F; a.r = VSIP_MAX_SCALAR_F; } else if(x.i == 0){ a.i = (vsip_scalar_f)((x.r < 0) ? M_PI : 0); a.r = (vsip_scalar_f)log((x.r < 0) ? -x.r : x.r); } else { a.i = (vsip_scalar_f)atan2(x.i,x.r); a.r = (vsip_scalar_f)log( s * sqrt((x.r * x.r)/ss + (x.i * x.i)/ss)); } return a; } <file_sep>/* Created RJudd November 22, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cmkron_f.c,v 2.1 2006/06/08 22:19:26 judd Exp $ */ #include"vsip.h" #include"vsip_cvviewattributes_f.h" #include"vsip_cmviewattributes_f.h" static void VI_csmmul_f( vsip_cscalar_f a, const vsip_cmview_f *b, const vsip_cmview_f *r) { { vsip_length n_mj, /* major length */ n_mn; /* minor length */ vsip_stride bst_mj, bst_mn, rst_mj, rst_mn; vsip_scalar_f *bp_r = (b->block->R->array) + b->offset * b->block->cstride, *rp_r = (r->block->R->array) + r->offset * r->block->cstride; vsip_scalar_f *bp_i = (b->block->I->array) + b->offset * b->block->cstride, *rp_i = (r->block->I->array) + r->offset * r->block->cstride; vsip_scalar_f *bp0_r = bp_r, *rp0_r = rp_r; vsip_scalar_f *bp0_i = bp_i, *rp0_i = rp_i; vsip_scalar_f temp; /* pick direction dependent on output */ if(r->row_stride < r->col_stride){ n_mj = r->row_length; n_mn = r->col_length; rst_mj = r->row_stride; rst_mn = r->col_stride; bst_mj = b->row_stride; bst_mn = b->col_stride; rst_mj *= r->block->cstride; rst_mn *= r->block->cstride; bst_mj *= b->block->cstride; bst_mn *= b->block->cstride; } else { n_mn = r->row_length; n_mj = r->col_length; rst_mn = r->row_stride; rst_mj = r->col_stride; bst_mn = b->row_stride; bst_mj = b->col_stride; rst_mn *= r->block->cstride; rst_mj *= r->block->cstride; bst_mn *= b->block->cstride; bst_mj *= b->block->cstride; } /* end define */ while(n_mn-- > 0){ vsip_length n = n_mj; while(n-- >0){ temp = a.r * *bp_r - a.i * *bp_i; *rp_i = a.r * *bp_i + a.i * *bp_r; *rp_r = temp; bp_r += bst_mj; rp_r += rst_mj; bp_i += bst_mj; rp_i += rst_mj; } bp0_r += bst_mn; rp0_r += rst_mn; bp_r = bp0_r; rp_r = rp0_r; bp0_i += bst_mn; rp0_i += rst_mn; bp_i = bp0_i; rp_i = rp0_i; } } return; } static vsip_cscalar_f VI_cmget_f( const vsip_cmview_f *v, vsip_index row, vsip_index col) { vsip_stride str = v->block->cstride * ( v->offset + row * v->col_stride + col * v->row_stride); vsip_cscalar_f retval; retval.r = *(v->block->R->array + str); retval.i = *(v->block->I->array + str); return retval; } static vsip_cscalar_f VI_cmul_f( vsip_cscalar_f x, vsip_cscalar_f y) { vsip_cscalar_f tmp; tmp.r = x.r * y.r - x.i * y.i; tmp.i = x.r * y.i + x.i * y.r; return tmp; } void vsip_cmkron_f( vsip_cscalar_f alpha, const vsip_cmview_f *x, const vsip_cmview_f *y, const vsip_cmview_f *c) { vsip_cmview_f C = *c; vsip_length y_row_length = y->row_length, x_row_length = x->row_length, y_col_length = y->col_length, x_col_length = x->col_length; vsip_offset c_offset = c->offset; /* c row is x_row * y_col_length, c col is x_col * y_row_length */ vsip_stride c_str_c = y_col_length * c->col_stride; vsip_stride c_str_r = y_row_length * c->row_stride; vsip_length i,j; C.row_length = y_row_length; C.col_length = y_col_length; for(i=0; i< x_col_length; i++){ for(j=0; j< x_row_length; j++){ C.offset = c_offset + i * c_str_c + j * c_str_r; VI_csmmul_f(VI_cmul_f(VI_cmget_f(x,i,j) , alpha),y,&C); } } return; } <file_sep>/* Created RJudd March 17, 2012 */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #ifndef _vsip_rcfirattributes_d_h #define _vsip_rcfirattributes_d_h #include"VI.h" struct vsip_rcfirattributes_d{ vsip_vview_d *h; vsip_cvview_d *s; vsip_length N; vsip_length M; vsip_length p; vsip_length D; int ntimes; vsip_symmetry symm; vsip_alg_hint hint; vsip_obj_state state; }; #endif /* _vsip_rcfirattributes_d_h */ <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmscatter_d.h,v 2.0 2003/02/22 15:23:21 judd Exp $ */ #include"VU_cmprintm_d.include" #include"VU_cvprintm_d.include" #include"VU_vprintm_mi.include" void cmscatter_d(void){ printf("\n******\nTEST cmscatter_d\n"); { vsip_scalar_d data1_r[]= {1, .1, 2, .2, 3,.3, 4,-.1, 5, -.3, 6,-.4, 7,.8, 8,.9, 9,-1}; vsip_scalar_d data1_i[]= {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,13,14,15,16,17,18}; vsip_scalar_vi data_index[] = {0,1 , 1,1 , 2,3 , 3,3 , 2,1}; vsip_scalar_d data_ans_r[] = { 0.0, -1.0, 0.0, 0.0, 0.0, 0.9, 0.0, 0.0, 0.0, -.3, 0.0, 0.8, 0.0, 0.0, 0.0, -.4}; vsip_scalar_d data_ans_i[] = { 0.0, 18.0, 0.0, 0.0, 0.0, 16, 0.0, 0.0, 0.0, 10, 0.0, 14, 0.0, 0.0, 0.0, 12}; vsip_cvview_d *a = vsip_cvbind_d( vsip_cblockbind_d(data1_r,data1_i,18,VSIP_MEM_NONE),17,-2,5); vsip_vview_mi *index = vsip_vbind_mi(/* matrix index is always interleaved */ vsip_blockbind_mi(data_index,5,VSIP_MEM_NONE),0,1,5); vsip_cmview_d *ans = vsip_cmbind_d( vsip_cblockbind_d(data_ans_r,data_ans_i,16,VSIP_MEM_NONE),0,4,4,1,4); vsip_cmview_d *b = vsip_cmcreate_d(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *chk = vsip_cmcreate_d(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *chk_i = vsip_mimagview_d(chk); vsip_cblockadmit_d(vsip_cvgetblock_d(a),VSIP_TRUE); vsip_blockadmit_mi(vsip_vgetblock_mi(index),VSIP_TRUE); vsip_cblockadmit_d(vsip_cmgetblock_d(ans),VSIP_TRUE); { vsip_mview_d *t = vsip_mrealview_d(b); vsip_mfill_d(0,t); vsip_mdestroy_d(t); t = vsip_mimagview_d(b); vsip_mfill_d(0,t); vsip_mdestroy_d(t); } printf("call vsip_cmscatter_d(a,b,index) \n"); vsip_cmscatter_d(a,b,index); printf("a =\n");VU_cvprintm_d("8.6",a); printf("index =\n");VU_vprintm_mi("",index); printf("b=\n");VU_cmprintm_d("8.6",b); printf("\nright answer =\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(ans,b,chk); vsip_cmmag_d(chk,chk_i); vsip_mclip_d(chk_i,0,2 * .0001,0,1,chk_i); if(fabs(vsip_msumval_d(chk_i)) > .5) printf("error\n"); else printf("correct\n"); vsip_cvalldestroy_d(a); vsip_valldestroy_mi(index); vsip_cmalldestroy_d(b); vsip_malldestroy_d(chk_i); vsip_cmalldestroy_d(chk); } return; } <file_sep>// // VectorExplorer.swift // VectorExplorer // // Created by <NAME> on 1/17/17. // Copyright © 2017 JVSIP. All rights reserved. // import Foundation import SwiftVsip func createBlock(length: Int) -> Vsip.Block { return Vsip.Block(length: length, type: .d) } <file_sep>/* Created By RJudd January 9, 1999 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_fftm_destroy_f.c,v 2.0 2003/02/22 15:18:52 judd Exp $ */ /* destroy vsip vectors created in vsip_xxfftxx_create_f */ #include"vsip.h" #include"vsip_cvviewattributes_f.h" #include"vsip_fftmattributes_f.h" #include"VI_cvalldestroy_f.h" int vsip_fftm_destroy_f(vsip_fftm_f *fftm) { #if defined(VSIP_USE_FFT_FOR_FFTM_F) if(fftm != NULL){ vsip_fft_f* fft = (vsip_fft_f*) fftm->ext_fftm_obj; if(fft != NULL) vsip_fft_destroy_f(fft); free(fftm); } #else if(fftm != NULL){ VI_cvalldestroy_f(fftm->wt); VI_cvalldestroy_f(fftm->temp); free(fftm->pn); free(fftm->p0); free(fftm->pF); free(fftm->index); free(fftm); } #endif return 0; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: tcloneview_uc.h,v 2.0 2003/02/22 15:23:35 judd Exp $ */ static void tcloneview_uc(void){ printf("********\nTEST tcloneview_uc\n"); { vsip_scalar_uc data[4][5][4] = {{{ 0, 1, 2, 3}, {10, 11, 12, 13}, { 20, 21, 22, 23}, {30, 31, 32, 33}, { 40, 41, 42, 43}}, {{ 100, 101 ,102 ,103}, {110, 111 ,112 ,113}, { 120, 121 ,122 ,123}, {130, 131 ,132 ,133}, { 140, 141, 142, 143}}, {{ 200, 201 ,202 ,203}, {210, 211 ,212 ,213}, { 220, 221 ,222 ,223}, {230, 231 ,232 ,233}, { 240, 241, 242, 243}}, {{ 000, 001 ,002 ,003}, {010, 011 ,012 ,013}, { 020, 021 ,022 ,023}, {030, 031 ,032 ,033}, { 040, 041, 042, 043}}}; vsip_offset o = 7; vsip_stride zs = 1, ys = 8, xs = 42; vsip_length zl = 4, yl = 5, xl = 4; vsip_block_uc *b = vsip_blockcreate_uc(200,VSIP_MEM_NONE); vsip_tview_uc *v = vsip_tbind_uc(b,o,zs,zl,ys,yl,xs,xl); vsip_tview_uc *sv = vsip_tcloneview_uc(v); vsip_scalar_uc chk = 0; int i,j,k; for(i=0; i< (int)zl; i++) for(j=0; j< (int)yl; j++) for(k=0; k< (int)xl; k++) vsip_tput_uc(v,i,j,k,data[i][j][k]); for(i=0; i< (int)zl; i++) for(j=0; j< (int)yl; j++) for(k=0; k< (int)xl; k++) chk += abs(vsip_tget_uc(sv,i,j,k) - data[i][j][k]); (chk > .0001) ? printf("error \n") : printf("correct \n"); fflush(stdout); vsip_tdestroy_uc(sv); vsip_talldestroy_uc(v); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mswap_f.h,v 2.0 2003/02/22 15:23:26 judd Exp $ */ #include"VU_mprintm_f.include" static void mswap_f(void){ printf("\n******\nTEST mswap_f\n"); { vsip_scalar_f data1[]= {1, 2, 3, 4, 5, 6, 7, 8, 9}; vsip_scalar_f data2[]= {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9}; vsip_mview_f *a = vsip_mbind_f( vsip_blockbind_f(data1,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_mview_f *b = vsip_mbind_f( vsip_blockbind_f(data2,9,VSIP_MEM_NONE),0,1,3,3,3); vsip_mview_f *a0 = vsip_mcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *b0 = vsip_mcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *chk = vsip_mcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_f(vsip_mgetblock_f(a),VSIP_TRUE); vsip_blockadmit_f(vsip_mgetblock_f(b),VSIP_TRUE); vsip_mcopy_f_f(a,a0); vsip_mcopy_f_f(b,b0); printf("a =\n");VU_mprintm_f("8.6",a); printf("b =\n");VU_mprintm_f("8.6",b); printf("call vsip_mswap_f(a,b)\n"); vsip_mswap_f(a,b); printf("a =\n");VU_mprintm_f("8.6",a); printf("b =\n");VU_mprintm_f("8.6",b); vsip_msub_f(a,b0,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,0,.0001,0,1,chk); if(fabs(vsip_msumval_f(chk)) > .5) printf("error in <a>\n"); else printf("<a> correct\n"); vsip_msub_f(b,a0,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,0,.0001,0,1,chk); if(fabs(vsip_msumval_f(chk)) > .5) printf("error in <b>\n"); else printf("<b> correct\n"); vsip_malldestroy_f(a); vsip_malldestroy_f(a0); vsip_malldestroy_f(b); vsip_malldestroy_f(b0); vsip_malldestroy_f(chk); } return; } <file_sep>/* * svd5_d.h * VSIP_svd_dev * * Created by <NAME> on 9/13/08. * Copyright 2008 Home. All rights reserved. * */ #include"VU_mprintm_d.include" #include"VU_vprintm_d.include" static void svd5_d(void){ printf("********\nTEST svd5 for double\n"); { vsip_index i; vsip_length M=3, N=10; vsip_scalar_d data[30] = {0, 0, 0, 0, \ 0, 0, 0, 0, \ 0, 0, 0, 1, \ 0, 0, 0, 100,\ 0, 0, 1, 0, \ 1,0,0,1,0,0,0,0,0,0}; vsip_vview_d *s = vsip_vcreate_d(((M > N) ? N : M),VSIP_MEM_NONE); vsip_sv_d *svd = vsip_svd_create_d(M,N,VSIP_SVD_UVFULL,VSIP_SVD_UVFULL); vsip_block_d *block = vsip_blockbind_d(data,(M * N),VSIP_MEM_NONE); vsip_mview_d *A0 = vsip_mbind_d(block,0,1,M,M,N); vsip_block_d *vblk = vsip_blockcreate_d(600,VSIP_MEM_NONE); vsip_mview_d *A = vsip_mbind_d(vblk,3,3, M,3*M , N); vsip_mview_d *U = vsip_mcreate_d(M,M,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *V = vsip_mcreate_d(N,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *B = vsip_mcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_d(block,VSIP_TRUE); vsip_mcopy_d_d(A0,A); printf("in = ");VU_mprintm_d("6.3",A); if(vsip_svd_d(svd,A,s)){ printf("svd error\n"); return; } /* create the singular value matrix */ vsip_mfill_d(0.0,B); for(i=0; i<vsip_vgetlength_d(s); i++) vsip_mput_d(B,i,i,vsip_vget_d(s,i)); vsip_svdmatu_d(svd, 0, M-1, U); vsip_svdmatv_d(svd, 0, N-1, V); printf("U = ");VU_mprintm_d("12.10",U); printf("B = ");VU_mprintm_d("12.10",B); printf("V = ");VU_mprintm_d("12.10",V); VU_vprintm_d("12.10",s); { /* check that A0 = U * B * V' */ vsip_scalar_d chk = 1.0; vsip_scalar_d lim = 5 * DBL_EPSILON * sqrt(vsip_msumsqval_d(A0)); vsip_mview_d *dif=vsip_mcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *out = vsip_mcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *Vt = vsip_mtransview_d(V); vsip_mprod_d(U,B,dif); vsip_mprod_d(dif,Vt,out); vsip_msub_d(out,A0,dif); vsip_mmag_d(dif, dif); chk = vsip_msumval_d(dif)/(2 * M * N); printf("%20.18e - %20.18e = %e\n",lim,chk, (lim - chk)); if(chk > lim){ printf("error\n"); } else { printf("correct\n"); } vsip_malldestroy_d(dif); vsip_malldestroy_d(out); vsip_mdestroy_d(Vt); } vsip_svd_destroy_d(svd); vsip_malldestroy_d(A0); vsip_malldestroy_d(A); vsip_valldestroy_d(s); vsip_malldestroy_d(U); vsip_malldestroy_d(B); vsip_malldestroy_d(V); } return; } <file_sep>// // main.swift // vsipExampleAdd // // Created by <NAME> on 10/5/16. // Copyright © 2016 JVSIP. All rights reserved. // import Foundation import vsip let N = vsip_length(500) let _ = vsip_init(nil) let m = vsip_cmcreate_d(N, N, VSIP_ROW, VSIP_MEM_NONE) let rnd = vsip_randcreate(8,1,1,VSIP_PRNG) let svd = vsip_csvd_create_d(N, N, VSIP_SVD_UVFULL, VSIP_SVD_UVFULL) let s = vsip_vcreate_d(N,VSIP_MEM_NONE) vsip_cmrandn_d(rnd,m) vsip_csvd_d(svd,m,s) for i in 0..<N{ print("i:\(i) -> \(vsip_vget_d(s,i))") } vsip_cmalldestroy_d(m) vsip_csvd_destroy_d(svd) vsip_valldestroy_d(s) vsip_randdestroy(rnd) let _ = vsip_finalize(nil) <file_sep>/* Created <NAME> 19, 1999 */ /* SPAWARSYSCEN D881 */ #ifndef _vsip_conv1dattributes_f #define _vsip_conv1dattributes_f 1 #include"VI.h" struct vsip_conv1dattributes_f{ vsip_cvview_f *H; vsip_cvview_f *x; vsip_cmview_f *Xm; vsip_fft_f *fft; vsip_fftm_f *fftm; vsip_scalar_vi method; /* 0 = vector, 1 = matrix */ vsip_symmetry symm; int D; /* decimation */ vsip_length nh; /* length of h */ vsip_length nx; /* length of input */ vsip_length Nsection; /* length of section */ vsip_length Noutput; /* total length of output vector */ vsip_length Ndata; vsip_length NumSection; int ntimes; /* ignored */ vsip_support_region support; vsip_alg_hint hint; /* ignored */ }; #endif /* _vsip_conv1dattributes_f */ <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mdiv_f.h,v 2.0 2003/02/22 15:23:24 judd Exp $ */ #include"VU_mprintm_f.include" static void mdiv_f(void){ printf("\n******\nTEST mdiv_f\n"); { vsip_scalar_f data1[]= {1, 2, 3, 4, 5, 6, 7, 8, 9}; vsip_scalar_f data2[]= {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9}; vsip_scalar_f ans[] = {0.9091, 0.4545, .3896, 1.8182, 0.9091, 0.6818, 2.1212, 1.2121, 0.9091}; vsip_mview_f *m1 = vsip_mbind_f( vsip_blockbind_f(data1,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_mview_f *m2 = vsip_mbind_f( vsip_blockbind_f(data2,9,VSIP_MEM_NONE),0,1,3,3,3); vsip_mview_f *ma = vsip_mbind_f( vsip_blockbind_f(ans,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_mview_f *m3 = vsip_mcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *chk = vsip_mcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_f(vsip_mgetblock_f(m1),VSIP_TRUE); vsip_blockadmit_f(vsip_mgetblock_f(m2),VSIP_TRUE); vsip_blockadmit_f(vsip_mgetblock_f(ma),VSIP_TRUE); printf("call vsip_mdiv_f(a,b,c)\n"); printf("a =\n");VU_mprintm_f("8.6",m1); printf("b =\n");VU_mprintm_f("8.6",m2); vsip_mdiv_f(m1,m2,m3); printf("c =\n");VU_mprintm_f("8.6",m3); printf("\nright answer =\n"); VU_mprintm_f("6.4",ma); vsip_msub_f(ma,m3,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,0,.0001,0,1,chk); if(fabs(vsip_msumval_f(chk)) > .5) printf("error\n"); else printf("correct\n"); vsip_mcopy_f_f(m1,m3); printf(" a,c inplace\n"); vsip_mdiv_f(m3,m2,m3); vsip_msub_f(ma,m3,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,0,.0001,0,1,chk); if(fabs(vsip_msumval_f(chk)) > .5) printf("error\n"); else printf("correct\n"); vsip_mcopy_f_f(m2,m3); printf(" b,c inplace\n"); vsip_mdiv_f(m1,m3,m3); vsip_msub_f(ma,m3,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,0,.0001,0,1,chk); if(fabs(vsip_msumval_f(chk)) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_f(m1); vsip_malldestroy_f(m2); vsip_malldestroy_f(m3); vsip_malldestroy_f(ma); vsip_malldestroy_f(chk); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: ctget_put_f.h,v 2.0 2003/02/22 15:23:33 judd Exp $ */ static void ctget_put_f(void){ printf("********\nTEST ctget_put_f\n"); { vsip_scalar_f datar_a[] = { 0, 1, 1, 0, 1, 0, 2, 1, -1, -2, 0 ,1}; vsip_scalar_f datai_a[] = { 1, -1, -1, 1, -1, 1, -2, 0, 1, 2, 1,-1}; vsip_scalar_f ansr[2][3][2] = {{{ 0, 1},{ 1, 0},{ 1, 0}},{{ 2, 1},{ -1, -2},{ 0 ,1}}}; vsip_scalar_f ansi[2][3][2] = {{{ 1, -1},{ -1, 1},{ -1, 1}},{{ -2, 0},{ 1, 2},{ 1,-1}}}; vsip_cblock_f *block_a = vsip_cblockbind_f(datar_a,datai_a,12,VSIP_MEM_NONE); vsip_ctview_f *a = vsip_ctbind_f(block_a,0,6,2,2,3,1,2); vsip_cblock_f *block_b = vsip_cblockcreate_f(50,VSIP_MEM_NONE); vsip_ctview_f *b = vsip_ctbind_f(block_b,45,-1,2,-3,3,-10,2); vsip_index h,i,j; vsip_cblockadmit_f(block_a,VSIP_TRUE); /* copy <a> into <b> */ for(h=0; h<2; h++) for(j=0; j<2; j++) for(i=0; i<3; i++) vsip_ctput_f(b,h,i,j,vsip_ctget_f(a,h,i,j)); /* check <a> against ans */ printf("check unit stride compact view\n"); for(h=0; h<2; h++) for(j=0; j<2; j++) for(i=0; i<3; i++){ vsip_cscalar_f chk = vsip_ctget_f(a,h,i,j); chk.r = chk.r - ansr[h][i][j]; chk.i = chk.i - ansi[h][i][j]; chk.r = chk.r * chk.r + chk.i * chk.i; (chk.r < 0.0001) ? printf("correct\n") : printf("error\n"); fflush(stdout); } printf("check general stride view\n"); for(h=0; h<2; h++) for(j=0; j<2; j++) for(i=0; i<3; i++){ vsip_cscalar_f chk = vsip_ctget_f(b,h,i,j); chk.r = chk.r - ansr[h][i][j]; chk.i = chk.i - ansi[h][i][j]; chk.r = chk.r * chk.r + chk.i * chk.i; (chk.r < 0.0001) ? printf("correct\n") : printf("error\n"); fflush(stdout); } vsip_ctalldestroy_f(a); vsip_ctalldestroy_f(b); } return; } <file_sep>/* Created RJudd September 13, 1997*/ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_vramp_f.h,v 2.1 2007/04/21 19:39:33 judd Exp $ */ #ifndef VI_VRAMP_F_H #define VI_VRAMP_F_H #define VI_vramp_f(x,y,r) { \ vsip_length N = r->length,i; \ register vsip_scalar_f start = x; register vsip_scalar_f inc = y;\ vsip_stride rst = r->stride * r->block->rstride;\ vsip_scalar_f *rp = (r->block->array) + r->offset * r->block->rstride;\ *rp = start;\ for(i=1; i<N; i++){\ rp += rst;\ *rp = start + (vsip_scalar_d)i * inc;\ }} #endif <file_sep>/* Created RJudd April 24, 2003 */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vhisto_li.c,v 2.1 2003/07/04 14:12:33 judd Exp $ */ #include"vsip.h" #include"vsip_vviewattributes_li.h" #include"VI_vfill_li.h" void (vsip_vhisto_li)( const vsip_vview_li* a, vsip_scalar_li min, vsip_scalar_li max, vsip_hist_opt opt, const vsip_vview_li* r) { /* histogram */ { vsip_stride str = 0; vsip_length n = a->length; vsip_length p = r->length; double p_s = (double)(p - 2); vsip_stride ast = a->stride, rst = r->stride; double scale = (double)rst * p_s; double iscale = (double)(max-min); vsip_scalar_li *ap = (a->block->array) + a->offset, *rp = (r->block->array) + r->offset; vsip_scalar_li *rp0 = rp, *rp_end = rp + p - 1 ; rp++; if(opt == VSIP_HIST_RESET) VI_vfill_l((vsip_scalar_li)0, r); while(n-- > 0){ if(*ap < min){ (*rp0)++; } else if (*ap >= max){ (*rp_end)++; } else { str = (vsip_stride)((scale * (double)(*ap - min))/iscale); (*(rp + str))++; } ap += ast; } } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mget_put_f.h,v 2.0 2003/02/22 15:23:34 judd Exp $ */ static void mget_put_f(void){ printf("********\nTEST mget_put_f\n"); { vsip_scalar_f data_a[] = { 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1}; vsip_scalar_f ans[6][2] = {{ 0, 1},{ 1, 0},{ 1, 0},{ 1, 0},{ 0, 1},{ 0, 1}}; vsip_block_f *block_a = vsip_blockbind_f(data_a,12,VSIP_MEM_NONE); vsip_mview_f *a = vsip_mbind_f(block_a,0,2,6,1,2); vsip_block_f *block_b = vsip_blockcreate_f(50,VSIP_MEM_NONE); vsip_mview_f *b = vsip_mbind_f(block_b,5,5,6,2,2); vsip_index i,j; vsip_blockadmit_f(block_a,VSIP_TRUE); /* copy <a> into <b> */ for(i=0; i<6; i++) for(j=0; j<2; j++) vsip_mput_f(b,i,j,vsip_mget_f(a,i,j)); /* check <a> against ans */ printf("check unit stride compact view\n"); for(i=0; i<6; i++) for(j=0; j<2; j++) { vsip_scalar_f chk = fabs(ans[i][j] - vsip_mget_f(a,i,j)); (chk < 0.0001) ? printf("correct\n") : printf("error\n"); fflush(stdout); } printf("check general stride view\n"); for(i=0; i<6; i++) for(j=0; j<2; j++){ vsip_scalar_f chk = fabs(ans[i][j] - vsip_mget_f(b,i,j)); (chk < 0.0001) ? printf("correct\n") : printf("error\n"); fflush(stdout); } vsip_malldestroy_f(a); vsip_malldestroy_f(b); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmconj_d.h,v 2.0 2003/02/22 15:23:20 judd Exp $ */ #include"VU_cmprintm_d.include" static void cmconj_d(void){ printf("\n*******\nTEST cmconj_d\n\n"); { vsip_scalar_d data_r[] = {M_PI/8.0, M_PI/4.0, M_PI/3.0, M_PI/1.5, 1.25 * M_PI, 1.75 * M_PI}; vsip_scalar_d data_i[] = {1, 2, -1, -2, 3, 4}; vsip_scalar_d ans_r[] = {M_PI/8.0, M_PI/4.0, M_PI/3.0, M_PI/1.5, 1.25 * M_PI, 1.75 * M_PI}; vsip_scalar_d ans_i[] = {-1, -2, +1, +2, -3, -4}; vsip_cblock_d *block = vsip_cblockbind_d(data_r,data_i,6,VSIP_MEM_NONE); vsip_cblock_d *ans_block = vsip_cblockbind_d(ans_r,ans_i,6,VSIP_MEM_NONE); vsip_cmview_d *a = vsip_cmbind_d(block,0,2,3,1,2); vsip_cmview_d *ansm = vsip_cmbind_d(ans_block,0,2,3,1,2); vsip_cmview_d *b = vsip_cmcreate_d(3,2,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *chk = vsip_cmcreate_d(3,2,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *chk_r = vsip_mcreate_d(3,2,VSIP_COL,VSIP_MEM_NONE); vsip_cblockadmit_d(block,VSIP_TRUE); vsip_cblockadmit_d(ans_block,VSIP_TRUE); printf("test out of place, compact, user \"a\", vsipl \"b\"\n"); vsip_cmconj_d(a,b); printf("vsip_cmconj_d(a,b)\n matrix a\n");VU_cmprintm_d("8.6",a); printf("matrix b\n");VU_cmprintm_d("8.6",b); printf("answer\n");VU_cmprintm_d("8.4",ansm); vsip_cmsub_d(b,ansm,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); printf("check cmconj_d in place\n"); vsip_cmconj_d(a,a); vsip_cmsub_d(a,ansm,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(a); vsip_cmalldestroy_d(b); vsip_mdestroy_d(chk_r); vsip_cmalldestroy_d(chk); vsip_cmalldestroy_d(ansm); } return; } <file_sep>import pyJvsip as pjv # Elementwise add using columns. # This is just to demo pyJvsip API features. There is no good reason to actually use this code def madd(A,B,C): assert 'pyJvsip' in repr(A) and '__View' in repr(A),'Input parameters must be views of type pyJvsip.__View.' assert type(A) == type(B) and type(A) == type(C),'Input paramteters must be the same type' assert 'mview' in A.type,'Only matrix views are supported for madd.' L = A.rowlength a = A.colview b = B.colview c = C.colview for i in range(L): pjv.add(a(i),b(i),c(i)) return C a = pjv.create('vview_d',50) b = pjv.create('vview_d',50) c = pjv.create('vview_d',50) A=a.block.bind(0,4,3,1,4) B=b.block.bind(0,4,3,1,4) C=c.block.bind(0,4,3,1,4) a.ramp(0.0,.01) b.ramp(0.0,1.0) madd(A,B,C); print('A = '); A.mprint('%.2f') print('B= '); B.mprint('%.2f') print("A + B = C = ");C.mprint('%.2f') <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmcloneview_f.h,v 2.0 2003/02/22 15:23:32 judd Exp $ */ static void cmcloneview_f(void){ printf("********\nTEST cmcloneview_f\n"); { vsip_scalar_f data_r[10][4] ={{ 0, 1, 2, 3}, { 10, 11, 12, 13}, { 20, 21, 22, 23}, { 30, 31, 32, 33}, { 40, 41, 42, 43}, { 50, 51, 52, 53}, { 60, 61, 62, 63}, { 70, 71, 72, 73}, { 80, 81, 82, 83}, { 90, 91, 92, 93}}; vsip_scalar_f data_i[10][4] ={{ 0, -1, -2, -3}, {-10, -11, -12, -13}, {-20, -21, -22, -23}, {-30, -31, -32, -33}, {-40, -41, -42, -43}, {-50, -51, -52, -53}, {-60, -61, -62, -63}, {-70, -71, -72, -73}, {-80, -81, -82, -83}, {-90, -91, -92, -93}}; vsip_offset o = 4; vsip_stride rs = 2, cs = 8; vsip_length m = 10, n = 4; vsip_cblock_f *b = vsip_cblockcreate_f(100,VSIP_MEM_NONE); vsip_cmview_f *v = vsip_cmbind_f(b,o,cs,m,rs,n); vsip_cmview_f *sv = vsip_cmcloneview_f(v); vsip_scalar_f chk = 0; int i,j; vsip_cscalar_f a; for(i=0; i< (int)m; i++){ for(j=0; j< (int)n; j++){ a.r = data_r[i][j]; a.i = data_i[i][j]; vsip_cmput_f(v,i,j,a); } } for(i=0; i< (int)m; i++){ for(j=0; j< (int)n; j++){ a = vsip_cmget_f(sv,i,j); a.r -= data_r[i][j]; a.i -= data_i[i][j]; chk += a.r * a.r +a.i * a.i; } } (chk > .0001) ? printf("error \n") : printf("correct \n"); fflush(stdout); vsip_cmdestroy_f(sv); vsip_cmalldestroy_f(v); } return; } <file_sep>/* Created By RJudd June 16, 2002 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_crfftop_create_f_fftw.h,v 2.1 2003/03/08 14:43:33 judd Exp $ */ /* complex to real fft */ #include"VI_fft_building_blocks_f.h" #include"VI_vrealview_f.h" #include"VI_vimagview_f.h" #define __VSIPL_FFTWOBJ_INIT #define __VSIPL_FFTWOBJ_FIN #include"VI_fftw_obj.h" vsip_fft_f* vsip_crfftop_create_f(vsip_length N, vsip_scalar_f scale, unsigned int ntimes, vsip_alg_hint hint) { vsip_fft_f *fft = (vsip_fft_f*) malloc(sizeof(vsip_fft_f)); vsipl_fftw_obj *obj; fftw_direction fftw_dir = FFTW_BACKWARD; int flags = (hint == VSIP_ALG_TIME) ? FFTW_MEASURE : FFTW_ESTIMATE; int init; if(fft == NULL) return (vsip_fft_f*) NULL; fft->N = N/2; fft->scale = scale; fft->d = VSIP_FFT_INV; fft->pn = NULL; fft->p0 = NULL; fft->pF = NULL; fft->wt = (vsip_cvview_f*)NULL; fft->index = (NULL); fft->hint = hint; fft->ntimes = ntimes; fft->type = VSIP_CRFFTOP; fft->temp = vsip_cvcreate_f(fft->N+1,VSIP_MEM_NONE); init = vsipl_fftwobj_init(&obj,fftw_dir,fft->N,flags); /* need some storage to keep from overwriting input */ if(obj->in == NULL){ obj->in = (fftw_complex*)malloc(fft->N * sizeof(fftw_complex)); } if(obj->in == NULL) init++; if((init!=0) || (fft->temp == (vsip_cvview_f*)NULL)){ if(init != 0) vsipl_fftwobj_fin(obj); if(fft->temp != NULL) vsip_cvdestroy_f(fft->temp); free(fft); return (vsip_fft_f*)NULL; } fft->ext_fft_obj = (void*)obj; { vsip_vview_f wt1,wt2; vsip_vview_f *wtR = VI_vrealview_f(fft->temp,&wt1); vsip_vview_f *wtI = VI_vimagview_f(fft->temp,&wt2); vsip_vramp_f((vsip_scalar_f)0, (vsip_scalar_f)VI_ft_f_PI/fft->N,wtR); vsip_vsin_f(wtR,wtI); vsip_vcos_f(wtR,wtR); } return fft; } <file_sep>/* * vsip_svdattributes_f.h * Created by <NAME> on 9/5/08. * Copyright 2008 Home. All rights reserved. * */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #ifndef _vsip_svd_f_h #define _vsip_svd_f_h 1 #include"vsip.h" #include"vsip_vviewattributes_f.h" #include"vsip_mviewattributes_f.h" #include"vsip_mviewattributes_f.h" #include"vsip_cmviewattributes_f.h" #include"vsip_cvviewattributes_f.h" #include"vsip_vviewattributes_vi.h" typedef vsip_sv_attr_f sv_attr; struct vsip_svd{ void *svd; sv_attr attr; int transpose; }; typedef struct {vsip_vview_f* t; vsip_vview_f ts; vsip_vview_f* w; vsip_mview_f B; vsip_mview_f Bs; vsip_vview_f bs; vsip_mview_f* L; vsip_mview_f Ls; vsip_vview_f ls_one; vsip_vview_f ls_two; vsip_vview_f* d; vsip_vview_f ds; vsip_vview_f* f; vsip_vview_f fs; vsip_mview_f* R; vsip_mview_f Rs; vsip_vview_f rs_one; vsip_vview_f rs_two; vsip_scalar_f eps0;int init; vsip_vview_vi *indx_L; vsip_vview_vi *indx_R;} svdObj_f; typedef struct {vsip_cvview_f* t; vsip_cvview_f ts; vsip_cvview_f* w; vsip_cmview_f B; vsip_cmview_f Bs; vsip_cvview_f bs; vsip_cvview_f bfs; vsip_vview_f rbs; vsip_cmview_f* L; vsip_cmview_f Ls; vsip_cvview_f ls_one; vsip_cvview_f ls_two; vsip_vview_f* d; vsip_vview_f ds; vsip_vview_f* f; vsip_vview_f fs; vsip_cmview_f* R; vsip_cmview_f Rs; vsip_cvview_f rs_one; vsip_cvview_f rs_two; vsip_scalar_f eps0;int init; vsip_vview_vi *indx_L; vsip_vview_vi *indx_R;} csvdObj_f; #endif /*_vsip_svd_f_h */ <file_sep>/* Created RJudd */ /* */ #include"VU_cmprintm_d.include" static void cmfreqswap_d(void){ printf("*********\nTEST cmfreqswap_d\n"); { vsip_length M=6,N=5; vsip_cmview_d *a = vsip_cmcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_cvview_d *v = vsip_cvbind_d(vsip_cmgetblock_d(a),0,1,M*N); vsip_vview_d *v_r=vsip_vrealview_d(v); vsip_vview_d *v_i=vsip_vimagview_d(v); vsip_cmview_d *ans = vsip_cmcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_scalar_d rdta[]={ 18.0, 19.0, 20.0, 16.0, 17.0, 23.0, 24.0, 25.0, 21.0, 22.0, 28.0, 29.0, 30.0, 26.0, 27.0, 3.0, 4.0, 5.0, 1.0, 2.0, 8.0, 9.0, 10.0, 6.0, 7.0, 13.0, 14.0, 15.0, 11.0, 12.0}; vsip_scalar_d idta[]={-18.0,-19.0,-20.0,-16.0,-17.0, -23.0,-24.0,-25.0,-21.0,-22.0, -28.0,-29.0,-30.0,-26.0,-27.0, -3.0,- 4.0,- 5.0,- 1.0,- 2.0, -8.0,- 9.0,-10.0,- 6.0,- 7.0, -13.0,-14.0,-15.0,-11.0,-12.0}; vsip_cmcopyfrom_user_d(rdta,idta,VSIP_ROW,ans); vsip_vramp_d (1,1,v_r); vsip_vramp_d (-1,-1,v_i); printf("input matrix\n"); VU_cmprintm_d("3.1",a); vsip_cmfreqswap_d(a); printf("expected output matrix\n"); VU_cmprintm_d("3.1",ans); printf("output matrix\n"); VU_cmprintm_d("3.1",a); { vsip_cmsub_d(a,ans,ans); if(vsip_mcmaxmgsqval_d(ans,NULL) > .00001){ printf("error\n"); }else{ printf("correct\n"); } } vsip_vdestroy_d(v_r); vsip_vdestroy_d(v_i); vsip_cvdestroy_d(v); vsip_cmalldestroy_d(a); vsip_cmalldestroy_d(ans); } } <file_sep>/* * vsip_svdattributes_d.h * Created by <NAME> 5/2013. * Copyright 2013 All rights reserved. * */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #ifndef _vsip_svd_d_h #define _vsip_svd_d_h 1 #include"vsip.h" #include"vsip_vviewattributes_d.h" #include"vsip_mviewattributes_d.h" #include"vsip_mviewattributes_d.h" #include"vsip_cmviewattributes_d.h" #include"vsip_cvviewattributes_d.h" #include"vsip_vviewattributes_vi.h" typedef vsip_sv_attr_d sv_attr; struct vsip_svd{ void *svd; sv_attr attr; int transpose; }; typedef struct {vsip_vview_d* t; vsip_vview_d ts; vsip_vview_d* w; vsip_mview_d B; vsip_mview_d Bs; vsip_vview_d bs; vsip_mview_d* L; vsip_mview_d Ls; vsip_vview_d ls_one; vsip_vview_d ls_two; vsip_vview_d* d; vsip_vview_d ds; vsip_vview_d* f; vsip_vview_d fs; vsip_mview_d* R; vsip_mview_d Rs; vsip_vview_d rs_one; vsip_vview_d rs_two; vsip_scalar_d eps0;int init; vsip_vview_vi *indx_L; vsip_vview_vi *indx_R;} svdObj_d; typedef struct {vsip_cvview_d* t; vsip_cvview_d ts; vsip_cvview_d* w; vsip_cmview_d B; vsip_cmview_d Bs; vsip_cvview_d bs; vsip_cvview_d bfs; vsip_vview_d rbs; vsip_cmview_d* L; vsip_cmview_d Ls; vsip_cvview_d ls_one; vsip_cvview_d ls_two; vsip_vview_d* d; vsip_vview_d ds; vsip_vview_d* f; vsip_vview_d fs; vsip_cmview_d* R; vsip_cmview_d Rs; vsip_cvview_d rs_one; vsip_cvview_d rs_two; vsip_scalar_d eps0;int init; vsip_vview_vi *indx_L; vsip_vview_vi *indx_R;} csvdObj_d; #endif /*_vsip_svd_d_h */ <file_sep>/* See Copyright in top level directory */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #ifndef _PYVSIP_H #define _PYVSIP_H #include<vsip.h> #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include"Python.h" /* extra functions for python */ vsip_index *vindexptr(void); void vindexfree(vsip_index*); vsip_index vindexptrToInt(vsip_index*); vsip_cscalar_f py_rcvjdot_f(const vsip_vview_f*, const vsip_cvview_f*); vsip_cscalar_f py_crvjdot_f(const vsip_cvview_f* , const vsip_vview_f*); vsip_cscalar_d py_rcvjdot_d(const vsip_vview_d*, const vsip_cvview_d*); vsip_cscalar_d py_crvjdot_d(const vsip_cvview_d* , const vsip_vview_d*); PyObject *cvcopyToList_f(vsip_cvview_f *); PyObject *cvcopyToList_d(vsip_cvview_d *); PyObject *vcopyToList_f(vsip_vview_f *); PyObject *vcopyToList_d(vsip_vview_d *); PyObject *vcopyToList_i(vsip_vview_i *); PyObject *vcopyToList_si(vsip_vview_si *); PyObject *vcopyToList_uc(vsip_vview_uc *); PyObject *vcopyToList_vi(vsip_vview_vi *); PyObject *vcopyToList_mi(vsip_vview_mi *); PyObject *cmcopyToListByRow_f(vsip_cmview_f *); PyObject *mcopyToListByRow_f(vsip_mview_f *); PyObject *cmcopyToListByRow_d(vsip_cmview_d *); PyObject *mcopyToListByRow_d(vsip_mview_d *); PyObject *mcopyToListByRow_i(vsip_mview_i *); PyObject *mcopyToListByRow_si(vsip_mview_si *); PyObject *mcopyToListByRow_uc(vsip_mview_uc *); PyObject *cmcopyToListByCol_f(vsip_cmview_f *); PyObject *mcopyToListByCol_f(vsip_mview_f *); PyObject *cmcopyToListByCol_d(vsip_cmview_d *); PyObject *mcopyToListByCol_d(vsip_mview_d *); PyObject *mcopyToListByCol_i(vsip_mview_i *); PyObject *mcopyToListByCol_si(vsip_mview_si *); PyObject *mcopyToListByCol_uc(vsip_mview_uc *); #endif <file_sep>import Foundation import vsip public func VU_vfprintxyg_d(_ format: String,_ x: OpaquePointer ,_ y: OpaquePointer,_ fname: String) { let N = vsip_length(vsip_vgetlength_d(y)) let of = fopen(fname.cString(using: .ascii)!,"w".cString(using: .ascii)) for i in 0..<N { let out = String(format: format, vsip_vget_d(x,i), vsip_vget_d(y,i)).cString(using: .ascii)! fwrite(out, MemoryLayout<Int8>.size, out.count - 1, of) } fclose(of); } <file_sep>/* * cmprod3_f.h * vsip_atest * * Created by <NAME> on 4/26/06. * Copyright 2006 * */ /* $Id: cmprod3_f.h,v 2.1 2006/04/27 01:40:55 judd Exp $ */ #include"VU_cmprintm_f.include" static void cmprod3_f(void){ printf("********\nTEST cmprod3_f\n"); { vsip_scalar_f datal_r[] = {1.0, 2.0, 3.0, 5.0, 5.0, 0.1, 2.0, 0.0, -1.0}; vsip_scalar_f datal_i[] = {9.0, 3.0, 2.0, 3.2, 5.0, 1.2, -2.1, 0.1, 2.0}; vsip_scalar_f datar_r[] = {0.1, 0.2, 0.3, 0.4, 1.0, 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 2.4, -1.1, -2.2, -2.3, -1.4, 3.1, 2.2, 1.3, 0.4, -1.1, -1.3, 4.3, -1.4}; vsip_scalar_f datar_i[] = { 1.1, 5.2, 3.3, 1.4, 2.1, 1.0, 1.2, 1.2, 4.1, 3.0, 2.3, 2.3, 1.1, -6.2, -1.3, 9.3, 1.0, 2.2, -2.3, 3.4, 4.6, 5.0, 2.1, 7.3}; /* we use vsip_cmprod_f to fill up the answer data space */ vsip_scalar_f ans_data_r[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; vsip_scalar_f ans_data_i[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; vsip_cblock_f *blockl = vsip_cblockbind_f(datal_r,datal_i,9,VSIP_MEM_NONE); vsip_cblock_f *blockr = vsip_cblockbind_f(datar_r,datar_i,24,VSIP_MEM_NONE); vsip_cblock_f *block_ans = vsip_cblockbind_f(ans_data_r,ans_data_i,24,VSIP_MEM_NONE); vsip_cblock_f *block = vsip_cblockcreate_f(250,VSIP_MEM_NONE); vsip_cmview_f *ml = vsip_cmbind_f(blockl,0,3,3,1,3); vsip_cmview_f *mr = vsip_cmbind_f(blockr,0,8,3,1,8); vsip_cmview_f *ans = vsip_cmbind_f(block_ans,0,8,3,1,8); vsip_cmview_f *a = vsip_cmbind_f(block,70,-1,3,-6,3); vsip_cmview_f *b = vsip_cmbind_f(block,71, 1,3,5,8); vsip_cmview_f *c = vsip_cmbind_f(block,220,-9,3,-1,8); vsip_cmview_f *chk = vsip_cmcreate_f(3,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *chk_r = vsip_mrealview_f(chk); vsip_cblockadmit_f(blockl,VSIP_TRUE); vsip_cblockadmit_f(blockr,VSIP_TRUE); vsip_cblockadmit_f(block_ans,VSIP_TRUE); vsip_cmcopy_f_f(ml,a); vsip_cmcopy_f_f(mr,b); vsip_cmprod_f(a,b,ans); vsip_cmprod3_f(a,b,c); printf("vsip_cmprod3_f(a,b,c)\n"); printf("a\n"); VU_cmprintm_f("6.4",a); printf("b\n"); VU_cmprintm_f("6.4",b); printf("c\n"); VU_cmprintm_f("6.4",c); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); { /* ccc */ vsip_cmview_f *a1 = vsip_cmcreate_f(4,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod3_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* ccr */ vsip_cmview_f *a1 = vsip_cmcreate_f(4,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod3_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* crc */ vsip_cmview_f *a1 = vsip_cmcreate_f(4,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod3_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* crr */ vsip_cmview_f *a1 = vsip_cmcreate_f(4,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod3_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* rcc */ vsip_cmview_f *a1 = vsip_cmcreate_f(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod3_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* rcr */ vsip_cmview_f *a1 = vsip_cmcreate_f(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod3_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* rrc */ vsip_cmview_f *a1 = vsip_cmcreate_f(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod3_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* rrr */ vsip_cmview_f *a1 = vsip_cmcreate_f(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod3_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } vsip_cmalldestroy_f(ml); vsip_cmalldestroy_f(mr); vsip_cmdestroy_f(a); vsip_cmdestroy_f(b); vsip_cmalldestroy_f(c); vsip_cmalldestroy_f(ans); vsip_mdestroy_f(chk_r); vsip_cmalldestroy_f(chk); } return; } <file_sep>import pyJvsip as pv N=6 A = pv.create('vview_f',N).randn(7) B = A.empty.fill(5.0) C = A.empty.fill(0.0) print('A = '+A.mstring('%+.2f')) print('B = '+B.mstring('%+.2f')) pv.add(A,B,C) print('C = A+B') print('C = '+C.mstring('%+.2f')) """ OUTPUT A = [-0.05 +0.59 +0.73 -0.37 -0.21 -0.83] B = [+5.00 +5.00 +5.00 +5.00 +5.00 +5.00] C = A+B C = [+4.95 +5.59 +5.73 +4.63 +4.79 +4.17] """ <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: sort1_f.h,v 1.1 2008/09/19 21:01:49 judd Exp $ */ static void sort1_f(void){ printf("********\nTEST sort (1) for float\n"); { vsip_scalar_f dta[30] = { -1, 2, 0,-3, 6, 8, 5, 4,-2, 1, 2, 3, 4, \ 5, 6, 7, 8, 9,10,11, -1,-2,-3,-4,-5, 0,-4,-5,-3,-2}; vsip_scalar_f ans_dta[30] = {0, 0, 1, 1,1, 2, 2, 2,2, 2, 3, \ 3,3, 3, 4, 4, 4, 4, 5, 5, 5, \ 5, 6, 6, 7, 8, 8, 9, 10, 11}; vsip_vview_f *s = vsip_vcreate_f(30,VSIP_MEM_NONE); vsip_vview_f *sinv = vsip_vcreate_f(30,VSIP_MEM_NONE); vsip_vview_f *ans_s = vsip_vcreate_f(30,VSIP_MEM_NONE); vsip_vview_vi *vi = vsip_vcreate_vi(30,VSIP_MEM_NONE); vsip_vview_bl *chk = vsip_vcreate_bl(30,VSIP_MEM_NONE); vsip_vcopyfrom_user_f(dta,s); vsip_vcopyfrom_user_f(ans_dta,ans_s); printf("sort by magnitude; sort ascending\n"); vsip_vsortip_f(s, VSIP_SORT_BYMAGNITUDE, VSIP_SORT_ASCENDING,VSIP_TRUE, vi); vsip_vmag_f(s,s); vsip_vleq_f(s,ans_s,chk); if(vsip_valltrue_bl(chk)) printf("correct\n"); else printf("error\n"); vsip_vcopyfrom_user_f(dta,s); vsip_vgather_f(s,vi,sinv); vsip_vmag_f(sinv,s); vsip_vleq_f(s,ans_s,chk); if(vsip_valltrue_bl(chk)) printf("correct\n"); else printf("error\n"); vsip_valldestroy_vi(vi); vsip_valldestroy_f(s); vsip_valldestroy_f(sinv); vsip_valldestroy_f(ans_s); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: matan2_f.h,v 2.0 2003/02/22 15:23:24 judd Exp $ */ #include"VU_mprintm_f.include" static void matan2_f(void){ printf("\n*******\nTEST matan2_f\n\n"); { vsip_scalar_f data_a[] = {0,1,2,3,4,5}; vsip_scalar_f data_b[] = {5,4,3,2,1,0}; vsip_scalar_f ans[] = {0, 0.2450, 0.5880, 0.9828, 1.3258, 1.5708}; vsip_block_f *block_a = vsip_blockbind_f(data_a,6,VSIP_MEM_NONE); vsip_block_f *block_b = vsip_blockbind_f(data_b,6,VSIP_MEM_NONE); vsip_block_f *ans_block = vsip_blockbind_f(ans,6,VSIP_MEM_NONE); vsip_mview_f *a = vsip_mbind_f(block_a,0,3,2,1,3); vsip_mview_f *b = vsip_mbind_f(block_b,0,3,2,1,3); vsip_mview_f *ansm = vsip_mbind_f(ans_block,0,3,2,1,3); vsip_mview_f *c = vsip_mcreate_f(2,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *chk = vsip_mcreate_f(2,3,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_f(block_a,VSIP_TRUE); vsip_blockadmit_f(block_b,VSIP_TRUE); vsip_blockadmit_f(ans_block,VSIP_TRUE); printf("vsip_matan2_f(a,b,c)\n"); vsip_matan2_f(a,b,c); printf("matrix a\n");VU_mprintm_f("8.6",a); printf("matrix b\n");VU_mprintm_f("8.6",b); printf("matrix c\n");VU_mprintm_f("8.6",c); printf("right answer \n");VU_mprintm_f("8.4",ansm); vsip_msub_f(c,ansm,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("inplace b,c\n"); vsip_matan2_f(a,b,b); vsip_msub_f(b,ansm,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_f(a); vsip_malldestroy_f(b); vsip_malldestroy_f(c); vsip_malldestroy_f(chk); vsip_malldestroy_f(ansm); } return; } <file_sep>/* Created RJudd September 19, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mbind_si.c,v 2.0 2003/02/22 15:18:54 judd Exp $ */ #include"vsip.h" #include"vsip_mviewattributes_si.h" vsip_mview_si* (vsip_mbind_si)( const vsip_block_si* block, vsip_offset offset, vsip_stride col_stride, vsip_length col_length, vsip_stride row_stride, vsip_length row_length) { { vsip_mview_si* mview_si = (vsip_mview_si*)malloc(sizeof(vsip_mview_si)); if(mview_si != NULL){ mview_si->block = (vsip_block_si*)block; mview_si->offset = offset; mview_si->col_stride = col_stride; mview_si->row_stride = row_stride; mview_si->col_length = col_length; mview_si->row_length = row_length; mview_si->markings = VSIP_VALID_STRUCTURE_OBJECT; } return mview_si; } } <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cvcopyto_user_d.h,v 1.1 2007/04/18 03:59:06 judd Exp $ */ #include"VU_cvprintm_d.include" static void cvcopyto_user_d(void){ int i; printf("********\nTEST cvcopyto_user_d\n"); { /* test interleaved */ vsip_cblock_d *block = vsip_cblockcreate_d(200,VSIP_MEM_NONE); vsip_scalar_d output[10]; vsip_scalar_d ans[10]={0,1,2,3,4,5,6,7,8,9}; vsip_scalar_d check = 0; vsip_cvview_d *view = vsip_cvbind_d(block,100,-2,5); vsip_cvview_d *all = vsip_cvbind_d(block,0,1,200); vsip_cvfill_d(vsip_cmplx_d(-1,-1),all); for(i=0; i<5; i++){ vsip_cscalar_d t = vsip_cmplx_d((vsip_scalar_d)i*2, (vsip_scalar_d)i*2+1); vsip_cvput_d(view,(vsip_index)i,t); } printf("interleaved\n"); VU_cvprintm_d("3.2",view); vsip_cvcopyto_user_d(view,output,(vsip_scalar_d*)NULL); for(i=0; i<10; i++){ printf("%f\n",(float)output[i]); check += fabs(output[i]-ans[i]); } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_cvdestroy_d(all); vsip_cvdestroy_d(view); vsip_cblockdestroy_d(block); } { /* test split */ vsip_cblock_d *block = vsip_cblockcreate_d(200,VSIP_MEM_NONE); vsip_scalar_d output_r[5]; vsip_scalar_d output_i[5]; vsip_scalar_d ans_r[5]={0,2,4,6,8}; vsip_scalar_d ans_i[5]={1,3,5,7,9}; vsip_scalar_d check = 0; vsip_cvview_d *view = vsip_cvbind_d(block,100,3,5); vsip_cvview_d *all = vsip_cvbind_d(block,0,1,200); vsip_cvfill_d(vsip_cmplx_d(-1,-1),all); for(i=0; i<5; i++){ vsip_cscalar_d t = vsip_cmplx_d((vsip_scalar_d)i*2, (vsip_scalar_d)i*2+1); vsip_cvput_d(view,(vsip_index)i,t); } printf("split\n"); VU_cvprintm_d("3.2",view); vsip_cvcopyto_user_d(view,output_r,output_i); for(i=0; i<5; i++){ printf("%f\n",(float)output_r[i]); check += fabs(output_r[i]-ans_r[i]); printf("%f\n",(float)output_i[i]); check += fabs(output_i[i]-ans_i[i]); } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_cvdestroy_d(all); vsip_cvdestroy_d(view); vsip_cblockdestroy_d(block); } return; } <file_sep>/* Created RJudd March 17, 1999 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_correlate1d_d.c,v 2.1 2007/04/16 16:50:41 judd Exp $ */ #include"vsip.h" #include"vsip_corr1dattributes_d.h" #include"vsip_cvviewattributes_d.h" #include"vsip_vviewattributes_d.h" #include"VI_vcopy_d_d.h" #include"VI_vfill_d.h" #include"VI_vrealview_d.h" #include"VI_vimagview_d.h" static void VI_vunbiasfull_d( const vsip_corr1d_d *cor, const vsip_vview_d *x, const vsip_vview_d *y) { /* register */ vsip_length n = y->length; /* register */ vsip_length s1 = n - cor->m; /* register */ vsip_length s2 = cor->m; /* register */ vsip_stride xst = x->stride * x->block->rstride, yst = y->stride * y->block->rstride; vsip_scalar_d *xp = (x->block->array) + x->offset * x->block->rstride, *yp = (y->block->array) + y->offset * y->block->rstride; vsip_scalar_d scale2 = 1.0/(vsip_scalar_d)cor->m, scale1 = 1.0; while(n-- > s1){ *yp = *xp / scale1; scale1 += 1.0; yp+=yst; xp+=xst; } n++; while(n-- > s2){ *yp = *xp * scale2; yp+=yst; xp+=xst; } n++; n++; while(n-- > 1){ *yp = *xp / (vsip_scalar_d)n; yp+=yst; xp+=xst; } return; } static void VI_vunbiassame_d( const vsip_corr1d_d *cor, const vsip_vview_d *x, const vsip_vview_d *y) { vsip_index i; register vsip_scalar_d mscale = (vsip_scalar_d)cor->m; vsip_length adj = (vsip_length)(cor->m & 1); vsip_length n0 = cor->m/2; vsip_length n1 = cor->n - n0; vsip_length n2 = cor->n; register vsip_scalar_d mceil = (vsip_scalar_d)(n0 + adj); register vsip_scalar_f N = (vsip_scalar_d)(n2 + n0 ); vsip_stride xst = x->stride * x->block->rstride, yst = y->stride * y->block->rstride; vsip_scalar_d *xp = (x->block->array) + x->offset * x->block->rstride, *yp = (y->block->array) + y->offset * y->block->rstride; for(i=0; i < n0; i++) yp[i * yst] = xp[i * xst] / ((vsip_scalar_d)(i) + mceil); for(i=n0; i < n1; i++) yp[i * yst] = xp[i * xst] / mscale ; for(i=n1; i < n2; i++) yp[i * yst] = xp[i * xst] / (N - (vsip_scalar_d)i); return; } void vsip_correlate1d_d( const vsip_corr1d_d *cor, vsip_bias bias, const vsip_vview_d *h, const vsip_vview_d *x, const vsip_vview_d *y) { vsip_vview_d xxr,xxi,hhr,hhi, *xr = VI_vrealview_d(cor->x,&xxr), *xi = VI_vimagview_d(cor->x,&xxi), *hr = VI_vrealview_d(cor->h,&hhr), *hi = VI_vimagview_d(cor->h,&hhi); xr->length = cor->x->length - x->length; VI_vfill_d(0,xr); xr->offset = xr->length; xr->length = x->length; VI_vcopy_d_d(x,xr); xr->offset = 0; xr->length = cor->x->length; hr->length = h->length; VI_vcopy_d_d(h,hr); hr->offset = hr->length; hr->length = cor->h->length - h->length; VI_vfill_d(0,hr); hr->offset = 0; hr->length = cor->h->length; VI_vfill_d(0,hi); VI_vfill_d(0,xi); vsip_ccfftip_d(cor->fft,cor->h); vsip_ccfftip_d(cor->fft,cor->x); vsip_cvjmul_d(cor->x,cor->h,cor->x); vsip_cvconj_d(cor->x,cor->x); vsip_rscvmul_d(1/(vsip_scalar_d)cor->N,cor->x,cor->x); vsip_ccfftip_d(cor->fft,cor->x); switch(cor->support){ case VSIP_SUPPORT_FULL: xr->offset = xr->length - cor->mn; xr->length = y->length; if(bias == VSIP_UNBIASED){ VI_vunbiasfull_d(cor,xr,y); } else { VI_vcopy_d_d(xr,y); } break; case VSIP_SUPPORT_SAME: xr->offset = xr->length - cor->mn + (cor->m-1)/2; xr->length = y->length; if(bias == VSIP_UNBIASED){ VI_vunbiassame_d(cor,xr,y); } else { VI_vcopy_d_d(xr,y); } break; case VSIP_SUPPORT_MIN: xr->offset = xr->length - cor->mn + cor->m -1; xr->length = y->length; if(bias == VSIP_UNBIASED){ vsip_svmul_d(1.0/(vsip_scalar_d)cor->m,xr,y); } else { VI_vcopy_d_d(xr,y); } break; } return; } <file_sep>/* Created RJudd September 15, 1999*/ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #ifndef _vsip_cludattributes_d_h #define _vsip_cludattributes_d_h 1 #include"vsip.h" #include"VI.h" #include"vsip_cmviewattributes_d.h" #include"vsip_cvviewattributes_d.h" #include"vsip_vviewattributes_vi.h" struct vsip_cludattributes_d{ vsip_cmview_d* LU; vsip_cmview_d LLU; vsip_index* P; vsip_length N; }; #endif /* _vsip_cludattributes_d */ <file_sep>/* Created RJudd Oct 26, 2012 */ /* Retired */ /* https://github.com/rrjudd/jvsip */ /*********************************************************************** // This code includes no warranty, express or implied, including the / // warranties of merchantability and fitness for a particular purpose./ // No person or entity assumes any legal liability or responsibility / // for the accuracy, completeness, or usefulness of an information / // apparatus, product, or process disclosed, or represents that its / // use would not infringe privately owned rights. / **********************************************************************/ /* created by modifying vsip_vfill_si.c */ #include"vsip.h" #include"vsip_vviewattributes_vi.h" void vsip_vfill_vi(vsip_scalar_vi alpha, const vsip_vview_vi* r) { unsigned int n = (unsigned int) r->length; int rst = (int) r->stride; vsip_scalar_vi *rp = (r->block->array) + r->offset; while(n-- > 0){ *rp = alpha; rp += rst; } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vget_put_uc.h,v 2.0 2003/02/22 15:23:36 judd Exp $ */ static void vget_put_uc(void){ printf("********\nTEST vget_put_uc\n"); { vsip_scalar_uc data_a[] = { 0, 1, 1, 0, 1, 0}; vsip_scalar_uc ans[] = { 0, 1, 1, 0, 1, 0}; vsip_block_uc *block_a = vsip_blockbind_uc(data_a,6,VSIP_MEM_NONE); vsip_vview_uc *a = vsip_vbind_uc(block_a,0,1,6); vsip_block_uc *block_b = vsip_blockcreate_uc(50,VSIP_MEM_NONE); vsip_vview_uc *b = vsip_vbind_uc(block_b, 35,-2,6); vsip_index i; vsip_blockadmit_uc(block_a,VSIP_TRUE); /* copy <a> into <b> */ for(i=0; i<6; i++) vsip_vput_uc(b,i,vsip_vget_uc(a,i)); /* check <a> against ans */ printf("check unit stride compact view\n"); for(i=0; i<6; i++){ vsip_scalar_uc chk = (ans[i] - vsip_vget_uc(a,i)); (chk == 0) ? printf("correct\n") : printf("error\n"); fflush(stdout); } printf("check general stride view\n"); for(i=0; i<6; i++){ vsip_scalar_uc chk = (ans[i] - vsip_vget_uc(a,i)); (chk == 0) ? printf("correct\n") : printf("error\n"); fflush(stdout); } vsip_valldestroy_uc(a); vsip_valldestroy_uc(b); } return; } <file_sep>/* Created RJudd September 23, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vput_mi.c,v 2.0 2003/02/22 15:19:17 judd Exp $ */ #include"vsip.h" #include"vsip_vviewattributes_mi.h" void (vsip_vput_mi)( const vsip_vview_mi *v, vsip_index i, vsip_scalar_mi s) { vsip_offset offset = (vsip_offset)((v->offset + (vsip_stride)i * v->stride) * 2); *(v->block->array + offset) = s.r; offset++; *(v->block->array + offset) = s.c; return; } <file_sep>/* Created RJudd For Core January 10, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vcreate_kaiser_f.c,v 2.0 2003/02/22 15:19:12 judd Exp $ */ /* Removed Development Mode RJudd Sept 00 */ #include"vsip.h" #include"vsip_vviewattributes_f.h" #include"VI_vcreate_f.h" #define a1 ((vsip_scalar_f)2.2499997) #define a2 ((vsip_scalar_f)1.2656208) #define a3 ((vsip_scalar_f)0.3163866) #define a4 ((vsip_scalar_f)0.0444479) #define a5 ((vsip_scalar_f)0.0039444) #define a6 ((vsip_scalar_f)0.0002100) #define b1 ((vsip_scalar_f)0.39894228) /* 1/sqrt(2pi) */ #define b2 ((vsip_scalar_f)0.02805063) #define b3 ((vsip_scalar_f)0.029219405) #define b4 ((vsip_scalar_f)0.0447422145) static vsip_scalar_f VI_Io_f(vsip_scalar_f x) { vsip_length n; vsip_scalar_f ans,x0,x1,n0,diff; diff = 1; x1 = x * x * (vsip_scalar_f).25; x0 = x1; ans = 1 + x1; n = 1; n0 = 1; while(diff > .00000001){ n++; n0 *= (vsip_scalar_f)n; x1 *= x0; diff = x1/(n0 * n0); ans += diff; } return ans; } vsip_vview_f* vsip_vcreate_kaiser_f( vsip_length N, vsip_scalar_f beta, vsip_memory_hint h) { vsip_vview_f *a; a = VI_vcreate_f(N,h); if(a == NULL) return (vsip_vview_f*)NULL; { vsip_length n = 0; vsip_scalar_f *ap = (a->block->array) + a->offset, Ibeta, x = beta, c1 = (vsip_scalar_f)2.0 / (N -1 ); if((vsip_scalar_f)fabs(x) <= 3.0){ x /= 3.0; x *= x; Ibeta = (vsip_scalar_f)1 + x * (a1 + x * (a2 + x * (a3 + x * (a4 + x * (a5 + x * a6))))); } else { Ibeta = VI_Io_f(x); } /* Note this is always unit stride */ while(n < N){ vsip_scalar_f c3 = c1 * n - 1; if(c3 > 1.0) c3 = 1.0; x = beta * (vsip_scalar_f)sqrt(1 - (c3 * c3)); if((vsip_scalar_f)fabs(x) <= 3.0){ x /= 3.0; x *= x; *ap++ = ((vsip_scalar_f)1 + x * (a1 + x * (a2 + x * (a3 + x * (a4 + x * (a5 + x * a6)))))) / Ibeta; } else { *ap++ = VI_Io_f(x)/ Ibeta; } n++; } } return a; } <file_sep># Elementary Math functions from vsip import * def __isSizeCompatible(a,b): if 'mview' in a.type and 'mview' in b.type: if (a.rowlength == b.rowlength) and (a.collength == b.collength): return True elif 'vview' in a.type and 'vview' in b.type: if a.length == b.length: return True else: return False def __isView(a): return 'pyJvsip' in repr(a) def arg(a,b): f={'cvview_fvview_f':vsip_varg_f, 'cvview_dvview_d':vsip_varg_d, 'cmview_fmview_f':vsip_marg_f, 'cmview_dmview_d':vsip_marg_d} assert __isView(a) and __isView(b), 'Arguments must be pyJvsip views' t=a.type+b.type assert t in f, 'Type <:%s:> not recognized for function arg'%t assert __isSizeCompatible(a,b), 'Input views must be the same size' f[t](a.vsip,b.vsip) return b def conj(a,b): f={'cvview_fcvview_f':vsip_cvconj_f, 'cvview_dcvview_d':vsip_cvconj_d, 'cmview_fcmview_f':vsip_cmconj_f, 'cmview_dcmview_d':vsip_cmconj_d} assert __isView(a) and __isView(b), 'Arguments must be pyJvsip views' t=a.type+b.type assert t in f, 'Type <:%s:> not recognized for function cconj'%t assert __isSizeCompatible(a,b), 'Input views must be the same size' f[t](a.vsip,b.vsip) return b def cumsum(a,b): """ Cumulative sum function (see vsip_dscumsum_f). Works for matrix and vectors. For matrix does cumulative sum along rows or columns defined by the major attribute of the first argument. If the major attribute is COL then it is done by column; otherwise it is done by row. It is recommended to set the major attribute when calling the function since you don't know what it is unless you check it, and it is easier to set it than to check it. The function cumsum(a,b) may be done in place. """ assert __isView(a) and __isView(b), 'Arguments must be pyJvsip views in function cumsum' t=a.type+b.type f={'mview_dmview_d':vsip_mcumsum_d, 'mview_fmview_f':vsip_mcumsum_f, 'mview_imview_i':vsip_mcumsum_i, 'mview_simview_si':vsip_mcumsum_si, 'vview_dvview_d':vsip_vcumsum_d, 'vview_fvview_f':vsip_vcumsum_f, 'vview_ivview_i':vsip_vcumsum_i, 'vview_sivview_si':vsip_vcumsum_si} assert __isSizeCompatible(a,b), 'Arguments must be the same size for cumsum' assert t in f,'Type <:'+t+':> not supported by cumsum' if 'mview' in t: if a.major == 'COL': f[t](a.vsip,VSIP_COL,b.vsip) else: f[t](a.vsip,VSIP_ROW,b.vsip) else: f[t](a.vsip,b.vsip) return b def euler(a,b): assert __isView(a) and __isView(b), 'Arguments must be pyJvsip views in function cumsum' f={'mview_dcmview_d':vsip_meuler_d,'mview_fcmview_f':vsip_meuler_f, 'vview_dcvview_d':vsip_veuler_d,'vview_fcvview_f':vsip_veuler_f} t=a.type+b.type assert __isSizeCompatible(a,b),'Arguments must be the same size for euler' assert t in f,'Type <:'+t+':>not supported by euler' f[t](a.vsip,b.vsip) return b def mag(a,b): f={'cmview_dmview_d':vsip_cmmag_d,'cmview_fmview_f':vsip_cmmag_f, 'cvview_dvview_d':vsip_cvmag_d,'cvview_fvview_f':vsip_cvmag_f, 'vview_dmview_d':vsip_mmag_d,'vview_fmview_f':vsip_mmag_f, 'vview_dvview_d':vsip_vmag_d,'vview_fvview_f':vsip_vmag_f, 'vview_ivview_i':vsip_vmag_i,'vview_sivview_si':vsip_vmag_si} assert __isView(a) and __isView(b), 'Arguments must be pyJvsip views in function mag' t=a.type+b.type assert __isSizeCompatible(a,b), 'Arguments must be the same size for mag' assert t in f,'Type <:'+t+':> not supported by mag' f[t](a.vsip,b.vsip) return b def cmagsq(a,b): f={'cmview_dmview_d':vsip_mcmagsq_d, 'cmview_fmview_f':vsip_mcmagsq_f, 'cvview_dvview_d':vsip_vcmagsq_d, 'cvview_fvview_f':vsip_vcmagsq_f} assert __isView(a) and __isView(b), 'Arguments must be pyJvsip views in function cmagsq' t=a.type+b.type assert __isSizeCompatible(a,b), 'Arguments must be the same size for cmagq' assert t in f,'Type <:'+t+':> not supported by cmagsq' f[t](a.vsip,b.vsip) return b def modulate(a,nu,phi,b): """ See VSIP document for more information on vsip_vmodulate_f Modulate takes a frequency and phase argument and returns a phase argument that would be used if modulate is called again for the same sequence. For pyJvsip modulate returns a tuple of the phase and the output vector. phiNew,b=modulate(a,nu,phiOld,b) """ assert __isView(a) and __isView(b), 'First and last arguments must be pyJvsip views in function modulate' f={'cvview_dcvview_d':vsip_cvmodulate_d, 'vview_dcvview_d':vsip_vmodulate_d, 'cvview_fcvview_f':vsip_cvmodulate_f, 'vview_fcvview_f':vsip_vmodulate_f} t=a.type+b.type assert __isSizeCompatible(a,b), 'Input/Output must be the same size for modulate' assert t in f,'Type <:'+t+':> not supported by modulate' phiNew=f[t](a,nu,phi,b) return (phiNew,b) def neg(a,b): f={'cmview_d:cmview_d':vsip_cmneg_d, 'cmview_fcmview_f':vsip_cmneg_f, 'cvview_dcvview_d':vsip_cvneg_d, 'cvview_fcvview_f':vsip_cvneg_f, 'mview_dmview_d':vsip_mneg_d, 'mview_fmview_f':vsip_mneg_f, 'vview_dvview_d':vsip_vneg_d, 'vview_fvview_f':vsip_vneg_f, 'vview_ivview_i':vsip_vneg_i, 'vview_sivview_si':vsip_vneg_si} assert __isView(a) and __isView(b), 'Arguments must be pyJvsip views in function neg' t=a.type+b.type assert __isSizeCompatible(a,b),'Input/Output views must be the same size for neg' assert t in f,'Type <:'+t+':> not supported for neg' f[t](a.vsip,b.vsip) return b def recip(a,b): f={'cmview_dcmview_d':vsip_cmrecip_d, 'cmview_fcmview_f':vsip_cmrecip_f, 'cvview_dcvview_d':vsip_cvrecip_d, 'cvview_fcvview_f':vsip_cvrecip_f, 'mview_dmview_d':vsip_mrecip_d, 'mview_fmview_f':vsip_mrecip_f, 'vview_dvview_d':vsip_vrecip_d, 'vview_fvview_f':vsip_vrecip_f} assert __isView(a) and __isView(b), 'Arguments must be pyJvsip views in function recip' t=a.type+b.type assert __isSizeCompatible(a,b),'Input/Output views must be the same size for recip' assert t in f,'Type <:'+t+':> not supported for recip' f[t](a.vsip,b.vsip) return b def rsqrt(a,b): f={'mview_dmview_d':vsip_mrsqrt_d, 'mview_fmview_f':vsip_mrsqrt_f, 'vview_dvview_d':vsip_vrsqrt_d, 'vview_fvview_f':vsip_vrsqrt_f} assert __isView(a) and __isView(b), 'Arguments must be pyJvsip views in function rsqrt' t=a.type+b.type assert __isSizeCompatible(a,b),'Input/Output views must be the same size for rsqrt' assert t in f,'Type <:'+t+':> not supported for rsqrt' f[t](a.vsip,b.vsip) return b def sq(a,b): f={'mview_dmview_d':vsip_msq_d, 'mview_fmview_f':vsip_msq_f, 'vview_dvview_d':vsip_vsq_d, 'vview_fvview_f':vsip_vsq_f} assert __isView(a) and __isView(b), 'Arguments must be pyJvsip views in function sq' t=a.type+b.type assert __isSizeCompatible(a,b),'Input/Output views must be the same size for sq' assert t in f,'Type <:'+t+':> not supported for sq' f[t](a.vsip,b.vsip) return b #vsip_sfloor_p_p def floor(a,r): f={'mview_dmview_d':vsip_mfloor_d_d, 'mview_fmview_f':vsip_mfloor_f_f, 'vview_dvview_d':vsip_vfloor_d_d, 'vview_fvview_f':vsip_vfloor_f_f, 'mview_dmview_i':vsip_mfloor_d_i, 'mview_fmview_i':vsip_mfloor_f_i, 'vview_dvview_i':vsip_vfloor_d_i, 'vview_fvview_i':vsip_vfloor_f_i} assert __isView(a) and __isView(r), 'Arguments must be pyJvsip views in function floor' t=a.type+r.type assert __isSizeCompatible(a,r),'Input/Output views must be the same size for floor' assert t in f,'Type <:%s:> not supported for floor'%t f[t](a.vsip,r.vsip) return r # vsip_sceil_p_p def ceil(a,r): f={'mview_dmview_d':vsip_mceil_d_d, 'mview_fmview_f':vsip_mceil_f_f, 'vview_dvview_d':vsip_vceil_d_d, 'vview_fvview_f':vsip_vceil_f_f, 'mview_dmview_i':vsip_mceil_d_i, 'mview_fmview_i':vsip_mceil_f_i, 'vview_dvview_i':vsip_vceil_d_i, 'vview_fvview_i':vsip_vceil_f_i} assert __isView(a) and __isView(r), 'Arguments must be pyJvsip views in function ceil' t=a.type+r.type assert __isSizeCompatible(a,r),'Input/Output views must be the same size for ceil' assert t in f,'Type <:%s:> not supported for ceil'%t f[t](a.vsip,r.vsip) return r # vsip_sround_p_p def round(a,r): f={'mview_dmview_d':vsip_mround_d_d, 'mview_fmview_f':vsip_mround_f_f, 'vview_dvview_d':vsip_vround_d_d, 'vview_fvview_f':vsip_vround_f_f, 'mview_dmview_i':vsip_mround_d_i, 'mview_fmview_i':vsip_mround_f_i, 'vview_dvview_i':vsip_vround_d_i, 'vview_fvview_i':vsip_vround_f_i} assert __isView(a) and __isView(r), 'Arguments must be pyJvsip views in function round' t=a.type+r.type assert __isSizeCompatible(a,r),'Input/Output views must be the same size for round' assert t in f,'Type <:%s:> not supported for round'%t f[t](a.vsip,r.vsip) return r <file_sep>from vsip import * # Python support functions def init(): return vsip_init(None) def finalize(): return vsip_finalize(None) def getType(v): """ Returns a tuple with True if a vsip type is found, plus a string indicating the type. For instance for a = vsip_vcreate_f(10,VSIP_MEM_NONE) will return for the call getType(a) (True,'vview_f') also returns types of scalars derived from structure. for instance c = vsip_cscalar_d() will return for getType(c) the tuple (True, 'cscalar_d'). attr = vsip_mattr_d() will return for getType(attr) the tuple (True, 'mattr_d') If float or int type is passed in returns (True,'scalar') If called with a non VSIPL type returns (False, 'Not a VSIPL Type') """ t = repr(v).rpartition('vsip_') if t[1] == 'vsip_': return(True,t[2].partition(" ")[0]) elif isinstance(v,float): return(True,'scalar') elif isinstance(v,int): return(True,'scalar') else: return(False,'Not a VSIPL Type') def cscalarToComplex(a): """ for a scalar of type vsip_cscalar return a python complex scalar value """ t=['cscalar_f','cscalar_d'] if getType(a)[1] in t: return complex(a.r,a.i) elif type(a) == float or type(a) == int: return a else: assert False,'Type not supported by cscalarToComplex.' def complexToCscalar(t,a): if t == 'cscalar_d': x=vsip_cscalar_d() x.r=a.real x.i=a.imag return x elif t == 'cscalar_f': x=vsip_cscalar_f() x.r=a.real x.i=a.imag return x elif type(a) == float or type(a) == int: return a else: assert False,'Type %s not supported by complexToCscalar'%t def miToTuple(a): return (a.r,a.c) def index(a): t = getType(a)[1] tm=['mview_d','mview_f','cmview_f','cmview_d','mview_i','mview_si', 'mview_uc','mview_bl'] tv=['vview_d','vview_f','cvview_f','cvview_d','vview_i','vview_si', 'vview_uc','vview_mi','vview_vi','vview_bl'] if t in tm: return vsip_scalar_mi() elif t in tv: return vindexptr() else: assert False,'Type %s not supported by index'%t def pyIndex(a): t=getType(a)[1] if t == 'scalar_mi': return (a.r, a.c) elif t == 'scalar_vi': return vindexptrToInt(a) else: assert False,'Type %s not suported by pyIndex'%t def create(atype,atuple): """ Create a vsipl object associated with a type. Note that scalar types and attribute types are not created here. The argument 'atuple' is a tuple containing necessary data to create the object defined by atype. The contents of the tuple are the same as the arguments described in the prototypes of the C VSIPL document. For instance create('block_f',(10000,VSIP_MEM_NONE)) is the same as vsip_blockcreate_f(10000,VSIP_MEM_NONE); """ if type(atuple) == int: l=(atuple,) elif type(atuple) == tuple: l=atuple else: assert False,'Second argument must be int or tuple corresponding to C VSIPL argument list' f={'block_f':'vsip_blockcreate_f(l[0],l[1])', 'block_d':'vsip_blockcreate_d(l[0],l[1])', 'cblock_f':'vsip_cblockcreate_f(l[0],l[1])', 'cblock_d':'vsip_cblockcreate_d(l[0],l[1])', 'block_i':'vsip_blockcreate_i(l[0],l[1])', 'block_si':'vsip_blockcreate_si(l[0],l[1])', 'block_uc':'vsip_blockcreate_uc(l[0],l[1])', 'block_vi':'vsip_blockcreate_vi(l[0],l[1])', 'block_mi':'vsip_blockcreate_mi(l[0],l[1])', 'block_bl':'vsip_blockcreate_bl(l[0],l[1])', 'blackman_d':'vsip_vcreate_blackman_d(l[0], l[1])', 'hanning_d':'vsip_vcreate_hanning_d(l[0], l[1])', 'kaiser_d':'vsip_vcreate_kaiser_d(l[0], l[1], l[2])', 'cheby_d':'vsip_vcreate_cheby_d(l[0], l[1], l[2])', 'blackman_f':'vsip_vcreate_blackman_f(l[0], l[1])', 'hanning_f':'vsip_vcreate_hanning_f(l[0], l[1])', 'kaiser_f':'vsip_vcreate_kaiser_f(l[0],l[1],l[2])', 'cheby_f':'vsip_vcreate_cheby_f(l[0], l[1], l[2])', 'vview_f':'vsip_vcreate_f(l[0],l[1])', 'vview_d':'vsip_vcreate_d(l[0],l[1])', 'cvview_f':'vsip_cvcreate_f(l[0],l[1])', 'cvview_d':'vsip_cvcreate_d(l[0],l[1])', 'vview_i':'vsip_vcreate_i(l[0],l[1])', 'vview_si':'vsip_vcreate_si(l[0],l[1])', 'vview_uc':'vsip_vcreate_uc(l[0],l[1])', 'vview_bl':'vsip_vcreate_bl(l[0],l[1])', 'vview_vi':'vsip_vcreate_vi(l[0],l[1])', 'vview_mi':'vsip_vcreate_mi(l[0],l[1])', 'mview_f':'vsip_mcreate_f(l[0],l[1],l[2],l[3])', 'mview_d':'vsip_mcreate_d(l[0],l[1],l[2],l[3])', 'cmview_f':'vsip_cmcreate_f(l[0],l[1],l[2],l[3])', 'cmview_d':'vsip_cmcreate_d(l[0],l[1],l[2],l[3])', 'mview_i':'vsip_mcreate_i(l[0],l[1],l[2],l[3])', 'mview_si':'vsip_mcreate_si(l[0],l[1],l[2],l[3])', 'mview_uc':'vsip_mcreate_uc(l[0],l[1],l[2],l[3])', 'mview_bl':'vsip_mcreate_bl(l[0],l[1],l[2],l[3])', 'lu_d':'vsip_lud_create_d(l[0])', 'lu_f':'vsip_lud_create_f(l[0])', 'clu_d':'vsip_clud_create_d(l[0])', 'clu_f':'vsip_clud_create_f(l[0])', 'qr_d':'vsip_qrd_create_d(l[0],l[1],l[2])', 'qr_f':'vsip_qrd_create_f(l[0],l[1],l[2])', 'cqr_d':'vsip_cqrd_create_d(l[0],l[1],l[2])', 'cqr_f':'vsip_cqrd_create_f(l[0],l[1],l[2])', 'ccfftip_f':'vsip_ccfftip_create_f(l[0],l[1],l[2],l[3],l[4])', 'ccfftop_f':'vsip_ccfftop_create_f(l[0],l[1],l[2],l[3],l[4])', 'rcfftop_f':'vsip_rcfftop_create_f(l[0],l[1],l[2],l[3])', 'crfftop_f':'vsip_crfftop_create_f(l[0],l[1],l[2],l[3])', 'ccfftip_d':'vsip_ccfftip_create_d(l[0],l[1],l[2],l[3],l[4])', 'ccfftop_d':'vsip_ccfftop_create_d(l[0],l[1],l[2],l[3],l[4])', 'rcfftop_d':'vsip_rcfftop_create_d(l[0],l[1],l[2],l[3])', 'crfftop_d':'vsip_crfftop_create_d(l[0],l[1],l[2],l[3])', 'ccfftmip_f':'vsip_ccfftmip_create_f(l[0],l[1],l[2],l[3],l[4],l[5],l[6])', 'ccfftmop_f':'vsip_ccfftmop_create_f(l[0],l[1],l[2],l[3],l[4],l[5],l[6])', 'rcfftmop_f':'vsip_rcfftmop_create_f(l[0],l[1],l[2],l[3],l[4],l[5])', 'crfftmop_f':'vsip_crfftmop_create_f(l[0],l[1],l[2],l[3],l[4],l[5])', 'ccfftmip_d':'vsip_ccfftmip_create_d(l[0],l[1],l[2],l[3],l[4],l[5],l[6])', 'ccfftmop_d':'vsip_ccfftmop_create_d(l[0],l[1],l[2],l[3],l[4],l[5],l[6])', 'rcfftmop_d':'vsip_rcfftmop_create_d(l[0],l[1],l[2],l[3],l[4],l[5])', 'crfftmop_d':'vsip_crfftmop_create_d(l[0],l[1],l[2],l[3],l[4],l[5])', 'chol_f':'vsip_chold_create_f(l[0],l[1])', 'chol_d':'vsip_chold_create_d(l[0],l[1])', 'cchol_f':'vsip_cchold_create_f(l[0],l[1])', 'cchol_d':'vsip_cchold_create_d(l[0],l[1])', 'sv_f':'vsip_svd_create_f(l[0],l[1],l[2],l[3])', 'sv_d':'vsip_svd_create_d(l[0],l[1],l[2],l[3])', 'fir_f':'vsip_fir_create_f(l[0],l[1],l[2],l[3],l[4],l[5],l[6])', 'fir_d':'vsip_fir_create_d(l[0],l[1],l[2],l[3],l[4],l[5],l[6])', 'cfir_f':'vsip_cfir_create_f(l[0],l[1],l[2],l[3],l[4],l[5],l[6])', 'cfir_d':'vsip_cfir_create_d(l[0],l[1],l[2],l[3],l[4],l[5],l[6])', 'randstate':'vsip_randcreate(l[0],l[1],l[2],l[3])'} assert atype in f,'Type %s Not a valid type for create.'%atype return eval(f[atype]) def destroy(obj): """ Free memory associated with a vsipl object created by the "create" function. Note that view creates also create a block object. To properly destroy all data associated with the view both the view and the block must be destroyed. However a block may have several views associated with it. Destroying the block before all associated views are destroyed is an error. Note the view destroy returns the block object it is associated with. so destroy(destroy(view)) is the same as an all destroy. For this module it is up to the user to keep track of when an all destroy can be done and when a block reference needs to be maintained. """ f={'block_f' :vsip_blockdestroy_f, 'block_d' :vsip_blockdestroy_d, 'cblock_f' :vsip_cblockdestroy_f, 'cblock_d' :vsip_cblockdestroy_d, 'block_i' :vsip_blockdestroy_i, 'block_si' :vsip_blockdestroy_si, 'block_uc' :vsip_blockdestroy_uc, 'block_vi' :vsip_blockdestroy_vi, 'block_mi' :vsip_blockdestroy_mi, 'block_bl' :vsip_blockdestroy_bl, 'vview_f' :vsip_vdestroy_f, 'vview_d' :vsip_vdestroy_d, 'cvview_f' :vsip_cvdestroy_f, 'cvview_d' :vsip_cvdestroy_d, 'vview_i' :vsip_vdestroy_i, 'vview_si' :vsip_vdestroy_si, 'vview_uc' :vsip_vdestroy_uc, 'vview_bl' :vsip_vdestroy_bl, 'vview_vi' :vsip_vdestroy_vi, 'vview_mi' :vsip_vdestroy_mi, 'mview_f' :vsip_mdestroy_f, 'mview_d' :vsip_mdestroy_d, 'cmview_f' :vsip_cmdestroy_f, 'cmview_d' :vsip_cmdestroy_d, 'mview_i' :vsip_mdestroy_i, 'mview_si' :vsip_mdestroy_si, 'mview_uc' :vsip_mdestroy_uc, 'mview_bl' :vsip_mdestroy_bl, 'lu_d' :vsip_lud_destroy_d, 'lu_f' :vsip_lud_destroy_f, 'clu_d' :vsip_clud_destroy_d, 'clu_f' :vsip_clud_destroy_f, 'qr_d' :vsip_qrd_destroy_d, 'qr_f' :vsip_qrd_destroy_f, 'cqr_d' :vsip_cqrd_destroy_d, 'cqr_f' :vsip_cqrd_destroy_f, 'fft_f' :vsip_fft_destroy_f, 'fft_d' :vsip_fft_destroy_d, 'fftm_f' :vsip_fftm_destroy_f, 'fftm_d' :vsip_fftm_destroy_d, 'chol_f' :vsip_chold_destroy_f, 'chol_d' :vsip_chold_destroy_d, 'cchol_f' :vsip_cchold_destroy_f, 'cchol_d' :vsip_cchold_destroy_d, 'sv_f' :vsip_svd_destroy_f, 'sv_d' :vsip_svd_destroy_d, 'fir_f' :vsip_fir_destroy_f, 'fir_d' :vsip_fir_destroy_d, 'cfir_f' :vsip_cfir_destroy_f, 'cfir_d' :vsip_cfir_destroy_d, 'randstate' :vsip_randdestroy} t=getType(obj)[1] assert t in f,'Type %s not supported by destroy'%t return f[t](obj) # VSIPL scalar functions # s on front denotes scalar and prevents conflict with overloaded view functions def sconj(a): t=getType(a)[1] f={'cscalar_f':vsip_conj_f, 'cscalar_d':vsip_conj_d} assert t in f,'Type %s not supported by sconj'%t return f[t](a) def scmplx(p,a,b): """ p is a string designating a type, either scalar_f or scalar_d. """ if p == 'scalar_f': return vsip_cmplx_f(a,b) elif p == 'scalar_d': return vsip_cmplx_d(a,b) else: assert False,'Type %s not defined for cmplx.'%p def scsub(a,b): t=getType(a)[1] assert t == getType(b)[1],'Type of arguments must agree in scsub.' if t == 'cscalar_f': return vsip_csub_f(a,b) elif t == 'cscalar_d': return vsip_csub_d(a,b) else: assert False,'Type %s not defined for complex subtraction scsub.'%p def smag(a): if type(a) == float or type(a) == int: if(a < 0): return -a else: return a t = getType(a)[1] if t == 'cscalar_f': return vsip_cmag_f(a) elif t == 'cscalar_d': return vsip_cmag_d(a) else: assert False,'Type %s not recognized by mag.'%t def _vget(a,b): # used internal to this module f={ 'vview_f':vsip_vget_f, 'vview_d':vsip_vget_d, 'vview_i':vsip_vget_i, 'vview_si':vsip_vget_si, 'vview_uc':vsip_vget_uc, 'vview_vi':vsip_vget_vi} assert b in f,'Type %s not found for private function _vget'%b return [f[b](a,i) for i in range(getlength(a))] def _cvget(a,b): # used internal to this module f={'cvview_f':vsip_cvget_f, 'cvview_d':vsip_cvget_d} retval = [] for i in range(getlength(a)): val=f[b](a,i) retval.append(complex(val.r,val.i)) return retval def _mget(a,b): # used internal to this module retval=list() attr = getattrib(a) f={ 'mview_f':vsip_mget_f, 'mview_d':vsip_mget_d, 'mview_i':vsip_mget_i, 'mview_si':vsip_mget_si, 'mview_uc':vsip_mget_uc} for i in range(attr.col_length): retval +=[f[b](a,i,j) for j in range(attr.row_length)] return retval def _cvget(a,b): # used internal to this module f={'cvview_f':vsip_cvget_f, 'cvview_d':vsip_cvget_d} return [cscalarToComplex(f[b](a,i)) for i in range(getlength(a))] def _cmget(a,b): # used internal to this module retval=list() attr = getattrib(a) f={ 'cmview_f':vsip_cmget_f, 'cmview_d':vsip_cmget_d} for i in range(attr.col_length): retval +=[cscalarToComplex(f[b](a,i,j)) for j in range(attr.row_length)] return retval def _bl(a): # used internal to this module if a == 0: return False else: return True def _vget_bl(a,b): return [_bl(vsip_vget_bl(a,i)) for i in range(getlength(a))] def _mget_bl(a,b): # used internal to this module retval=list() attr=getattrib(a) for i in range(attr.col_length): retval += [_bl(vsip_mget_bl(a,i,j)) for j in range(attr.row_length)] def _vget_mi(a,b): # used internal to this module return [miToTuple(vsip_vget_mi(a,i)) for i in range(getlength(a))] def vList(v): """ This function copies the data from a VSIPL view into a flat list. If the view is a matrix view it copies the data by row (flattens it). VSIP complex is copied into python complex. Type _bl (bool) is copied into True, False """ t=getType(v) f={ 'vview_f': _vget, 'vview_d': _vget, 'mview_f': _mget, 'mview_d': _mget, 'cvview_f': _cvget, 'cvview_d': _cvget, 'cmview_f': _cmget, 'cmview_d': _cmget, 'vview_i': _vget, 'mview_i': _mget, 'vview_si': _vget, 'mview_si': _mget, 'vview_uc': _vget, 'mview_uc': _mget, 'vview_vi': _vget, 'vview_bl': _vget_bl, 'mview_bl': _mget_bl, 'vview_mi': _vget_mi} if t[0]: return f[t[1]](v,t[1]) else: return list() def mList(m): f={'mview_f':(), 'mview_d':(), 'cmview_f':(), 'cmview_d':(), 'mview_i':(), 'mview_si':(), 'mview_uc':(), 'mview_bl':()} t=getType(m) l=[] assert t[1] in f,'Type <:%s:> not a supporte type for mList.'%t[1] attr=getattrib(m) attr0=getattrib(m) n=range(attr.col_length) attr.col_length=1 putattrib(m,attr) for i in n: l.append(vList(m)) attr.offset += attr.col_stride putattrib(m,attr) putattrib(m,attr0) return l def listV(t,v): """ This function is not very 'smart' This function creates a vsipl double or integer vector and copies a list into VSIPL. It will only copy into vectors of type double (real or complex) or of type int. That is to say vectors of type vsip_vview_d, vsip_cvview_d, and vsip_vview_i. The list is expected to be of a float, integer, or Python complex type. It is expected to be flat. List of lists is not allowed here. No error checking is done. The input list must be of a single type (integer, complex, float). The first element of the list is checked and depending on the result a vsipl vector is created and list comprehension is used to copy it into VSIPL. If things don't work out python will probably complain. """ n=len(v) f={'vview_d':vsip_vcreate_d, 'vview_f':vsip_vcreate_f} if isinstance(v[0],float) and t in f: retval=f[t](n,VSIP_MEM_NONE) [put(retval,i,v[i]) for i in range(n)] return retval elif isinstance(v[0],int): retval=vsip_vcreate_i(n,VSIP_MEM_NONE) [put(retval,i,v[i]) for i in range(n)] return retval elif isinstance(v[0],complex): retval=vsip_cvcreate_d(n,VSIP_MEM_NONE) [put(retval,i,v[i]) for i in range(n)] return retval else: assert False,'listV failed' def _sizeVattr(a): # used internal to this module return a.offset + a.length * abs(a.stride); def _sizeMattr(a): # used internal to this module str_r=abs(a.row_stride) str_c=abs(a.col_stride) if str_r > str_c: return a.offset + str_r * a.row_length else: return a.offset + str_c * a.col_length def _sizeAttr(a): f={ 'vattr_f': _sizeVattr, 'vattr_d': _sizeVattr, 'cvattr_f':_sizeVattr, 'cvattr_d':_sizeVattr, 'vattr_vi':_sizeVattr, 'vattr_mi':_sizeVattr, 'vattr_bl':_sizeVattr, 'vattr_i': _sizeVattr, 'vattr_si':_sizeVattr, 'vattr_uc':_sizeVattr, 'mattr_f': _sizeMattr, 'mattr_d': _sizeMattr, 'cmattr_f':_sizeMattr, 'cmattr_d':_sizeMattr, 'mattr_bl':_sizeMattr, 'mattr_i': _sizeMattr, 'mattr_si':_sizeMattr, 'mattr_uc':_sizeMattr} t=getType(a) return f[t](a) def _blocktype(vt): # used internal to this module f=f={ 'vattr_f':'block_f', 'vattr_d':'block_d', 'cvattr_f':'cblock_f', 'cvattr_d':'cblock_d', 'mattr_f':'block_f', 'mattr_d':'block_d', 'cmattr_f':'cblock_f', 'cmattr_d':'cblock_d', 'vattr_vi':'block_vi', 'vattr_mi':'block_mi', 'vattr_bl':'block_bl', 'vattr_i':'block_i', 'vattr_si':'block_si', 'vattr_uc':'block_uc', 'mattr_bl':'block_bl', 'mattr_i':'block_i', 'mattr_si':'block_si', 'mattr_uc':'block_uc'} return f[vt] def _blockcreate(l,t): # used internal to this module f={ 'block_f':vsip_blockcreate_f, 'block_d':vsip_blockcreate_d, 'cblock_f':vsip_cblockcreate_f, 'cblock_d':vsip_cblockcreate_d, 'block_i':vsip_blockcreate_i, 'block_si':vsip_blockcreate_si, 'block_uc':vsip_blockcreate_uc, 'block_vi':vsip_blockcreate_vi, 'block_mi':vsip_blockcreate_mi, 'block_bl':vsip_blockcreate_bl} return f[t](l,VSIP_MEM_NONE) # VU Functions def dataGen(a): #print(getType(a)[1]) from math import cos as ccos,sin as ssin,pi def _gen(a): #print(getType(a)[1]) N=int(getlength(a)) assert N > 1,'Vector input length required to be greater than one.' npm=N/2 c=pi/float(N) put(a,0,(float(N) - 1.0)/2.0) indx=0; if N % 2: for i in range(npm): indx = i+1 x = c * float(i) + c x = -0.5j * ccos(x)/ssin(x) - 0.5 put(a,indx,x) for i in range(npm,0,-1): indx +=1 x=get(a,i) x.i=-x.i put(a,indx,x) else: npm -= 1 for i in range(npm): indx = i+1 x = c * float(i) + c x = -0.5j * ccos(x)/ssin(x) - 0.5 put(a,indx,x) x=-0.5 indx +=1 put(a,indx,x) for i in range(npm,0,-1): indx +=1 x=get(a,i) x.i=-x.i put(a,indx,x) t=getType(a) sz=() if t[0]: sz=size(a) if len(sz) == 3 and (t[1] == 'cvview_f' or t[1] == 'cvview_d'): _gen(a) return a else: assert False,'Not a supported type for dataGen. Should be a vsip complex float vector vector' def randCreate(t,seed,length): """ Create a VSIPL vector view and populate it with random numbers. type "t" is (for example) 'vview_dnprngU' for double vector ('vview_d') filled with uniform ('U') numbers from the non-portable random number generator ('nprng => VSIP_NPRNG'). Another example would be 'cvview_fprngN' for a complex float vector('cvview_f') tilled with a normal distribution ('N') from the VSIP defined portable random number generator ('prng' => VSIP_PRNG). """ def rcfn(t,s,f,l): a=view('vview_d',l); s=rand(s,1,1,f) randn(s,a) randDestroy(s) return a def rcfu(t,s,f,l): a=view('vview_d',l); s=rand(s,1,1,f) randu(s,a) randDestroy(s) return a f={'vview_dprngN':"rcfn('vview_d',seed,VSIP_PRNG,length)", 'vview_fprngN':"rcfn('vview_f',seed,VSIP_PRNG,length)", 'cvview_dprngN':"rcfn('cvview_d',seed,VSIP_PRNG,length)", 'cvview_fprngN':"rcfn('cvview_f',seed,VSIP_PRNG,length)", 'vview_dprngU':"rcfu('vview_d',seed,VSIP_PRNG,length)", 'vview_fprngU':"rcfu('vview_f',seed,VSIP_PRNG,length)", 'cvview_dprngU':"rcfu('cvview_d',seed,VSIP_PRNG,length)", 'cvview_fprngU':"rcfu('cvview_f',seed,VSIP_PRNG,length)", 'vview_dnprngN':"rcfn('vview_d',seed,VSIP_NPRNG,length)", 'vview_fnprngN':"rcfn('vview_d',seed,VSIP_NPRNG,length)", 'cvview_dnprngN':"rcfn('cvview_d',seed,VSIP_NPRNG,length)", 'cvview_fnprngN':"rcfn('cvview_f',seed,VSIP_NPRNG,length)", 'vview_dnprngU':"rcfu('vview_d',seed,VSIP_NPRNG,length)", 'vview_fnprngU':"rcfu('vview_f',seed,VSIP_NPRNG,length)", 'cvview_dnprngU':"rcfu('cvview_d',seed,VSIP_NPRNG,length)", 'cvview_fnprngU':"rcfu('cvview_f',seed,VSIP_NPRNG,length)"} assert t in f,'Type <:t:> not supported for randCreate'%t return eval(f[t]) # functions not closely related to VSIPL defined functionality def viewCreate(a): """ Create a vsip view object. The argument "a" is a view attribute. Use the attribute type and attribute state to create a view object. Return object on success, and False on failure NOTE: The size of the underlying block is the magnitutde of the maximum stride times the length of dimension associated with the stride plus the offset. This produces a block at least big enough to accomodate the view associated with the attribute. If a particular block size is required first create the block using the standard vsipl block create, and then create the view using vbind or mbind and then (if vbind or mbind are not sufficient) put the attribute using putattrib. """ t=getType(a) f={ 'vattr_f':putattrib(vbind(_blockcreate(_sizeAttr(a),_blocktype(t[1])),0,1,1),a), 'vattr_d':putattrib(vbind(_blockcreate(_sizeAttr(a),_blocktype(t[1])),0,1,1),a), 'cvattr_f':putattrib(vbind(_blockcreate(_sizeAttr(a),_blocktype(t[1])),0,1,1),a), 'cvattr_d':putattrib(vbind(_blockcreate(_sizeAttr(a),_blocktype(t[1])),0,1,1),a), 'vattr_vi':putattrib(vbind(_blockcreate(_sizeAttr(a),_blocktype(t[1])),0,1,1),a), 'vattr_mi':putattrib(vbind(_blockcreate(_sizeAttr(a),_blocktype(t[1])),0,1,1),a), 'vattr_bl':putattrib(vbind(_blockcreate(_sizeAttr(a),_blocktype(t[1])),0,1,1),a), 'vattr_i':putattrib(vbind(_blockcreate(_sizeAttr(a),_blocktype(t[1])),0,1,1),a), 'vattr_si':putattrib(vbind(_blockcreate(_sizeAttr(a),_blocktype(t[1])),0,1,1),a), 'vattr_uc':putattrib(vbind(_blockcreate(_sizeAttr(a),_blocktype(t[1])),0,1,1),a), 'mattr_f':putattrib(mbind(_blockcreate(_sizeAttr(a),_blocktype(t[1])),0,1,1,1,1),a), 'mattr_d':putattrib(mbind(_blockcreate(_sizeAttr(a),_blocktype(t[1])),0,1,1,1,1),a), 'cmattr_f':putattrib(mbind(_blockcreate(_sizeAttr(a),_blocktype(t[1])),0,1,1,1,1),a), 'cmattr_d':putattrib(mbind(_blockcreate(_sizeAttr(a),_blocktype(t[1])),0,1,1,1,1),a), 'mattr_bl':putattrib(mbind(_blockcreate(_sizeAttr(a),_blocktype(t[1])),0,1,1,1,1),a), 'mattr_i':putattrib(mbind(_blockcreate(_sizeAttr(a),_blocktype(t[1])),0,1,1,1,1),a), 'mattr_si':putattrib(mbind(_blockcreate(_sizeAttr(a),_blocktype(t[1])),0,1,1,1,1),a), 'mattr_uc':putattrib(mbind(_blockcreate(_sizeAttr(a),_blocktype(t[1])),0,1,1,1,1),a)} assert (t[0] and t[1] in f),'type <:%s:> not supported for viewCreate.'%t[1] return f[t[1]] def associatedView(v,attr): f={ 'block_fvattr_f':'putattrib(vbind(blk,0,1,1),attr)', 'block_dvattr_d':'putattrib(vbind(blk,0,1,1),attr)', 'cblock_fcvattr_f':'putattrib(vbind(blk,0,1,1),attr)', 'cblock_dcvattr_d':'putattrib(vbind(blk,0,1,1),attr)', 'block_vivattr_vi':'putattrib(vbind(blk,0,1,1),attr)', 'block_mivattr_mi':'putattrib(vbind(blk,0,1,1),attr)', 'block_blvattr_bl':'putattrib(vbind(blk,0,1,1),attr)', 'block_ivattr_i':'putattrib(vbind(blk,0,1,1),attr)', 'block_sivattr_si':'putattrib(vbind(blk,0,1,1),attr)', 'block_ucvattr_uc':'putattrib(vbind(blk,0,1,1),attr)', 'block_fmattr_f':'putattrib(mbind(blk,0,1,1,1,1),attr)', 'block_dmattr_d':'putattrib(mbind(blk,0,1,1,1,1),attr)', 'cblock_fcmattr_f':'putattrib(mbind(blk,0,1,1,1,1),attr)', 'cblock_dcmattr_d':'putattrib(mbind(blk,0,1,1,1,1),attr)', 'block_blmattr_bl':'putattrib(mbind(blk,0,1,1,1,1),attr)', 'block_imattr_i':'putattrib(mbind(blk,0,1,1,1,1),attr)', 'block_simattr_si':'putattrib(mbind(blk,0,1,1,1,1),attr)', 'block_ucmattr_uc':'putattrib(mbind(blk,0,1,1,1,1),attr)'} t2=getType(attr) t=str() if(getType(v)[0] and t2[0]): vattr=getattrib(v) blk=vattr.block t1=getType(blk) t=t1[1]+t2[1] assert t in f,'Not a supported type for associatedView' return eval(f[t]) def attr(t,l): """ This function creates and returns an initialized attribute object. Note the block attribute is not filled out. The Argument "l" is a list or tuple of (offset, stride, length) for a vector or (offset, col_stride, col_length, row_stride, row_length) for a matrix """ f={'vview_f':'vsip_vattr_f()', 'vview_vi':'vsip_vattr_vi()', 'vview_d': 'vsip_vattr_d()', 'cvview_f':'vsip_cvattr_f()', 'cvview_d':'vsip_cvattr_d()', 'vview_bl':'vsip_vattr_bl()', 'vview_i': 'vsip_vattr_i()', 'vview_mi':'vsip_vattr_mi()', 'vview_si':'vsip_vattr_si()', 'vview_uc':'vsip_vattr_si()', 'mview_d': 'vsip_mattr_d()', 'mview_f': 'vsip_mattr_f()', 'cmview_d':'vsip_cmattr_d()', 'cmview_f':'vsip_cmattr_f()', 'mview_i': 'vsip_mattr_i()', 'mview_si':'vsip_mattr_si()', 'mview_uc':'vsip_mattr_uc()', 'mview_bl': 'vsip_mattr_bl'} def _vattr(a,l): a.offset=l[0] a.stride=l[1] a.length=l[2] def _mattr(a,l): a.offset=l[0] a.col_stride=l[1] a.col_length=l[2] a.row_stride=l[3] a.col_stride=l[4] assert t in f,'Not a supported type for attr.' a = eval(f[t]) if len(l) == 3: _vattr(a,l) return a elif len(l) == 5: _mattr(a,l) return a else: assert False,'Incorrect list argument' def size(a): f={'vview_d':'_vsize(getattrib(a))', 'vview_f': '_vsize(getattrib(a))', 'cvview_d':'_vsize(getattrib(a))', 'cvview_f':'_vsize(getattrib(a))', 'vview_vi':'_vsize(getattrib(a))', 'vview_mi':'_vsize(getattrib(a))', 'vview_bl':'_vsize(getattrib(a))', 'vview_i':'_vsize(getattrib(a))', 'vview_si':'_vsize(getattrib(a))', 'vview_uc':'_vsize(getattrib(a))', 'mview_d':'_msize(getattrib(a))', 'mview_f':'_msize(getattrib(a))', 'cmview_d':'_msize(getattrib(a))', 'cmview_f':'_msize(getattrib(a))', 'mview_bl':'_msize(getattrib(a))', 'mview_i':'_msize(getattrib(a))', 'mview_si':'_msize(getattrib(a))', 'mview_uc':'_msize(getattrib(a))'} def _vsize(attr): return (attr.offset,attr.stride,attr.length) def _msize(attr): return (attr.offset,attr.col_stride,attr.col_length,attr.row_stride, attr.row_length) t=getType(a) assert t[1] in f, 'Type <:%s:> not supported for size.'%t[1] return eval(f[t[1]]) # view => vcreate,mcreate, .. # block => blockcreate # bind => vbind, mbind, ... def block(t,l): """ Function "block(t,l) creates a block of type t and length l """ f={ 'block_f':vsip_blockcreate_f, 'block_d':vsip_blockcreate_d, 'cblock_f':vsip_cblockcreate_f, 'cblock_d':vsip_cblockcreate_d, 'block_i':vsip_blockcreate_i, 'block_si':vsip_blockcreate_si, 'block_uc':vsip_blockcreate_uc, 'block_vi':vsip_blockcreate_vi, 'block_mi':vsip_blockcreate_mi, 'block_bl':vsip_blockcreate_bl} assert t in f,'Not a supported block type' return f[t](l,VSIP_MEM_NONE) def bind(blk,l_in): """ The function "bind(blk,l)" binds a view to a block. The attributes of the view are determined by a tuple "l". If the tuple is of length 3 then a vector is assumed. If the tupe is of length 5 then a matrix is assumed. vector tuple is (offset, stride, length) matrix tuple is (offset, col_stride, col_length, row_stride, row_length) Precision is determined by the block type. """ f={ 'block_fvector':'vsip_vbind_f(blk,l[0],l[1],l[2])', 'block_dvector':'vsip_vbind_d(blk,l[0],l[1],l[2])', 'cblock_fvector':'vsip_cvbind_f(blk,l[0],l[1],l[2])', 'cblock_dvector':'vsip_cvbind_d(blk,l[0],l[1],l[2])', 'block_ivector':'vsip_vbind_i(blk,l[0],l[1],l[2])', 'block_sivector':'vsip_vbind_si(blk,l[0],l[1],l[2])', 'block_ucvector':'vsip_vbind_uc(blk,l[0],l[1],l[2])', 'block_vivector':'vsip_vbind_vi(blk,l[0],l[1],l[2])', 'block_mivector':'vsip_vbind_mi(blk,l[0],l[1],l[2])', 'block_blvector':'vsip_vbind_bl(blk,l[0],l[1],l[2])', 'block_fmatrix':'vsip_mbind_f(blk,l[0],l[1],l[2],l[3],l[4])', 'block_dmatrix':'vsip_mbind_d(blk,l[0],l[1],l[2],l[3],l[4])', 'cblock_fmatrix':'vsip_cmbind_f(blk,l[0],l[1],l[2],l[3],l[4])', 'cblock_dmatrix':'vsip_cmbind_d(blk,l[0],l[1],l[2],l[3],l[4])', 'block_imatrix':'vsip_mbind_i(blk,l[0],l[1],l[2],l[3],l[4])', 'block_simatrix':'vsip_mbind_si(blk,l[0],l[1],l[2],l[3],l[4])', 'block_ucmatrix':'vsip_mbind_uc(blk,l[0],l[1],l[2],l[3],l[4])', 'block_blmatrix':'vsip_mbind_bl(blk,l[0],l[1],l[2],l[3],l[4])'} t=getType(blk)[1] t_l=type(l_in) if t_l == tuple: l=[item for item in l_in] elif t_l == list: l=l_in else: assert False,"Argument two in bind must be a tuple or list of attribues \ for a vector or matrix" if len(l) == 3: t+='vector' elif len(l) == 5: t+='matrix' if t in f: return eval(f[t]) else: assert False,'Bind has no type ' + t def view(t,l_in): """ This function creates a vector or matrix view including vector views associated with a window function (hanning,blackman,kaiser, cheby). Note: To make this as a single call for all view creates the first parameter is the type and the second parameter is a tuple with three entries as indicated. The value of the entries are the same as for the vsip function call. the second and/or third entries may be ignored if the type does not need them. See the VSIPL specification for additional clues. The calling convention for a float vector is: view('vview_f',(length)) Note the first argument is a view type with associated precision (_f, _d, _vi, _si, _i, _uc, _mi) for a float matrix the call is: view('mview_f',(col_length, row_length,VSIP_ROW)) for row major. Use VSIP_COL for column major. for a window function use: (note _d is also supported): view('blackman_f',(length)) view('hanning_f',(length)) view('kaiser_f',(length,float parameter)) view('cheby_f',(length,float parameter)) """ f={'blackman_d':'vsip_vcreate_blackman_d(l[0], VSIP_MEM_NONE)', 'hanning_d':'vsip_vcreate_hanning_d(l[0], VSIP_MEM_NONE)', 'kaiser_d':'vsip_vcreate_kaiser_d(l[0], l[1], VSIP_MEM_NONE)', 'cheby_d':'vsip_vcreate_cheby_d(l[0], l[1], VSIP_MEM_NONE)', 'blackman_f':'vsip_vcreate_blackman_f(l[0], VSIP_MEM_NONE)', 'hanning_f':'vsip_vcreate_hanning_f(l[0], VSIP_MEM_NONE)', 'kaiser_f':'vsip_vcreate_kaiser_f(l[0],l[1], VSIP_MEM_NONE)', 'cheby_f':'vsip_vcreate_cheby_f(l[0], l[1], VSIP_MEM_NONE)', 'vview_f':'vsip_vcreate_f( l[0], VSIP_MEM_NONE)', 'vview_vi':'vsip_vcreate_vi( l[0], VSIP_MEM_NONE)', 'vview_d':'vsip_vcreate_d( l[0], VSIP_MEM_NONE)', 'cvview_f':'vsip_cvcreate_f( l[0], VSIP_MEM_NONE)', 'cvview_d':'vsip_cvcreate_d( l[0], VSIP_MEM_NONE)', 'vview_bl':'vsip_vcreate_bl(l[0], VSIP_MEM_NONE)', 'vview_i':'vsip_vcreate_i(l[0], VSIP_MEM_NONE)', 'vview_mi':'vsip_vcreate_mi(l[0], VSIP_MEM_NONE)', 'vview_si':'vsip_vcreate_si(l[0], VSIP_MEM_NONE)', 'vview_uc':'vsip_vcreate_uc(l[0], VSIP_MEM_NONE)', 'mview_d':'vsip_mcreate_d(l[0],l[1],l[2],VSIP_MEM_NONE)', 'mview_f':'vsip_mcreate_f(l[0],l[1],l[2],VSIP_MEM_NONE)', 'cmview_d':'vsip_cmcreate_d(l[0],l[1],l[2],VSIP_MEM_NONE)', 'cmview_f':'vsip_cmcreate_f(l[0],l[1],l[2],VSIP_MEM_NONE)', 'mview_i':'vsip_mcreate_i(l[0],l[1],l[2],VSIP_MEM_NONE)', 'mview_si':'vsip_mcreate_si(l[0],l[1],l[2],VSIP_MEM_NONE)', 'mview_uc':'vsip_mcreate_uc(l[0],l[1],l[2],VSIP_MEM_NONE)', 'mview_bl':'vsip_mcreate_bl(l[0],l[1],l[2],VSIP_MEM_NONE)'} l=[] tl = type(l_in) if tl == int: l.append(l_in) elif tl == tuple: for item in l_in: l.append(item) elif t1 == list: l=l_in else: assert False,'Attribute input argument is not list, tuple, or int length.' assert t in f,'Type argument not a supported type for view' return eval(f[t]) # Other Support Functions def getblock(v): return getattrib(v).block def mbind(block,o,cs,cl,rs,rl): t=getType(block); f={ 'block_f':vsip_mbind_f, 'block_d':vsip_mbind_d, 'cblock_f':vsip_cmbind_f, 'cblock_d':vsip_cmbind_d, 'block_i':vsip_mbind_i, 'block_si':vsip_mbind_si, 'block_uc':vsip_mbind_uc, 'block_bl':vsip_mbind_bl} if t[0] and t[1] in f: return f[t[1]](block,o,cs,cl,rs,rl) else: return False def vbind(block,o,s,l): t=getType(block); f={ 'block_f':vsip_vbind_f, 'block_d':vsip_vbind_d, 'cblock_f':vsip_cvbind_f, 'cblock_d':vsip_cvbind_d, 'block_i':vsip_vbind_i, 'block_si':vsip_vbind_si, 'block_uc':vsip_vbind_uc, 'block_vi':vsip_vbind_vi, 'block_mi':vsip_vbind_mi, 'block_bl':vsip_vbind_bl} if t[0] and t[1] in f: return f[t[1]](block,o,s,l) else: return False def getattrib(a): """ Return the attribute of a VSIPL view. NOTE: Unlike the C vsipl function this function will create the attribute (you don't pass one in). This function is shorthand for (for instance in the float case): attr = vsip_vattr_f() and then using the C VSIPL interface do vsip_vgetattrib_f(a,attr) which will fill in the attr object. Note that the example is typed but this function gets the type by checking the input view. """ t=getType(a) f={ 'vview_f': (vsip_vgetattrib_f,vsip_vattr_f), 'vview_d': (vsip_vgetattrib_d,vsip_vattr_d), 'mview_f': (vsip_mgetattrib_f,vsip_mattr_f), 'mview_d': (vsip_mgetattrib_d,vsip_mattr_d), 'cvview_f':(vsip_cvgetattrib_f,vsip_cvattr_f), 'cvview_d':(vsip_cvgetattrib_d,vsip_cvattr_d), 'cmview_f':(vsip_cmgetattrib_f,vsip_cmattr_f), 'cmview_d':(vsip_cmgetattrib_d,vsip_cmattr_d), 'vview_i': (vsip_vgetattrib_i,vsip_vattr_i), 'mview_i': (vsip_mgetattrib_i,vsip_mattr_i), 'vview_si':(vsip_vgetattrib_si,vsip_vattr_si), 'mview_si':(vsip_mgetattrib_si,vsip_mattr_si), 'vview_uc':(vsip_vgetattrib_uc,vsip_vattr_uc), 'mview_uc':(vsip_mgetattrib_uc,vsip_mattr_uc), 'vview_vi':(vsip_vgetattrib_vi,vsip_vattr_vi), 'vview_bl':(vsip_vgetattrib_bl,vsip_vattr_bl), 'mview_bl':(vsip_mgetattrib_bl,vsip_mattr_bl), 'vview_mi':(vsip_vgetattrib_mi,vsip_vattr_mi), 'cfir_d':(vsip_cfir_getattr_d,vsip_cfir_attr), 'cfir_f':(vsip_cfir_getattr_f,vsip_cfir_attr), 'fir_d':(vsip_fir_getattr_f,vsip_fir_attr), 'fir_f':(vsip_fir_getattr_f,vsip_fir_attr), 'lu_f':(vsip_lud_getattr_f,vsip_lu_attr_f), 'clu_f':(vsip_clud_getattr_f,vsip_clu_attr_f), 'lu_d':(vsip_lud_getattr_d,vsip_lu_attr_d), 'clu_d':(vsip_clud_getattr_d,vsip_clu_attr_d), 'chol_f':(vsip_chold_getattr_f,vsip_chol_attr_f), 'cchol_f':(vsip_cchold_getattr_f,vsip_cchol_attr_f), 'chol_d':(vsip_chold_getattr_d,vsip_chol_attr_d), 'cchold_d':(vsip_cchold_getattr_d,vsip_cchol_attr_d), 'qr_f':( vsip_qrd_getattr_f,vsip_qr_attr_f), 'cqr_f':(vsip_cqrd_getattr_f,vsip_cqr_attr_f), 'qr_d':( vsip_qrd_getattr_d,vsip_qr_attr_d), 'cqr_d':(vsip_cqrd_getattr_d,vsip_cqr_attr_d)} assert (t[0] and t[1] in f),'Type <:%s:> not supported for getattrib.'%t[1] attr = f[t[1]][1]() f[t[1]][0](a,attr) return attr def putattrib(a,attr): """ Change the attributes of a vector view object """ t1=getType(a) t2=getType(attr) t=t1[1]+t2[1] f={ 'vview_fvattr_f':vsip_vputattrib_f, 'vview_dvattr_d':vsip_vputattrib_d, 'cvview_fcvattr_f':vsip_cvputattrib_f, 'cvview_dcvattr_d':vsip_cvputattrib_d, 'mview_fmattr_f':vsip_mputattrib_f, 'mview_dmattr_d':vsip_mputattrib_d, 'cmview_fcmattr_f':vsip_cmputattrib_f, 'cmview_dcmattr_d':vsip_cmputattrib_d, 'vview_vivattr_vi':vsip_vputattrib_vi, 'vview_mivattr_mi':vsip_vputattrib_mi, 'vview_blvattr_bl':vsip_vputattrib_bl, 'vview_ivattr_i':vsip_vputattrib_i, 'vview_sivattr_si':vsip_vputattrib_si, 'vview_ucvattr_uc':vsip_vputattrib_uc, 'mview_blmattr_bl':vsip_mputattrib_bl, 'mview_imattr_i':vsip_mputattrib_i, 'mview_simattr_si':vsip_mputattrib_si, 'mview_ucmattr_uc':vsip_mputattrib_uc} assert t1[0] and t2[0],'Argument not supported for putattrib.' assert t in f,'Type <:%s:> not supported for putattrib.'%s return f[t](a,attr) def getoffset(a): """ Get the offset of a view object """ t=getType(a) f={'vview_f':vsip_vgetoffset_f, 'mview_f':vsip_mgetoffset_f, 'vview_d':vsip_vgetoffset_d, 'mview_d':vsip_mgetoffset_d, 'vview_i':vsip_vgetoffset_i, 'mview_i':vsip_mgetoffset_i, 'vview_si':vsip_vgetoffset_si, 'mview_si':vsip_mgetoffset_si, 'vview_uc':vsip_vgetoffset_uc, 'mview_uc':vsip_mgetoffset_uc, 'vview_vi':vsip_vgetoffset_vi, 'cvview_f':vsip_cvgetoffset_f, 'cmview_f':vsip_cmgetoffset_f, 'cvview_d':vsip_cvgetoffset_d, 'cmview_d':vsip_cmgetoffset_d, 'vview_mi':vsip_vgetoffset_mi, 'mview_bl':vsip_mgetoffset_bl, 'vview_bl':vsip_vgetoffset_bl} assert (t[0] and t[1] in f),'Not a supported type for getoffset' return f[t[1]](a) def putoffset(a,s): """ Change the offset of a view object """ t=getType(a) f={'vview_f':vsip_vputoffset_f, 'mview_f':vsip_mputoffset_f, 'vview_d':vsip_vputoffset_d, 'mview_d':vsip_mputoffset_d, 'vview_i':vsip_vputoffset_i, 'mview_i':vsip_mputoffset_i, 'vview_si':vsip_vputoffset_si, 'mview_si':vsip_mputoffset_si, 'vview_uc':vsip_vputoffset_uc, 'mview_uc':vsip_mputoffset_uc, 'vview_vi':vsip_vputoffset_vi, 'cvview_f':vsip_cvputoffset_f, 'cmview_f':vsip_cmputoffset_f, 'cvview_d':vsip_cvputoffset_d, 'cmview_d':vsip_cmputoffset_d, 'vview_mi':vsip_vputoffset_mi, 'mview_bl':vsip_mputoffset_bl, 'vview_bl':vsip_vputoffset_bl } assert (t[0] and t[1] in f),'Not a supported type for putoffset' return f[t[1]](a,s) def getstride(a): """ Get the stride of a vector view object """ t=getType(a) f={'vview_f':vsip_vgetstride_f, 'vview_d':vsip_vgetstride_d, 'vview_i':vsip_vgetstride_i, 'vview_si':vsip_vgetstride_si, 'vview_uc':vsip_vgetstride_uc, 'vview_bl':vsip_vgetstride_bl, 'vview_vi':vsip_vgetstride_vi, 'cvview_f':vsip_cvgetstride_f, 'cvview_d':vsip_cvgetstride_d, 'vview_mi':vsip_vgetstride_mi } assert (t[0] and t[1] in f),'Argument not recognized for getstride.' return f[t[1]](a) def putstride(a,s): """ Change the stride of a vector view object """ t=getType(a) f={ 'vview_f':vsip_vputstride_f, 'vview_d':vsip_vputstride_d, 'vview_i':vsip_vputstride_i, 'vview_si':vsip_vputstride_si, 'vview_uc':vsip_vputstride_uc, 'vview_bl':vsip_vputstride_bl, 'vview_vi':vsip_vputstride_vi, 'cvview_f':vsip_cvputstride_f, 'cvview_d':vsip_cvputstride_d, 'vview_mi':vsip_vputstride_mi } assert t[0],'Type not supported for putstride.' return f[t[1]](a,s) def getlength(a): """ Get the length of a vector view object """ t=getType(a) f={'vview_f':vsip_vgetlength_f, 'vview_d':vsip_vgetlength_d, 'vview_i':vsip_vgetlength_i, 'vview_si':vsip_vgetlength_si, 'vview_uc':vsip_vgetlength_uc, 'vview_bl':vsip_vgetlength_bl, 'vview_vi':vsip_vgetlength_vi, 'cvview_f':vsip_cvgetlength_f, 'cvview_d':vsip_cvgetlength_d, 'vview_mi':vsip_vgetlength_mi } assert t[0],'Not a supported type for getlength.' return f[t[1]](a) def putlength(a,l): """ Change the length of a vector view object """ t=getType(a) f={'vview_f':vsip_vputlength_f, 'vview_d':vsip_vputlength_d, 'vview_i':vsip_vputlength_i, 'vview_si':vsip_vputlength_si, 'vview_uc':vsip_vputlength_uc, 'vview_bl':vsip_vputlength_bl, 'vview_vi':vsip_vputlength_vi, 'cvview_f':vsip_cvputlength_f, 'cvview_d':vsip_cvputlength_d, 'vview_mi':vsip_vputlength_mi } assert t[0],'Not a compatible type for putlength.' return f[t[1]](a,l) def getrowstride(a): """ Get the stride of a matrix view object """ t=getType(a) f={'mview_f':vsip_mgetrowstride_f, 'mview_d':vsip_mgetrowstride_d, 'mview_i':vsip_mgetrowstride_i, 'mview_si':vsip_mgetrowstride_si, 'mview_uc':vsip_mgetrowstride_uc, 'mview_bl':vsip_mgetrowstride_bl, 'cmview_f':vsip_cmgetrowstride_f, 'cmview_d':vsip_cmgetrowstride_d } assert t[0] and t[1] in f,'Type <:%s:> not a supported type for getrowstride.'%t[1] return f[t[1]](a) def getcolstride(a): """ Get the stride of a matrix view object """ t=getType(a) f={'mview_f':vsip_mgetcolstride_f, 'mview_d':vsip_mgetcolstride_d, 'mview_i':vsip_mgetcolstride_i, 'mview_si':vsip_mgetcolstride_si, 'mview_uc':vsip_mgetcolstride_uc, 'mview_bl':vsip_mgetcolstride_bl, 'cmview_f':vsip_cmgetcolstride_f, 'cmview_d':vsip_cmgetcolstride_d } assert t[0] and t[1] in f,'Type <:%s:> not a supported type for getcolstride.'%t[1] return f[t[1]](a) def getrowlength(a): """ Get the length of a matrix view object """ t=getType(a) f={'mview_f':vsip_mgetrowlength_f, 'mview_d':vsip_mgetrowlength_d, 'mview_i':vsip_mgetrowlength_i, 'mview_si':vsip_mgetrowlength_si, 'mview_uc':vsip_mgetrowlength_uc, 'cmview_f':vsip_cmgetrowlength_f, 'cmview_d':vsip_cmgetrowlength_d, 'mview_bl':vsip_mgetcollength_bl} assert t[0] and t[1] in f,'Type <:%s:> not a supported type for getrowlength'%t[1] return f[t[1]](a) def getcollength(a): """ Get the length of a matrix view object """ t=getType(a) f={'mview_f':vsip_mgetcollength_f, 'mview_d':vsip_mgetcollength_d, 'mview_i':vsip_mgetcollength_i, 'mview_si':vsip_mgetcollength_si, 'mview_uc':vsip_mgetcollength_uc, 'cmview_f':vsip_cmgetcollength_f, 'cmview_d':vsip_cmgetcollength_d, 'mview_bl':vsip_mgetcollength_bl } assert t[0] and t[1] in f,'Type <:%s:> not a supported type for for getcollength'%t[1] return f[t[1]](a) def putrowstride(a,s): """ Put the stride of a matrix view object """ t=getType(a) f={'mview_f':vsip_mputrowstride_f, 'mview_d':vsip_mputrowstride_d, 'mview_i':vsip_mputrowstride_i, 'mview_si':vsip_mputrowstride_si, 'mview_uc':vsip_mputrowstride_uc, 'mview_bl':vsip_mputrowstride_bl, 'cmview_f':vsip_cmputrowstride_f, 'cmview_d':vsip_cmputrowstride_d } assert t[0] and t[1] in f,'Type <:%s:> not a supported type for for putrowstride'%t[1] return f[t[1]](a,s) def putcolstride(a,s): """ Put the stride of a matrix view object """ t=getType(a) f={'mview_f':vsip_mputcolstride_f, 'mview_d':vsip_mputcolstride_d, 'mview_i':vsip_mputcolstride_i, 'mview_si':vsip_mputcolstride_si, 'mview_uc':vsip_mputcolstride_uc, 'mview_bl':vsip_mputcolstride_bl, 'cmview_f':vsip_cmputcolstride_f, 'cmview_d':vsip_cmputcolstride_d } assert t[0] and t[1] in f,'Type <:%s:> not a supported type for for putcolstride'%t[1] return f[t[1]](a,s) def putrowlength(a,l): """ Put the length of a matrix view object """ t=getType(a) f={'mview_f':vsip_mputrowlength_f, 'mview_d':vsip_mputrowlength_d, 'mview_i':vsip_mputrowlength_i, 'mview_si':vsip_mputrowlength_si, 'mview_uc':vsip_mputrowlength_uc, 'mview_bl':vsip_mputrowlength_bl, 'cmview_f':vsip_cmputrowlength_f, 'cmview_d':vsip_cmputrowlength_d } assert t[0] and t[1] in f,'Type <:%s:> not a supported type for for putrowlength'%t[1] return f[t[1]](a,l) def putcollength(a,l): """ Put the length of a matrix view object """ t=getType(a) f={'mview_f':vsip_mputcollength_f, 'mview_d':vsip_mputcollength_d, 'mview_i':vsip_mputcollength_i, 'mview_si':vsip_mputcollength_si, 'mview_uc':vsip_mputcollength_uc, 'mview_bl':vsip_mputcollength_bl, 'cmview_f':vsip_cmputcollength_f, 'cmview_d':vsip_cmputcollength_d } assert t[0] and t[1] in f,'Type <:%s:> not a supported type for for putcollength'%t[1] return f[t[1]](a,l) def cloneview(a): f={'vview_f':vsip_vcloneview_f, 'vview_d':vsip_vcloneview_d, 'cvview_f':vsip_cvcloneview_f, 'cvview_d':vsip_cvcloneview_d, 'cmview_d':vsip_cmcloneview_d, 'cmview_f':vsip_cmcloneview_f, 'mview_bl':vsip_mcloneview_bl, 'mview_d':vsip_mcloneview_d, 'mview_f':vsip_mcloneview_f, 'mview_i':vsip_mcloneview_i, 'mview_si':vsip_mcloneview_si, 'mview_uc':vsip_mcloneview_uc, 'vview_bl':vsip_vcloneview_bl, 'vview_i':vsip_vcloneview_i, 'vview_mi':vsip_vcloneview_mi, 'vview_si':vsip_vcloneview_si, 'vview_uc':vsip_vcloneview_uc, 'vview_vi':vsip_vcloneview_vi} t=getType(a) assert t[1] in f,'Type <:%s:> not supported for cloneview.'%t[1] return f[t[1]](a) def realview(a): t=getType(a) f=f={'cmview_d': vsip_mrealview_d, 'cmview_f': vsip_mrealview_f, 'cvview_d': vsip_vrealview_d, 'cvview_f': vsip_vrealview_f} assert t[1] in f,'Type <:%s:> not a valid type for real view.'%t[1] return f[t[1]](a) def imagview(a): t=getType(a) f = {'cmview_d': vsip_mimagview_d, 'cmview_f': vsip_mimagview_f, 'cvview_d': vsip_vimagview_d, 'cvview_f': vsip_vimagview_f} assert t[1] in f,'Type <:%s:> not a valid type for imag view.'%t[1] return f[t[1]](a) def diagview(a,i): t=getType(a) f = {'mview_i': vsip_mdiagview_i, 'mview_si': vsip_mdiagview_si, 'mview_uc': vsip_mdiagview_uc, 'cmview_d': vsip_cmdiagview_d, 'cmview_f': vsip_cmdiagview_f, 'mview_d': vsip_mdiagview_d, 'mview_bl': vsip_mdiagview_bl, 'mview_f': vsip_mdiagview_f} assert t[1] in f,'Type <:%s:> not a valid type for diagonal view.'%t[1] return f[t[1]](a,i) def rowview(A,i): f={'mview_i': vsip_mrowview_i, 'mview_si': vsip_mrowview_si, 'mview_uc': vsip_mrowview_uc, 'cmview_d': vsip_cmrowview_d, 'cmview_f': vsip_cmrowview_f, 'mview_d': vsip_mrowview_d, 'mview_f': vsip_mrowview_f, 'mview_bl': vsip_mrowview_bl} t=getType(A)[1] assert t in f,'Type <:%s:> not a valid type for row view.'%t return f[t](A,i) def colview(A,i): f={'mview_i': vsip_mcolview_i, 'mview_si': vsip_mcolview_si, 'mview_uc': vsip_mcolview_uc, 'cmview_d': vsip_cmcolview_d, 'cmview_f': vsip_cmcolview_f, 'mview_d': vsip_mcolview_d, 'mview_f': vsip_mcolview_f, 'mview_bl': vsip_mcolview_bl} t=getType(A)[1] assert t in f,'Type <:%s:> not a valid type for col view.'%t return f[t](A,i) def subview(v,i): """ Usage a = subview(A,i) where a is a new vsip view created by subview. The new view a is on the same block as A. i is a tuple corresponding to the index of the starting point in A and length of the corresponding dimensions. See VSIPL document for additional information. Ex: for a vector A of length 10 with elements from 0 to 9 then a=subview(A,(3,2)) returns a vector of length 2 with elements 2,3 Ex: for a matrix A of size 10,10 with elements 0 to 9 in each row a=subview(A,3,3,2,3) returns a matrix of size 2,3 with elements 2,3 in each row """ f={'vview_vi':'vsip_vsubview_vi(v, i[0], i[1])', 'vview_mi':'vsip_vsubview_mi(v, i[0], i[1])', 'vview_bl':'vsip_vsubview_bl(v, i[0], i[1])', 'vview_d':'vsip_vsubview_d(v, i[0], i[1])', 'vview_f':'vsip_vsubview_f(v, i[0], i[1])', 'vview_i':'vsip_vsubview_i(v, i[0], i[1])', 'vview_si':'vsip_vsubview_si(v, i[0], i[1])', 'vview_uc':'vsip_vsubview_uc(v, i[0], i[1])', 'cvview_d':'vsip_cvsubview_d(v, i[0], i[1])', 'cvview_f':'vsip_cvsubview_f(v, i[0], i[1])', 'mview_d':'vsip_msubview_d(v, i[0], i[1], i[2], i[3])', 'mview_f':'vsip_msubview_f(v, i[0], i[1], i[2], i[3])', 'cmview_d':'vsip_cmsubview_d(v, i[0], i[1], i[2], i[3])', 'cmview_f':'vsip_cmsubview_f(v, i[0], i[1], i[2], i[3])', 'mview_bl':'vsip_msubview_bl(v, i[0], i[1], i[2], i[3])', 'mview_i':'vsip_msubview_i(v, i[0], i[1], i[2], i[3])', 'mview_si':'vsip_msubview_si(v, i[0], i[1], i[2], i[3])', 'mview_uc':'vsip_msubview_uc(v, i[0], i[1], i[2], i[3])'} t=getType(v)[1] assert t[1] in f,'Type <:%s:> not a valid type for sub view.'%t[1] return eval(f[t]) def transview(A): """ Note this function creates a transpose view that should be destroyed when it is no longer needed """ f={'mview_bl': vsip_mtransview_bl, 'mview_i': vsip_mtransview_i, 'mview_si': vsip_mtransview_si, 'mview_uc': vsip_mtransview_uc, 'cmview_d': vsip_cmtransview_d, 'cmview_f': vsip_cmtransview_f, 'mview_d': vsip_mtransview_d, 'mview_f': vsip_mtransview_f} t=getType(A)[1] assert t in f,'Type <:%s:> not a valid type for trans view.'%t return f[t](A) def get(a,i): """ get(aView,aIndex) will return a value from a vsip view. Argument aIndex corresponds to a tuple, a single integer, or a vsip_scalar_mi. The argument must make sense for the input view. """ f={'cvview_dscalar':'vsip_cvget_d(a,int(i))', 'cvview_fscalar':'vsip_cvget_f(a,int(i))', 'vview_dscalar':'vsip_vget_d(a,int(i))', 'vview_fscalar':'vsip_vget_f(a,int(i))', 'vview_iscalar':'vsip_vget_i(a,int(i))', 'vview_viscalar':'vsip_vget_vi(a,int(i))', 'vview_siscalar':'vsip_vget_si(a,int(i))', 'vview_ucscalar':'vsip_vget_uc(a,int(i))', 'vview_blscalar':'_bl(vsip_vget_bl(a,int(i)))', 'vview_miscalar':'vsip_vget_mi(a,int(i))', 'cmview_dtuple':'vsip_cmget_d(a,i[0],i[1])', 'cmview_ftuple':'vsip_cmget_f(a,i[0],i[1])', 'mview_dtuple':'vsip_mget_d(a,i[0],i[1])', 'mview_ftuple':'vsip_mget_f(a,i[0],i[1])', 'mview_ituple':'vsip_mget_i(a,i[0],i[1])', 'mview_situple':'vsip_mget_si(a,i[0],i[1])', 'mview_uctuple':'vsip_mget_uc(a,i[0],i[1])', 'mview_blstuple':'_bl(vsip_mget_bl(a,i[0],i[1]))', 'cmview_dscalar_mi':'vsip_cmget_d(a,i.r,i.c)', 'cmview_fscalar_mi':'vsip_cmget_f(a,i.r,i.c)', 'mview_dscalar_mi':'vsip_mget_d(a,i.r,i.c)', 'mview_fscalar_mi':'vsip_mget_f(a,i.r,i.c)', 'mview_iscalar_mi':'vsip_mget_i(a,i.r,i.c)', 'mview_siscalar_mi':'vsip_mget_si(a,i.r,i.c)', 'mview_ucscalar_mi':'vsip_mget_uc(a,i.r,i.c)', 'mview_blscalar_mi':'vsip_mget_bl(a,i.r,i.c)'} t=getType(a)[1] if 'vview' in t: if type(i) is int or type(i) is float and i >=0: t += 'scalar' else: assert False,'In get function; index must be an integer >=0 for vector view' elif 'mview' in t: if type(i) == tuple and len(i) == 2: t += 'tuple' elif type(i) == list and len(i) == 2: #Index i is indexed the same tuple or list t += 'tuple' elif 'scalar_mi' in getType(i)[1]: t += 'scalar_mi' else: assert False,'In get function; index not recognized for matrix.' else: assert False,'Argument not recognized by get as vector or matrix?' assert t in f,'Type <:%s:> not a supported type.'%t return eval(f[t]) def put(a,i,scl): """ put(aView,aIndex,aScalar) will put aScalar in aView at position aIndex. Argument aIndex corresponds to a tuple or a single integer, or a vsip_scalar_mi. aIndex must make sense for the input view. """ f={'cvview_dscalar':'vsip_cvput_d(a,i,x)', 'cvview_fscalar':'vsip_cvput_f(a,i,x)', 'vview_dscalar':'vsip_vput_d(a,i,x)', 'vview_fscalar':'vsip_vput_f(a,i,x)', 'vview_iscalar':'vsip_vput_i(a,i,x)', 'vview_viscalar':'vsip_vput_vi(a,i,x)', 'vview_siscalar':'vsip_vput_si(a,i,x)', 'vview_ucscalar':'vsip_vput_uc(a,i,x)', 'vview_blscalar':'vsip_vput_bl(a,i,x)', 'vview_miscalar':'vsip_vput_mi(a,i,x)', 'cmview_dscalar_mi':'vsip_cmput_d(a,r,c,x)', 'cmview_fscalar_mi':'vsip_cmput_f(a,r,c,x)', 'mview_dscalar_mi':'vsip_mput_d(a,r,c,x)', 'mview_fscalar_mi':'vsip_mput_f(a,r,c,x)', 'mview_iscalar_mi':'vsip_mput_i(a,r,c,x)', 'mview_siscalar_mi':'vsip_mput_si(a,r,c,x)', 'mview_ucscalar_mi':'vsip_mput_uc(a,r,c,x)', 'mview_blscalar_mi':'vsip_mput_bl(a,r,c,x)'} t=getType(a)[1] # figure out the scalar if 'cvview' in t or 'cmview' in t: if type(scl) is complex: if '_d' in t: x = vsip_cmplx_d(scl.real,scl.imag) else: x = vsip_cmplx_f(scl.real,scl.imag) elif type(scl) is int or type(scl) is float: if '_d' in t: x = vsip_cmplx_d(scl,0.0) else: x = vsip_cmplx_f(scl,0.0) elif 'cscalar' in getType(scl)[1]: x = scl else: assert False,'In vsiutils put; Input scalar type is not recognized for complex view' elif '_mi' in t: if 'scalar_mi' in getType(scl)[1]: x=scl else: assert False,'Input to vview_mi type must be scalar_mi' return elif '_i' in t or '_si' in t: if type(scl) is int: x = scl elif type(scl) is float: x = int(scl) else: assert False,'Input to integer view must be float or integer' elif '_vi' in t: if type(scl) is float or type(scl) is int and scl >= 0: x = int(scl) else: assert False,'Type for _vi must be unsigned int' elif '_uc' in t: if type(scl) is float or type(scl) is int and scl >= 0: x = int(scl) else: assert False,'Type for _uc must be unsigned int' elif '_d' or '_f' in t: if type(scl) is float or type(scl) is int: x = float(scl) else: assert False,'Type must be float for _d or _f precision views' else: assert False,'Precision type of scalar not recognized for function put' #figure out the type if 'vview' in t: if type(i) is int: t+='scalar' else: assert False,'Index for function <:put:> must be an int for a vector' elif 'mview' in t: if type(i) is tuple or type(i) is list and len(i) is 2: r=i[0]; c = i[1] t += 'scalar_mi' elif 'scalar_mi' in getType(i)[1]: r=i.r; c = i.c t += 'scalar_mi' else: assert False,'Index for function put not recognized for a matrix.' else: assert False,'Input argument not a vsip vector or matrix?' #evaluate the function for type assert t in f,'Type <:%s:> not supported for put.'%t eval(f[t]) # Block and View Destroy functions def viewDestroy(a): t=getType(a) f = {'mview_bl':vsip_mdestroy_bl, 'vview_bl':vsip_vdestroy_bl, 'tview_d':vsip_tdestroy_d, 'mview_d':vsip_mdestroy_d, 'vview_d':vsip_vdestroy_d, 'tview_f':vsip_tdestroy_f, 'mview_f':vsip_mdestroy_f, 'vview_f':vsip_vdestroy_f, 'tview_i':vsip_tdestroy_i, 'mview_i':vsip_mdestroy_i, 'vview_i':vsip_vdestroy_i, 'vview_mi':vsip_vdestroy_mi, 'tview_si':vsip_tdestroy_si, 'mview_si':vsip_mdestroy_si, 'vview_si':vsip_vdestroy_si, 'tview_uc':vsip_tdestroy_uc, 'mview_uc':vsip_mdestroy_uc, 'vview_uc':vsip_vdestroy_uc, 'vview_vi':vsip_vdestroy_vi, 'ctview_d':vsip_ctdestroy_d, 'cmview_d':vsip_cmdestroy_d, 'cvview_d':vsip_cvdestroy_d, 'ctview_f':vsip_ctdestroy_f, 'cmview_f':vsip_cmdestroy_f, 'cvview_f':vsip_cvdestroy_f} assert (t[0] and t[1] in f), 'Type <:%s:> not recongnized for viewDestroy.'%t[1] b = f[t[1]](a) return b def blockDestroy(a): t=getType(a) f={ 'block_bl':vsip_blockdestroy_bl, 'block_d':vsip_blockdestroy_d, 'block_f':vsip_blockdestroy_f, 'block_i':vsip_blockdestroy_i, 'block_mi':vsip_blockdestroy_mi, 'block_si':vsip_blockdestroy_si, 'block_uc':vsip_blockdestroy_uc, 'block_vi':vsip_blockdestroy_vi, 'cblock_d':vsip_cblockdestroy_d, 'cblock_f':vsip_cblockdestroy_f} assert (t[0] and t[1] in f), 'Type <:%s:> not recongnized for blockDestroy.'%t[1] f[t[1]](a) def allDestroy(a): t=getType(a) f={ 'cmview_d':vsip_cmalldestroy_d, 'cmview_f':vsip_cmalldestroy_f, 'ctview_d':vsip_ctalldestroy_d, 'ctview_f':vsip_ctalldestroy_f, 'cvview_d':vsip_cvalldestroy_d, 'cvview_f':vsip_cvalldestroy_f, 'mview_bl':vsip_malldestroy_bl, 'mview_d':vsip_malldestroy_d, 'mview_f':vsip_malldestroy_f, 'mview_i':vsip_malldestroy_i, 'mview_si':vsip_malldestroy_si, 'mview_uc':vsip_malldestroy_uc, 'tview_d':vsip_talldestroy_d, 'tview_f':vsip_talldestroy_f, 'tview_i':vsip_talldestroy_i, 'tview_si':vsip_talldestroy_si, 'tview_uc':vsip_talldestroy_uc, 'vview_bl':vsip_valldestroy_bl, 'vview_d':vsip_valldestroy_d, 'vview_f':vsip_valldestroy_f, 'vview_i':vsip_valldestroy_i, 'vview_mi':vsip_valldestroy_mi, 'vview_si':vsip_valldestroy_si, 'vview_uc':vsip_valldestroy_uc, 'vview_vi':vsip_valldestroy_vi} assert (t[0] and t[1] in f), 'Type <:%s:> not recongnized for allDestroy.'%t[1] f[t[1]](a) # Random Number Generation class randcreate(object): """ randcreate defaults to vsip_randcreate(s, 1,1,VSIP_PRNG) if an integer is passed in as the argument. If the argument type is 'randstate' then this object is used to initialize the randcreate object. """ def __init__(self,s): t = getType(s) if isinstance(s,int): self.rand= vsip_randcreate(s,1,1,VSIP_PRNG) elif t[0] and t[1]=='randstate': self.rand = s; else: assert False,'argument must be an integer or a randstate object' def get(self): return self.rand def randu(self,a): t=getType(a) f = {'cvview_d':vsip_cvrandu_d, 'cvview_f':vsip_cvrandu_f, 'vview_d':vsip_vrandu_d, 'vview_f':vsip_vrandu_f} assert t[0] and t[1] in f,'Not a supported type for randu.' f[t[1]](self.rand,a) return a def randn(self,a): t=getType(a) f = {'cvview_d':vsip_cvrandn_d, 'cvview_f':vsip_cvrandn_f, 'vview_d':vsip_vrandn_d, 'vview_f':vsip_vrandn_f} assert t[0] and t[1] in f,'Not a supported type for randn' f[t[1]](self.rand,a) return a def __del__(self): t=getType(self.rand) if t[0]: vsip_randdestroy(self.rand) def rand(seed,numprocs,id,rng): return vsip_randcreate(seed,numprocs,id,rng) def randn(state, a): f={'cvview_d':vsip_cvrandn_d, 'cvview_f':vsip_cvrandn_f, 'vview_d':vsip_vrandn_d, 'vview_f':vsip_vrandn_f} t=getType(a)[1] assert t in f,'Type <:%s:> not supported for randn'%t f[t](state,a) return a def randu(state, a): f={'cvview_d':vsip_cvrandu_d, 'cvview_f':vsip_cvrandu_f, 'vview_d':vsip_vrandu_d, 'vview_f':vsip_vrandu_f} t=getType(a)[1] assert t in f,'Type <:%s:> not supported for randu'%t f[t](state,a) return a def randDestroy(state): return vsip_randdestroy(state) # Elementary math functions def acos(a,b): t=getType(a) f={ 'mview_d':vsip_macos_d, 'mview_f':vsip_macos_f, 'vview_d':vsip_vacos_d, 'vview_f':vsip_vacos_f} assert (t[0] and t[1] in f),'Type <:%s:> note supported by acos.'%t f[t[1]](a,b) return b def asin(a,b): t=getType(a) f={ 'mview_d':vsip_masin_d, 'mview_f':vsip_masin_f, 'vview_d':vsip_vasin_d, 'vview_f':vsip_vasin_f} assert (t[0] and t[1] in f),'Type <:%s:> note supported by asin.'%t f[t[1]](a,b) return b def cos(a,b): t=getType(a) f={ 'mview_d':vsip_mcos_d, 'mview_f':vsip_mcos_f, 'vview_d':vsip_vcos_d, 'vview_f':vsip_vcos_f} assert t[0] and t[1] in f,'Type <:%s:> not a supported type for cos.'%t[1] f[t[1]](a,b) return b def cosh(a,b): t=getType(a) f={ 'mview_d':vsip_mcosh_d, 'mview_f':vsip_mcosh_f, 'vview_d':vsip_vcosh_d, 'vview_f':vsip_vcosh_f} assert (t[0] and t[1] in f),'Type <:%s:> note supported by cosh.'%t f[t[1]](a,b) return b def exp(a,b): """" Supported for matrix and vector floats of type real and complex """ t=getType(a) f={ 'cmview_d':vsip_cmexp_d, 'cmview_f':vsip_cmexp_f, 'cvview_d':vsip_cvexp_d, 'cvview_f':vsip_cvexp_f, 'mview_d':vsip_mexp_d, 'mview_f':vsip_mexp_f, 'vview_d':vsip_vexp_d, 'vview_f':vsip_vexp_f} assert (t[0] and t[1] in f),'Type <:%s:> note supported by tan.'%t f[t[1]](a,b) return b def exp10(a,b): t=getType(a) f={ 'mview_d':vsip_mexp10_d, 'mview_f':vsip_mexp10_f, 'vview_d':vsip_vexp10_d, 'vview_f':vsip_vexp10_f} assert (t[0] and t[1] in f),'Type <:%s:> note supported by exp10.'%t f[t[1]](a,b) return b def log(a,b): """" Supported for matrix and vector floats of type real and complex """ t=getType(a) f={ 'cmview_d':vsip_cmlog_d, 'cmview_f':vsip_cmlog_f, 'cvview_d':vsip_cvlog_d, 'cvview_f':vsip_cvlog_f, 'mview_d':vsip_mlog_d, 'mview_f':vsip_mlog_f, 'vview_d':vsip_vlog_d, 'vview_f':vsip_vlog_f} assert (t[0] and t[1] in f),'Type <:%s:> note supported by log.'%t f[t[1]](a,b) return b def log10(a,b): t=getType(a) f={ 'mview_d':vsip_mlog10_d, 'mview_f':vsip_mlog10_f, 'vview_d':vsip_vlog10_d, 'vview_f':vsip_vlog10_f} assert (t[0] and t[1] in f),'Type <:%s:> note supported by log10.'%t f[t[1]](a,b) return b def sin(a,b): t=getType(a) f={ 'mview_d':vsip_msin_d, 'mview_f':vsip_msin_f, 'vview_d':vsip_vsin_d, 'vview_f':vsip_vsin_f} assert (t[0] and t[1] in f),'Type <:%s:> note supported by sin.'%t f[t[1]](a,b) return b def sinh(a,b): t=getType(a) f={ 'mview_d':vsip_msinh_d, 'mview_f':vsip_msinh_f, 'vview_d':vsip_vsinh_d, 'vview_f':vsip_vsinh_f} assert (t[0] and t[1] in f),'Type <:%s:> note supported by sinh.'%t f[t[1]](a,b) return b def sqrt(a,b): """" Supported for matrix and vector floats of type real and complex """ t=getType(a) f={ 'cmview_d':vsip_cmsqrt_d, 'cmview_f':vsip_cmsqrt_f, 'cvview_d':vsip_cvsqrt_d, 'cvview_f':vsip_cvsqrt_f, 'mview_d':vsip_msqrt_d, 'mview_f':vsip_msqrt_f, 'vview_d':vsip_vsqrt_d, 'vview_f':vsip_vsqrt_f} assert (t[0] and t[1] in f),'Type <:%s:> note supported by sqrt.'%t f[t[1]](a,b) return b def tan(a,b): t=getType(a) f={ 'mview_d':vsip_mtan_d, 'mview_f':vsip_mtan_f, 'vview_d':vsip_vtan_d, 'vview_f':vsip_vtan_f} assert (t[0] and t[1] in f),'Type <:%s:> note supported by tan.'%t f[t[1]](a,b) return b def tanh(a,b): t=getType(a) f={ 'mview_d':vsip_mtanh_d, 'mview_f':vsip_mtanh_f, 'vview_d':vsip_vtanh_d, 'vview_f':vsip_vtanh_f} assert (t[0] and t[1] in f),'Type <:%s:> not supported by tanh.'%t f[t[1]](a,b) return b #Unary Operations def arg(input,output): f={'cmview_dmview_d':vsip_marg_d, 'cmview_fmview_d':vsip_marg_f, 'cvview_dvview_d':vsip_varg_d, 'cvview_fvview_f':vsip_varg_f} t=getType(input)[1]+getType(output)[1] assert t in f,'Type <:%s:> not supported for arg.'%t f[t](input,output) return output def conj(input,output): f={'cmview_d':vsip_cmconj_d, 'cmview_f':vsip_cmconj_f, 'cvview_d':vsip_cvconj_d, 'cvview_f':vsip_cvconj_f} fr=['vview_d','vview_f','mview_d','mview_f'] t=getType(input)[1] assert t == getType(output)[1],'Type of input and output must be the same for conj.' if t in f: f[t](input,output) return output elif t in fr: return copy(input,output) else: assert False,'Type <:%s:> Not a supported type for conj.'%t def cumsum(input,output): """ cumsum(input,output) input is a vector or matrix. output is either a vector for vector inpute or output is a tuple consiting of a vsip_major flag plus a corresponding matrix; For instance cumsum(vector_input, vector_output) or cumsum(matrix_input, (VSIP_ROW, matrix_output)) """ f={'mview_dtuple':'vsip_mcumsum_d(input,output[0],output[1])', 'mview_ftuple':'vsip_mcumsum_f(input,output[0],output[1])', 'mview_ituple':'vsip_mcumsum_i(input,output[0],output[1])', 'mview_situple':'vsip_mcumsum_si(input,output[0],output[1])', 'vview_dvview_d':'vsip_vcumsum_d(input,output)', 'vview_fvview_f':'vsip_vcumsum_f(input,output)', 'vview_ivview_i':'vsip_vcumsum_i(input,output)', 'vview_sivview_si':'vsip_vcumsum_si}(input,output)'} t=str() if getType(output)[0]: if type(output)==tuple : t=getType(input)[1]+'tuple' else: t=getType(input)[1]+getType(output)[1] assert t in f,'Type <:%s:> not supported for cumsum.'%t eval(f[t]) def euler(input,output): f={'mview_dcmview_d':vsip_meuler_d, 'mview_fcmview_f':vsip_meuler_f, 'vview_dcvview_d':vsip_veuler_d, 'vview_fcvview_f':vsip_veuler_f} t=getType(input)[1]+getType(output)[1] assert t in f,'Type <:%s:> not supported for euler.'%t f[t](input,output) return output def mag(input,output): f={'cmview_d':vsip_cmmag_d, 'cmview_f':vsip_cmmag_f, 'cvview_d':vsip_cvmag_d, 'cvview_f':vsip_cvmag_f, 'mview_d':vsip_mmag_d, 'mview_f':vsip_mmag_f, 'vview_d':vsip_vmag_d, 'vview_f':vsip_vmag_f, 'vview_i':vsip_vmag_i, 'vview_si':vsip_vmag_si} t = getType(input)[1] assert t in f,'Type <:%s:> not supported for mag.'%t f[t](input,output) return output def magsq(input,output): f={'cmview_d':vsip_mcmagsq_d, 'cmview_f':vsip_mcmagsq_f, 'cvview_d':vsip_vcmagsq_d, 'cvview_f':vsip_vcmagsq_f} t = getType(input)[1] assert t in f,'Type <:%s:> not supported for magsq.'%t f[t](input,output) return output def meanval(input): f={'cmview_d':vsip_cmmeanval_d, 'cvview_d':vsip_cvmeanval_d, 'cmview_f':vsip_cmmeanval_f, 'cvview_f':vsip_cvmeanval_f, 'mview_d':vsip_mmeanval_d, 'vview_d':vsip_vmeanval_d, 'mview_f':vsip_mmeanval_f, 'vview_f':vsip_vmeanval_f} t=getType(input)[1] assert t in f,'Type <:%s:> not supported for meanval.'%t return f[t](input) def meansqval(input): f={'cmview_d':vsip_cmmeansqval_d, 'cvview_d':vsip_cvmeansqval_d, 'cmview_f':vsip_cmmeansqval_f, 'cvview_f':vsip_cvmeansqval_f, 'mview_d':vsip_mmeansqval_d, 'vview_d':vsip_vmeansqval_d, 'mview_f':vsip_mmeansqval_f, 'vview_f':vsip_vmeansqval_f} t=getType(input)[1] assert t in f,'Type <:%s:> not supported for meansqval.'%t return f[t](input) def modulate(input,nu,phi,output): f={'cvview_d':vsip_cvmodulate_d, 'vview_d':vsip_vmodulate_d, 'cvview_f':vsip_cvmodulate_f, 'vview_f':vsip_vmodulate_f} t=getType(input)[1] assert t in f,'Type <:%s:> not supported for modulate.'%t return f[t](input,nu,phi,output) def neg(a,b): """ Elementwise place the negative values of a in b. May be done in place using neg(a,a) Returns the result as a convinience. """ t=getType(a) f= {'cmview_f':vsip_cmneg_d, 'cmview_f':vsip_cmneg_f, 'cvview_d':vsip_cvneg_d, 'cvview_f':vsip_cvneg_f, 'mview_d':vsip_mneg_d, 'mview_f':vsip_mneg_f, 'vview_d':vsip_vneg_d, 'vview_f':vsip_vneg_f, 'vview_i':vsip_vneg_i, 'vview_si':vsip_vneg_si} assert (t[0] and t[1] in f),'Type <:%s:> not supported for neg.'%t[1] f[t[1]](a,b) return b def recip(a,b): f={'cmview_d':vsip_cmrecip_d, 'cmview_f':vsip_cmrecip_f, 'cvview_d':vsip_cvrecip_d, 'cvview_f':vsip_cvrecip_f, 'mview_d':vsip_mrecip_d, 'mview_f':vsip_mrecip_f, 'vview_d':vsip_vrecip_d, 'vview_f':vsip_vrecip_f} t = getType(a)[1] assert t in f,'Type <:%s:> not supported for recip.'%t f[t](a,b) return b def rsqrt(a,b): f={'mview_d':vsip_mrsqrt_d, 'mview_f':vsip_mrsqrt_f, 'vview_d':vsip_vrsqrt_d, 'vview_f':vsip_vrsqrt_f} t = getType(a)[1] assert t in f,'Type <:%s:> not supported for rsqrt.'%t f[t](a,b) return b; def sq(a,b): f={'mview_d':vsip_msq_d, 'mview_f':vsip_msq_f, 'vview_d':vsip_vsq_d, 'vview_f':vsip_vsq_f} t = getType(a)[1] assert t in f,'Type <:%s:> not supported for sq.'%t f[t](a,b) return b; def sumval(input): f={'cmview_d':'cscalarToComplex(vsip_cmsumval_d ( input ))', 'cvview_d':'cscalarToComplex(vsip_cvsumval_d ( input ))', 'cmview_f':'cscalarToComplex(vsip_cmsumval_f ( input ))', 'cvview_f':'cscalarToComplex(vsip_cvsumval_f ( input ))', 'mview_d':'vsip_msumval_d ( input )', 'vview_d':'vsip_vsumval_d ( input )', 'mview_f':'vsip_msumval_f ( input )', 'vview_f':'vsip_vsumval_f ( input )', 'vview_i':'vsip_vsumval_i ( input )', 'vview_si':'vsip_vsumval_si ( input )', 'vview_uc':'vsip_vsumval_uc ( input )', 'mview_bl':'vsip_msumval_bl ( input )', 'vview_bl':'vsip_vsumval_bl ( input )'} t=getType(input)[1] assert t in f,'Type <:%s:> not supported for sumval.'%t return eval(f[t]) def sumsqval(input): f={'mview_d':vsip_msumsqval_d, 'mview_f':vsip_msumsqval_f, 'vview_d':vsip_vsumsqval_d, 'vview_f':vsip_vsumsqval_f} t=getType(input)[1] assert t in f,'Type <:%s:> not supported for sumsqval.'%t return f[t](input) #Binary Operations def add(a,b,c): """ Through introspection add two vsipl objects. add(a,b,c) adds a to b elementwise returning the answer in c. Unlike VSIPL this add will return c as a convenience. note not every combination is supported. Currently supported are vsip_vadd_f, vsip_vadd_d, vsip_madd_f, vsip_madd_d, vsip_cvadd_f, vsip_cvadd_d, vsip_cmadd_f, vsip_cmadd_d, vsip_vadd_i, vsip_madd_i, vsip_vadd_si, vsip_madd_si, vsip_vadd_vi, vsip_vadd_uc, vsip_rcvadd_f, vsip_rcvadd_d, vsip_rcmadd_f, vsip_rcmadd_d, vsip_csmadd_d, vsip_csmadd_f, vsip_csvadd_d, vsip_csvadd_f, vsip_rscmadd_d, vsip_rscmadd_f, vsip_rscvadd_d, vsip_rscvadd_f, vsip_smadd_d, vsip_smadd_f, vsip_svadd_d, vsip_svadd_f, vsip_svadd_i, vsip_svadd_si, vsip_svadd_uc, vsip_svadd_vi to decode read about vsipl naming conventions in VSIPL specification. """ t0=getType(a) t1=getType(b) t = str() if t0[0] and t1[0]: t= t0[1] + t1[1] f={ 'vview_fvview_f': vsip_vadd_f, 'vview_dvview_d': vsip_vadd_d, 'mview_fmview_f': vsip_madd_f, 'mview_dmview_d': vsip_madd_d, 'cvview_fcvview_f': vsip_cvadd_f, 'cvview_dcvview_d': vsip_cvadd_d, 'cmview_fcmview_f': vsip_cmadd_f, 'cmview_dcmview_d': vsip_cmadd_d, 'vview_ivview_i': vsip_vadd_i, 'mview_imview_i': vsip_madd_i, 'vview_sivview_si': vsip_vadd_si, 'mview_simview_si': vsip_madd_si, 'vview_vivview_vi': vsip_vadd_vi, 'vview_ucvview_uc': vsip_vadd_uc, 'vview_fcvview_f': vsip_rcvadd_f, 'vview_dcvview_d':vsip_rcvadd_d, 'mview_fcmview_f': vsip_rcmadd_f, 'mview_dcmview_d':vsip_rcmadd_d, 'cscalar_dcmview_d':vsip_csmadd_d, 'cscalar_fcmview_f':vsip_csmadd_f, 'cscalar_dcvview_d':vsip_csvadd_d, 'cscalar_fcvview_f':vsip_csvadd_f, 'scalarcmview_d':vsip_rscmadd_d, 'scalarcmview_f':vsip_rscmadd_f, 'scalarcvview_d':vsip_rscvadd_d, 'scalarcvview_f':vsip_rscvadd_f, 'scalarmview_d':vsip_smadd_d, 'scalarmview_f':vsip_smadd_f, 'scalarvview_d':vsip_svadd_d, 'scalarvview_f':vsip_svadd_f, 'scalarvview_i':vsip_svadd_i, 'scalarvview_si':vsip_svadd_si, 'scalarvview_uc':vsip_svadd_uc, 'scalarvview_vi':vsip_svadd_vi} assert t in f,'Type <:%s:> not supported by add.'%t f[t](a,b,c) return c def expoavg(alpha,b,c): f={'cmview_d':vsip_cmexpoavg_d, 'cmview_f':vsip_cmexpoavg_f, 'cvview_d':vsip_cvexpoavg_d, 'cvview_f':vsip_cvexpoavg_f, 'mview_d':vsip_mexpoavg_d, 'mview_f':vsip_mexpoavg_f, 'vview_d':vsip_vexpoavg_d, 'vview_f':vsip_vexpoavg_f} t=getType(b)[1] assert t in f,'Type <:%s:> not supported for expoavg.'%t f[t](alpha,b,c) return c def hypot(a,b,c): f={'mview_d':vsip_mhypot_d, 'mview_f':vsip_mhypot_f, 'vview_d':vsip_vhypot_d, 'vview_f':vsip_vhypot_f} t=getType(a)[1] assert t in f,'Type <:%s:> not supported for hypot.'%t f[t](a,b,c) return c def sub(a,b,c): """ sub(a,b,c) does a-b returning the result in c. View c is returned as a convenience. The first argument, a may be a scalar, Otherwise a and b must be of the same size. VSIPL functions supported are vsip_cmsub_d, vsip_cmsub_f, vsip_crmsub_d, vsip_crmsub_f, vsip_crvsub_d, vsip_crvsub_f, vsip_csmsub_d, vsip_csmsub_f, vsip_csvsub_d, vsip_csvsub_f, vsip_cvsub_d, vsip_cvsub_f, vsip_msub_d, vsip_msub_f, vsip_msub_i, vsip_msub_si, vsip_rcmsub_d, vsip_rcmsub_f, vsip_rcvsub_d, vsip_rcvsub_f,vsip_rscmsub_d, vsip_rscmsub_f, vsip_rscvsub_d, vsip_rscvsub_f, vsip_smsub_d, vsip_smsub_f, vsip_smsub_i, vsip_smsub_si, vsip_svsub_d, vsip_svsub_f, vsip_svsub_i, vsip_svsub_si, vsip_svsub_uc, vsip_svsub_vi, vsip_vsub_d, vsip_vsub_f, vsip_vsub_i, vsip_vsub_si, vsip_vsub_uc """ t0=getType(a) t1=getType(b) t = str() if t0[0] and t1[0]: t= t0[1] + t1[1] f={'cmview_dcmview_d':vsip_cmsub_d, 'cmview_fcmview_f':vsip_cmsub_f, 'cmview_dmview_d':vsip_crmsub_d, 'cmview_fmview_f':vsip_crmsub_f, 'cvview_dvview_d':vsip_crvsub_d, 'cvview_fvview_f':vsip_crvsub_f, 'cscalar_dcmview_d':vsip_csmsub_d, 'cscalar_fcmview_f':vsip_csmsub_f, 'cscalar_fcvview_d':vsip_csvsub_d, 'cscalar_fcvview_f':vsip_csvsub_f, 'cvview_dcvview_d':vsip_cvsub_d, 'cvview_fcvview_f':vsip_cvsub_f, 'mview_dmview_d':vsip_msub_d, 'mview_fmview_f':vsip_msub_f, 'mview_imview_i':vsip_msub_i, 'mview_simview_si':vsip_msub_si, 'mview_dcmview_d':vsip_rcmsub_d, 'mview_fcmview_f':vsip_rcmsub_f, 'vview_dcvview_d':vsip_rcvsub_d, 'vview_fcvview_f':vsip_rcvsub_f, 'scalarcmview_d':vsip_rscmsub_d, 'scalarcmview_f':vsip_rscmsub_f, 'scalarcvview_d':vsip_rscvsub_d, 'scalarcvview_f':vsip_rscvsub_f, 'scalarmview_d':vsip_smsub_d, 'scalarmview_f':vsip_smsub_f, 'scalarmview_i':vsip_smsub_i, 'scalarmview_si':vsip_smsub_si, 'scalarvview_d':vsip_svsub_d, 'scalarvview_f':vsip_svsub_f, 'scalarvview_i':vsip_svsub_i, 'scalarvview_si':vsip_svsub_si, 'scalarvview_uc':vsip_svsub_uc, 'scalarvview_vi':vsip_svsub_vi, 'vview_dvview_d':vsip_vsub_d, 'vview_fvview_f':vsip_vsub_f, 'vview_ivview_i':vsip_vsub_i, 'vview_sivview_si':vsip_vsub_si, 'vview_ucvview_uc':vsip_vsub_uc} assert t in f,'Type <:%s:> not found for sub.'%t f[t](a,b,c) return c def mul(a,b,c): """ Through introspection multiply elementwise two vsipl objects. mul(a,b,c) multiplies a times b elementwise returning the answer in c. Unlike VSIPL this mul returns the answer as a convenience. May be done in-place if a or b is the same type as c. VSIPL functions supported are vsip_vmul_d, vsip_vmul_f, vsip_vmul_i, vsip_vmul_si, vsip_vmul_uc, vsip_cmmul_d, vsip_cmmul_f, vsip_cvmul_d, vsip_cvmul_f, vsip_mmul_d, vsip_mmul_f, vsip_rcmmul_d, vsip_rcmmul_f, vsip_rcvmul_d, vsip_rcvmul_f, vsip_rscmmul_d, vsip_rscmmul_f, vsip_rscvmul_d, vsip_rscvmul_f, vsip_smmul_d, vsip_smmul_f, vsip_svmul_d, vsip_svmul_f, vsip_svmul_i, vsip_svmul_si, vsip_svmul_uc, vsip_csmmul_d, vsip_csmmul_f, vsip_csvmul_d, vsip_csvmul_f To decode read about vsipl naming conventions in VSIPL specification. Note there are other muls which could not be included because the API was not the same, or conflicted. For instance vsip_cjmul_d has the same type inputs as vsip_cmul_d. """ t0=getType(a) t1=getType(b) t = str() if t0[0] and t1[0]: t= t0[1] + t1[1] f={ 'vview_dvview_d':vsip_vmul_d, 'vview_fvview_f':vsip_vmul_f, 'vview_ivview_i':vsip_vmul_i, 'vview_sivview_si':vsip_vmul_si, 'vview_ucvview_uc':vsip_vmul_uc, 'cmview_dvview_d':vsip_cmmul_d, 'cmview_fcmview_f':vsip_cmmul_f, 'cvview_dcvview_d':vsip_cvmul_d, 'cvview_fcvview_f':vsip_cvmul_f, 'mview_dmview_d':vsip_mmul_d, 'mview_fmview_f':vsip_mmul_f, 'mview_dcmview_d':vsip_rcmmul_d, 'mview_fcmview_f':vsip_rcmmul_f, 'vview_dcvview_d':vsip_rcvmul_d, 'vview_fcvview_f':vsip_rcvmul_f, 'scalarcmview_d':vsip_rscmmul_d, 'scalarcmview_f':vsip_rscmmul_f, 'scalarcvview_d':vsip_rscvmul_d, 'scalarcvview_f':vsip_rscvmul_f, 'scalarmview_d':vsip_smmul_d, 'scalarmview_f':vsip_smmul_f, 'scalarvview_d':vsip_svmul_d, 'scalarvview_f':vsip_svmul_f, 'scalarvview_i':vsip_svmul_i, 'scalarvview_si':vsip_svmul_si, 'scalarvview_uc':vsip_svmul_uc, 'cscalar_dcmview_d':vsip_csmmul_d, 'cscalar_fcmview_f':vsip_csmmul_f, 'cscalar_dcvview_d':vsip_csvmul_d, 'cscalar_fcvview_f':vsip_csvmul_f} assert t in f,'Type <:%s:> not found for mul.'%t f[t](a,b,c) return c def vmmul(a,b,flg,c): """ This function does vmmul, -cvmmul, and rvcmmul """ f={'cvview_dcmview_d':vsip_cvmmul_d, 'cvview_fcmview_f':vsip_cvmmul_f, 'vview_dcmview_d':vsip_rvcmmul_d, 'vview_fcmview_f':vsip_rvcmmul_f, 'vview_dmview_d':vsip_vmmul_d, 'vview_fmview_f':vsip_vmmul_f} t=getType(a)[1]+getType(b)[1] if t in f: f[t](a,b,flg,c) return c else: assert False,'Type %s not supported for vmmul.'%t def jmul(a,b,c): f={'cmview_d':vsip_cmjmul_d, 'cmview_f':vsip_cmjmul_f, 'cvview_d':vsip_cvjmul_d, 'cvview_f':vsip_cvjmul_f} if t in f: f[t](a,b,c) return c else: assert False,'Type %s Not a valid type for jmul'%t def div(a,b,c): """ Divide a by b puting result in c. Here c is returned as a convenience. Arguments a or b (not both) may be a scalar. Otherwise all arguments are the same size. VSIPL functions supported are vsip_cmdiv_d, vsip_cmdiv_f, vsip_cmrsdiv_d, vsip_cmrsdiv_f, vsip_crmdiv_d, vsip_crmdiv_f, vsip_crvdiv_d, vsip_crvdiv_f, vsip_csmdiv_d, vsip_csmdiv_f, vsip_csvdiv_d, vsip_csvdiv_f, vsip_cvdiv_d, vsip_cvdiv_f, vsip_cvrsdiv_d, vsip_cvrsdiv_f, vsip_mdiv_d, vsip_mdiv_f, vsip_msdiv_d, vsip_msdiv_f, vsip_rcmdiv_d, vsip_rcmdiv_f, vsip_rcvdiv_d, vsip_rcvdiv_f, vsip_rscmdiv_d, vsip_rscmdiv_f, vsip_rscvdiv_d, vsip_rscvdiv_f, vsip_smdiv_d, vsip_smdiv_f, vsip_svdiv_d, vsip_svdiv_f, vsip_vdiv_d, vsip_vdiv_f, vsip_vsdiv_d, vsip_vsdiv_f """ def _cOverCscalar(v,s,r): m=s.r * s.r + s.i * s.i s.r /= m; s.i /= -m mul(s,v,r) t0=getType(a)[1] t1=getType(b)[1] t=t0+t1 f = {'cmview_dcmview_d':vsip_cmdiv_d, 'cmview_fcmview_f':vsip_cmdiv_f, 'cmview_dscalar':vsip_cmrsdiv_d, 'cmview_fscalar':vsip_cmrsdiv_f, 'cmview_dmview_d':vsip_crmdiv_d, 'cmview_fmview_f':vsip_crmdiv_f, 'cvview_dvview_d':vsip_crvdiv_d, 'cvview_fvview_f':vsip_crvdiv_f, 'cscalar_dcmview_d':vsip_csmdiv_d, 'cscalar_fcmview_f':vsip_csmdiv_f, 'cscalar_dcvview_d':vsip_csvdiv_d, 'cscalar_fcvview_f':vsip_csvdiv_f, 'cvview_dcvview_d':vsip_cvdiv_d, 'cvview_fcvview_f':vsip_cvdiv_f, 'cvview_dscalar':vsip_cvrsdiv_d, 'cvview_fscalar':vsip_cvrsdiv_f, 'mview_dmview_d':vsip_mdiv_d, 'mview_fmview_d':vsip_mdiv_f, 'mview_dscalar':vsip_msdiv_d, 'mview_fscalar':vsip_msdiv_f, 'mviwew_dcmview_d':vsip_rcmdiv_d, 'mview_fcmview_f':vsip_rcmdiv_f, 'vview_dcvview_d':vsip_rcvdiv_d, 'vview_fcvview_f':vsip_rcvdiv_f, 'scalarcmview_d':vsip_rscmdiv_d, 'scalarcmview_f':vsip_rscmdiv_f, 'scalarcvview_d':vsip_rscvdiv_d, 'scalarcvview_f':vsip_rscvdiv_f, 'scalarmview_d':vsip_smdiv_d, 'scalarmview_f':vsip_smdiv_f, 'scalarvview_d':vsip_svdiv_d, 'scalarvview_f':vsip_svdiv_f, 'vview_dvview_d':vsip_vdiv_d, 'vview_fvview_f':vsip_vdiv_f, 'vview_dscalar':vsip_vsdiv_d, 'vview_fscalar':vsip_vsdiv_f} g = {'cvview_fcscalar_f': _cOverCscalar, 'cvview_dcscalar_d': _cOverCscalar, 'cmview_fcscalar_f': _cOverCscalar, 'cmview_dcscalar_d': _cOverCscalar} if t in f: f[t](a,b,c) return c elif t in g: g[t](a,b,c) return c else: assert False,'Type <:%s:> not recognized for div'%t # Ternary Operations # Logical Operations # Selection Operations # Bitwise and Boolean def am(a,b,c,d): """ add and multiply (a+b) * c am(a,b,c,d) adds a to b and then multiplies c putting result in d """ f={'cvview_dcvview_dcvview_d':vsip_cvam_d, 'cvview_fcvview_fcvview_f':vsip_cvam_f, 'cvview_dcscalar_dcvview_d':vsip_cvsam_d, 'cvview_fcscalar_fcvview_f':vsip_cvsam_f, 'vview_dvview_dvview_d':vsip_vam_d, 'vview_fvview_fvview_f':vsip_vam_f, 'vview_dscalarvview_d':vsip_vsam_d, 'vview_fscalarvview_f':vsip_vsam_f} t=getType(a)[1]+getType(b)[1]+getType(c)[1] assert t in f,'Type <:%s:> not supported by am.'%t f[t](a,b,c,d) return d def ma(a,b,c,d): """ multiply add (a*b) + c ma(a,b,c,d) multiplies a * b and adds c """ f={'cvview_dcscalar_dcscalar_d':vsip_cvsmsa_d, 'cvview_fcscalar_fcscalar_f':vsip_cvsmsa_f, 'vview_dscalarscalar':vsip_vsmsa_d, 'vview_fscalar_fscalar_f':vsip_vsmsa_f, 'cvview_dcscalar_dcvview_d':vsip_cvsma_d, 'cvview_fcscalar_fcscalar_f':vsip_cvsma_f, 'vview_dscalarvview_d':vsip_vsma_d, 'vview_fscalarvview_f':vsip_vsma_f, 'cvview_dcvview_dcvview_d':vsip_cvma_d, 'cvview_fcvview_fcvview_f':vsip_cvma_f, 'vview_dvview_dvview_d':vsip_vma_d, 'vview_fvview_fvview_f':vsip_vma_f, 'cvview_dcvview_dcscalar_d':vsip_cvmsa_d, 'cvview_fcvview_fcscalar_f':vsip_cvmsa_f, 'vview_dvview_dscalar':vsip_vmsa_d, 'vview_fvview_fscalar':vsip_vmsa_f} t=getType(a)[1]+getType(b)[1]+getType(c)[1] assert t in f,'Type <:%s:> not supported by ma.'%t f[t](a,b,c,d) return d def msb(a,b,c,d): """ multiply subtract (a*b) -c """ f={'cvview_dcvview_dcvview_d':vsip_cvmsb_d, 'cvview_fcvview_fcvview_f':vsip_cvmsb_f, 'vview_dvview_dvview_d':vsip_vmsb_d, 'vview_fvview_fvview_f':vsip_vmsb_f} t=getType(a)[1]+getType(b)[1]+getType(c)[1] assert t in f,'Type <:%s:> not supported by msb.'%t f[t](a,b,c,d) return d def sbm(a,b,c,d): """ subtract multiply (a-b) * c """ f={'cvview_dcvview_dcvview_d':vsip_cvsbm_d, 'cvview_fcvview_fcvview_f':vsip_cvsbm_f, 'vview_dvview_dvview_d':vsip_vsbm_d, 'vview_fvview_fvview_f':vsip_vsbm_f} t=getType(a)[1]+getType(b)[1]+getType(c)[1] assert t in f,'Type <:%s:> not supported by sbm.'%t f[t](a,b,c,d) return d # Logical Operations def alltrue(a): f={'mview_bl':vsip_malltrue_bl, 'vview_bl':vsip_valltrue_bl} t=getType(a)[1] assert t in f,'Type <:%s:> not supported by alltrue.'%t return 1 == f[t](a) def anytrue(a): f={'mview_bl':vsip_manytrue_bl, 'vview_bl':vsip_vanytrue_bl} t=getType(a)[1] assert t in f,'Type <:%s:> not supported by anytrue.'%t return 1 == f[t](a) def leq(a,b,c): f={'mview_dmview_d':vsip_mleq_d, 'mview_fmview_f':vsip_mleq_f, 'vview_dvview_d':vsip_vleq_d, 'vview_fvview_f':vsip_vleq_f, 'vview_ivview_i':vsip_vleq_i, 'vview_sivview_si':vsip_vleq_si, 'vview_ucvview_uc':vsip_vleq_uc} t=getType(a)[1]+getType(b)[1] assert t in f,'Type <:%s:> not supported by leq.'%t f[t](a,b,c) return c def lge(a,b,c): f={'mview_dmview_d':vsip_mlge_d, 'mview_fmview_f':vsip_mlge_f, 'vview_dvview_d':vsip_vlge_d, 'vview_fvview_f':vsip_vlge_f, 'vview_ivview_i':vsip_vlge_i, 'vview_sivview_si':vsip_vlge_si, 'vview_ucvview_uc':vsip_vlge_uc} t=getType(a)[1]+getType(b)[1] assert t in f,'Type <:%s:> not supported by lge.'%t f[t](a,b,c) return c def lgt(a,b,c): f={'mview_dmview_d':vsip_mlgt_d, 'mview_fmview_f':vsip_mlgt_f, 'vview_dvview_d':vsip_vlgt_d, 'vview_fvview_f':vsip_vlgt_f, 'vview_ivview_i':vsip_vlgt_i, 'vview_sivview_si':vsip_vlgt_si, 'vview_ucvview_uc':vsip_vlgt_uc} t=getType(a)[1]+getType(b)[1] assert t in f,'Type <:%s:> not supported by lgt.'%t f[t](a,b,c) return c def lle(a,b,c): f={'mview_dmview_d':vsip_mlle_d, 'mview_fmview_f':vsip_mlle_f, 'vview_dvview_d':vsip_vlle_d, 'vview_fvview_f':vsip_vlle_f, 'vview_ivview_i':vsip_vlle_i, 'vview_sivview_si':vsip_vlle_si, 'vview_ucvview_uc':vsip_vlle_uc} t=getType(a)[1]+getType(b)[1] assert t in f,'Type <:%s:> not supported by lle.'%t f[t](a,b,c) return c def llt(a,b,c): f={'mview_dmview_d':vsip_mllt_d, 'mview_fmview_f':vsip_mllt_f, 'vview_dvview_d':vsip_vllt_d, 'vview_fvview_f':vsip_vllt_f, 'vview_ivview_i':vsip_vllt_i, 'vview_sivview_si':vsip_vllt_si, 'vview_ucvview_uc':vsip_vllt_uc} t=getType(a)[1]+getType(b)[1] assert t in f,'Type <:%s:> not supported by llt.'%t f[t](a,b,c) return c def lne(a,b,c): f={'mview_dmview_d':vsip_mlne_d, 'mview_fmview_f':vsip_mlne_f, 'vview_dvview_d':vsip_vlne_d, 'vview_fvview_f':vsip_vlne_f, 'vview_ivview_i':vsip_vlne_i, 'vview_sivview_si':vsip_vlne_si, 'vview_ucvview_uc':sip_vlne_uc} t=getType(a)[1]+getType(b)[1] assert t in f,'Type <:%s:> not supported by lne.'%t f[t](a,b,c) return c # Element Generation and Copy def fill(a_scalar,a_view): """ Fill view object b with scalar object a VSIPL functions supported are vsip_cmfill_d, vsip_cmfill_f, vsip_cvfill_d, vsip_cvfill_f, vsip_mfill_d, vsip_mfill_f, vsip_mfill_i, vsip_mfill_si, vsip_vfill_d, vsip_vfill_f, vsip_vfill_i, vsip_vfill_si, vsip_vfill_uc """ t1=getType(a_scalar) t2=getType(a_view) t=str() x=a_scalar ct=['cmview_f','cmview_d','cvview_f','cvview_d'] f={ 'cscalar_dcmview_d':vsip_cmfill_d, 'cscalar_fcmview_f':vsip_cmfill_f, 'cscalar_dcvview_d':vsip_cvfill_d, 'cscalar_fcvview_f':vsip_cvfill_f, 'scalarmview_d':vsip_mfill_d, 'scalarmview_f':vsip_mfill_f, 'scalarmview_i':vsip_mfill_i, 'scalarmview_si':vsip_mfill_si, 'scalarvview_d':vsip_vfill_d, 'scalarvview_f':vsip_vfill_f, 'scalarvview_i':vsip_vfill_i, 'scalarvview_vi':vsip_vfill_vi, 'scalarvview_uc':vsip_vfill_uc} if t2[1] in ct: #do complex myType=str() if t2[1] == 'cmview_d' or t2[1] == 'cvview_d': myType='cscalar_d' else: myType='cscalar_f' if t1[1] == 'scalar' or type(a_view) == complex: x=complexToCscalar(myType,a_scalar) t=getType(x)[1] + t2[1] assert t in f,'Type <:%s:> not supported by fill.'%t f[t](x,a_view) return a_view def ramp(a,b,c): """ A ramp is supported for real vector types. called as ramp(start, increment, vector). Note the length is determined by the vector. returns the result as a convienience. """ t=getType(c)[1] f={'vview_f':vsip_vramp_f, 'vview_d':vsip_vramp_d, 'vview_i':vsip_vramp_i, 'vview_si':vsip_vramp_si, 'vview_uc':vsip_vramp_uc, 'vview_vi':vsip_vramp_vi} assert t in f,'Type <:%s:> not supported by ramp.'%t f[t](a,b,c) return c def copy(a,b): f={'cmview_dcmview_d':vsip_cmcopy_d_d, 'cmview_dcmview_f':vsip_cmcopy_d_f, 'cmview_fcmview_d':vsip_cmcopy_f_d, 'cmview_fcmview_f':vsip_cmcopy_f_f, 'cvview_dcvview_d':vsip_cvcopy_d_d, 'cvview_dcvview_f':vsip_cvcopy_d_f, 'cvview_fcvview_d':vsip_cvcopy_f_d, 'cvview_fcvview_f':vsip_cvcopy_f_f, 'mview_blmview_bl':vsip_mcopy_bl_bl, 'mview_blmview_d':vsip_mcopy_bl_d, 'mview_blmview_f':vsip_mcopy_bl_f, 'mview_dmview_bl':vsip_mcopy_d_bl, 'mview_dmview_d':vsip_mcopy_d_d, 'mview_dmview_f':vsip_mcopy_d_f, 'mview_dmview_i':vsip_mcopy_d_i, 'mview_dmview_uc':vsip_mcopy_d_uc, 'mview_fmview_bl':vsip_mcopy_f_bl, 'mview_fmview_d':vsip_mcopy_f_d, 'mview_fmview_f':vsip_mcopy_f_f, 'mview_fmview_i':vsip_mcopy_f_i, 'mview_fmview_uc':vsip_mcopy_f_uc, 'mview_imview_f':vsip_mcopy_i_f, 'mview_simview_f':vsip_mcopy_si_f, 'vview_blvview_bl':vsip_vcopy_bl_bl, 'vview_blvview_d':vsip_vcopy_bl_d, 'vview_blvview_f':vsip_vcopy_bl_f, 'vview_dvview_bl':vsip_vcopy_d_bl, 'vview_dvview_d':vsip_vcopy_d_d, 'vview_dvview_f':vsip_vcopy_d_f, 'vview_dvview_i':vsip_vcopy_d_i, 'vview_dvview_si':vsip_vcopy_d_si, 'vview_dvview_uc':vsip_vcopy_d_uc, 'vview_dvview_vi':vsip_vcopy_d_vi, 'vview_fvview_bl':vsip_vcopy_f_bl, 'vview_fvview_d':vsip_vcopy_f_d, 'vview_fvview_f':vsip_vcopy_f_f, 'vview_fvview_i':vsip_vcopy_f_i, 'vview_fvview_si':vsip_vcopy_f_si, 'vview_fvview_uc':vsip_vcopy_f_uc, 'vview_fvview_vi':vsip_vcopy_f_vi, 'vview_ivview_d':vsip_vcopy_i_d, 'vview_ivview_f':vsip_vcopy_i_f, 'vview_ivview_i':vsip_vcopy_i_i, 'vview_ivview_uc':vsip_vcopy_i_uc, 'vview_ivview_vi':vsip_vcopy_i_vi, 'vview_mivview_mi':vsip_vcopy_mi_mi, 'vview_sivview_d':vsip_vcopy_si_d, 'vview_sivview_f':vsip_vcopy_si_f, 'vview_sivview_si':vsip_vcopy_si_si, 'vview_vivview_i':vsip_vcopy_vi_i, 'vview_vivview_vi':vsip_vcopy_vi_vi} f1v={'cvview_d':get, 'cvview_f':get, 'vview_d':get, 'vview_f':get, 'vview_i':get, 'vview_si':get, 'vview_uc':get, 'vview_vi':get, 'vview_bl':get, 'vview_mi':get} f1m={'cmview_d':get, 'cmview_f':get, 'mview_d':get, 'mview_f':get, 'mview_i':get, 'mview_si':get, 'mview_uc':get, 'mview_bl':get} t1=getType(a)[1] t2=getType(b)[1] t=t1+t2 if t in f: f[t](a,b) return b elif t1 in f1v and t2 in f1v: for i in range(getlength(a)): put(b,i,get(a,i)) return b elif t1 in f1m and t2 in f1m: for i in range(getcollength(a)): for j in range(getrowlength(a)): put(b,(i,j),get(a,(i,j))) return b else: assert False,'Type <:' + t1 + t2 + ':> not supported by copy' # Selection Operations def clip(a,t1,t2,c1,c2,r): f = {'mview_d':vsip_mclip_d, 'mview_f':vsip_mclip_f, 'mview_i':vsip_mclip_i, 'mview_si':vsip_mclip_si, 'vview_d':vsip_vclip_d, 'vview_f':vsip_vclip_f, 'vview_i':vsip_vclip_i, 'vview_si':vsip_vclip_si, 'vview_uc':vsip_vclip_uc} t=getType(a)[1] assert t in f,'Type <:%s:> not supported by clip.'%t f[t](a,t1,t2,c1,c2,r) return r def invclip(a,t1,t2,t3,c1,c2,r): f={'mview_d':vsip_minvclip_d, 'mview_f':vsip_minvclip_f, 'vview_d':vsip_vinvclip_d, 'vview_f':vsip_vinvclip_f, 'vview_i':vsip_vinvclip_i, 'vview_si':vsip_vinvclip_si, 'vview_uc':vsip_vinvclip_uc} t=getType(a)[1] assert t in f,'Type <:%s:> not supported by invclip.'%t f[t](a,t1,t2,t3,c1,c2,r) return r def indexbool(a,b): f={'mview_bl':vsip_mindexbool, 'vview_bl':vsip_vindexbool} t=getType(a)[1] assert t in f,'Type <:%s:> not supported by indexbool.'%t return f[t](a,b) def max(a,b,c): f={'mview_d':vsip_mmax_d, 'mview_f':vsip_mmax_f, 'vview_d':vsip_vmax_d, 'vview_f':vsip_vmax_f} t=getType(a)[1] assert t in f,'Type <:%s:> not supported by max.'%t f[t](a,b,c) return c def maxmg(a,b,c): f={'mview_d':vsip_mmaxmg_d, 'mview_f':vsip_mmaxmg_f, 'vview_d':vsip_vmaxmg_d, 'vview_f':vsip_vmaxmg_f} t=getType(a)[1] assert t in f,'Type <:%s:> not supported by maxmg.'%t f[t](a,b,c) return c def maxmgsq(a,b,c): f={'cmview_d':vsip_mcmaxmgsq_d, 'cmview_f':vsip_mcmaxmgsq_f, 'cvview_d':vsip_vcmaxmgsq_d, 'cvview_f':vsip_vcmaxmgsq_f} t=getType(a)[1] assert t in f,'Type <:%s:> not supported by maxmgsq.'%t f[t](a,b,c) return c def maxmgsqval(a,idx): f={'cmview_dscalar_mi':'vsip_mcmaxmgsqval_d(a,idx)', 'cvview_dscalar_vi':'vsip_vcmaxmgsqval_d(a,idx)', 'cmview_fscalar_mi':'vsip_mcmaxmgsqval_f(a,idx)', 'cvview_fscalar_vi':'vsip_vcmaxmgsqval_f(a,idx)'} t=getType(a)[1]+getType(idx)[1] assert t in f,'Type <:%s:> not supported by maxmgsqval.'%t return eval(f[t]) def maxmgval(a,idx): f={'mview_dscalar_mi':'vsip_mmaxmgval_d(a,idx)', 'vview_dscalar_vi':'vsip_vmaxmgval_d(a,idx)', 'mview_fscalar_mi':'vsip_mmaxmgval_f(a,idx)', 'vview_fscalar_vi':'vsip_vmaxmgval_f(a,idx)'} t=getType(a)[1]+getType(idx)[1] assert t in f,'Type <:%s:> not supported by maxmgval.'%t return eval(f[t]) def maxval(a,idx): f={'mview_d':'vsip_mmaxval_d(a,idx)', 'vview_d':'vsip_vmaxval_d(a,idx)', 'mview_f':'vsip_mmaxval_f(a,idx)', 'vview_f':'vsip_vmaxval_f(a,idx)', 'mview_i':'vsip_mmaxval_i(a,idx)', 'vview_i':'vsip_vmaxval_i(a,idx)', 'mview_si':'vsip_mmaxval_si(a,idx)', 'vview_si':'vsip_vmaxval_si(a,idx)'} t=getType(a)[1] assert t in f,'Type <:%s:> not supported by maxval.'%t return eval(f[t]) def min(a,b,c): f={'mview_d':vsip_mmin_d, 'mview_f':vsip_mmin_f, 'vview_d':vsip_vmin_d, 'vview_f':vsip_vmin_f} t=getType(a)[1] assert t in f,'Type <:%s:> not supported by min.'%t f[t](a,b,c) return c def minmg(a,b,c): f={'mview_d':vsip_mminmg_d, 'mview_f':vsip_mminmg_f, 'vview_d':vsip_vminmg_d, 'vview_f':vsip_vminmg_f} t=getType(a)[1] assert t in f,'Type <:%s:> not supported by minmg.'%t f[t](a,b,c) return c def minmgsq(a,b,c): f={'cmview_d':vsip_mcminmgsq_d, 'cmview_f':vsip_mcminmgsq_f, 'cvview_d':vsip_vcminmgsq_d, 'cvview_f':vsip_vcminmgsq_f} t=getType(a)[1] assert t in f,'Type <:%s:> not supported by minmgsq.'%t f[t](a,b,c) return c def minmgval(a,idx): f={'mview_dscalar_mi':'vsip_mminmgval_d(a,idx)', 'vview_dscalar_vi':'vsip_vminmgval_d(a,idx)', 'mview_fscalar_mi':'vsip_mminmgval_f(a,idx)', 'vview_fscalar_vi':'vsip_vminmgval_f(a,idx)'} t=getType(a)[1]+getType(idx)[1] assert t in f,'Type <:%s:> not supported by minmgval.'%t return eval(f[t]) def minval(a,idx): f={'mview_d':'vsip_mminval_d(a,idx)', 'vview_d':'vsip_vminval_d(a,idx)', 'mview_f':'vsip_mminval_f(a,idx)', 'vview_f':'vsip_vminval_f(a,idx)'} t=getType(a)[1] assert t in f,'Type <:%s:> not supported by minval.'%t return eval(f[t]) # Bitwise and Boolean def andd(a,b,c): """ renamed 'andd' to avoid collision with python keyword """ f={'mview_i':'vsip_mand_i(a,b,c)', 'mview_si':'vsip_mand_si(a,b,c)', 'vview_bl':'vsip_vand_bl(a,b,c)', 'vview_i':'vsip_vand_i(a,b,c)', 'vview_si':'vsip_vand_si(a,b,c)', 'vview_uc':'vsip_vand_uc(a,b,c)' } t=getType(a)[1] assert t in f,'Type <:%s:> not supported by and.'%t eval(f[t]) return c def nott(a,b): """ renamed 'nott' to avoid collision with python keyword """ f={'vview_bl':'vsip_vnot_bl(a,b)', 'vview_i':'vsip_vnot_i(a,b)', 'vview_si':'vsip_vnot_si(a,b)', 'vview_uc':'vsip_vnot_uc(a,b)'} t=getType(a)[1] assert t in f,'Type <:%s:> not supported by not.'%t eval(f[t]) return b def orr(a,b,c): """ renamed 'orr' to avoid collision with python keyword. """ f={'vview_bl':'vsip_vor_bl(a,b,c)', 'vview_i':'vsip_vor_i(a,b,c)', 'vview_si':'vsip_vor_si(a,b,c)', 'vview_uc':'vsip_vor_uc(a,b,c)'} t=getType(a)[1] assert t in f,'Type <:%s:> not supported by or.'%t eval(f[t]) return c def xor(a,b,c): f={'vview_bl':'vsip_vxor_bl(a,b,c)', 'vview_i':'vsip_vxor_i(a,b,c)', 'vview_si':'vsip_vxor_si(a,b,c)', 'vview_uc':'vsip_vxor_uc(a,b,c)'} t=getType(a)[1] assert t in f,'Type <:%s:> not supported by xor.'%t eval(f[t]) return c # Manipulation def cmplx(r,i,c): f={'vview_d':'vsip_vcmplx_d(r,i,c)', 'vview_f':'vsip_vcmplx_f(r,i,c)'} t=getType(r)[1] assert t in f,'Type <:%s:> not supported by cmplx.'%t eval(f[t]) return c def gather(input,indx,output): f={'cmview_d':'vsip_cmgather_d(input,indx,output)', 'cmview_f':'vsip_cmgather_f(input,indx,output)', 'cvview_d':'vsip_cvgather_d(input,indx,output)', 'cvview_f':'vsip_cvgather_f(input,indx,output)', 'mview_d':'vsip_mgather_d(input,indx,output)', 'mview_f':'vsip_mgather_f(input,indx,output)', 'vview_d':'vsip_vgather_d(input,indx,output)', 'vview_f':'vsip_vgather_f(input,indx,output)', 'vview_i':'vsip_vgather_i(input,indx,output)', 'vview_si':'vsip_vgather_si(input,indx,output)', 'vview_uc':'vsip_vgather_uc(input,indx,output)', 'vview_mi':'vsip_vgather_mi(input,indx,output)', 'vview_vi':'vsip_vgather_vi(input,indx,output)'} t=getType(input)[1] assert t in f,'Type <:%s:> not supported by gather.'%t eval(f[t]) return output def scatter(input,output,indx): f={'cvview_d':'vsip_cmscatter_d(input,output,indx)', 'cvview_f':'vsip_cmscatter_f(input,output,indx)', 'cvview_d':'vsip_cvscatter_d(input,output,indx)', 'cvview_f':'vsip_cvscatter_f(input,output,indx)', 'vview_d':'vsip_mscatter_d(input,output,indx)', 'vview_f':'vsip_mscatter_f(input,output,indx)', 'vview_d':'vsip_vscatter_d(input,output,indx)', 'vview_f':'vsip_vscatter_f(input,output,indx)', 'vview_i':'vsip_vscatter_i(input,output,indx)', 'vview_si':'vsip_vscatter_si(input,output,indx)', 'vview_uc':'vsip_vscatter_uc(input,output,indx)'} t=getType(input)[1] assert t in f,'Type <:%s:> not supported by scatter.'%t eval(f[t]) return output def polar(input,r,phi): f={'cvview_d':'vsip_vpolar_d(input,r,phi)', 'cvview_f':'vsip_vpolar_f(input,r,phi)'} t=getType(input)[1] assert t in f,'Type <:%s:> not supported by polar.'%t eval(f[t]) return(r,phi) def rect(r,phi,ouput): f={'vview_d':'vsip_vrect_d(r,phi,output)', 'vview_f':'vsip_vrect_f(r,phi,output)'} t=getType(r)[1] assert t in f,'Type <:%s:> not supported by rect.'%t eval(f[t]) return output def real(c,r): f={'cvview_d':'vsip_vreal_d(c,r)', 'cvview_f':'vsip_vreal_f(c,r)'} t=getType(c)[1] assert t in f,'Type <:%s:> not supported by real.'%t eval(f[t]) return r def imag(c,i): f={'cvview_d':'vsip_vreal_d(c,i)', 'cvview_f':'vsip_vreal_f(c,i)'} t=getType(c)[1] assert t in f,'Type <:%s:> not supported by imag.'%t eval(f[t]) return i def swap(a,b): f={'cmview_d':vsip_cmswap_d, 'cmview_f':vsip_cmswap_f, 'cvview_d':vsip_cvswap_d, 'cvview_f':vsip_cvswap_f, 'mview_d':vsip_mswap_d, 'mview_f':vsip_mswap_f, 'vview_d':vsip_vswap_d, 'vview_f':vsip_vswap_f, 'vview_i':vsip_vswap_i, 'vview_si':vsip_vswap_si, 'vview_uc':vsip_vswap_uc} t=getType(a)[1] assert t in f,'Type <:%s:> not supported by swap.'%t f[t](a,b) return(a,b) # FFT Functions def fftCreate(t,arg): """ This function creates a VSIPL fft Object. It takes a type argument as a string, and a tuple argument that corresponds to the VSIPL function call argument list. The first argument for fftCreate corresponds to the supported types for fft call input and output views. For out-of-place this would be (for instance) 'cvview_dcvview_d' for ccfftop with double precision and 'vview_fcvview_f for 'rcfftop' for float precision. For in-place calls only the type of the input/output view is called for. 'if the views are matrix views then the multiple fft object is created. If the type FFT requested is not supported then a message is printed and False is returned' """ if type(arg) != tuple: print('second argument must be a tuple coresponding to VSIP fft create call') f={ 'cvview_d':'vsip_ccfftip_create_d(arg[0] , arg[1] , arg[2] , arg[3] , arg[4])', 'cvview_f':'vsip_ccfftip_create_f(arg[0] , arg[1] , arg[2] , arg[3] , arg[4])', 'cvview_dcvview_d':'vsip_ccfftop_create_d(arg[0] , arg[1] , arg[2] , arg[3] , arg[4])', 'cvview_fcvview_f':'vsip_ccfftop_create_f(arg[0] , arg[1] , arg[2] , arg[3] , arg[4])', 'vview_dcvview_d':'vsip_rcfftop_create_d(arg[0] , arg[1] , arg[2] , arg[3])', 'vview_fcvview_f':'vsip_rcfftop_create_f(arg[0] , arg[1] , arg[2] , arg[3])', 'cvview_dvview_d':'vsip_crfftop_create_d(arg[0] , arg[1] , arg[2] , arg[3])', 'cvview_dvview_f':'vsip_crfftop_create_f(arg[0] , arg[1] , arg[2] , arg[3])', 'cmview_d':'vsip_ccfftmip_create_d(arg[0] , arg[1] , arg[2] , arg[3] , arg[4] , arg[5] , arg[6])', 'cmview_f':'vsip_ccfftmip_create_f(arg[0] , arg[1] , arg[2] , arg[3] , arg[4] , arg[5] , arg[6])' , 'cmview_dcmview_d':'vsip_ccfftmop_create_d(arg[0] , arg[1] , arg[2] , arg[3] , arg[4] , arg[5] , arg[6])' , 'cmview_fcmview_f':'vsip_ccfftmop_create_f(arg[0] , arg[1] , arg[2] , arg[3] , arg[4] , arg[5] , arg[6])' , 'cmview_dmview_d':'vsip_crfftmop_create_d(arg[0] , arg[1] , arg[2] , arg[3] , arg[4] , arg[5]) ', 'cmview_fmview_f':'vsip_crfftmop_create_f(arg[0] , arg[1] , arg[2] , arg[3] , arg[4] , arg[5]) ', 'mview_dcmview_d':'vsip_rcfftmop_create_d,(arg[0] , arg[1] , arg[2] , arg[3] , arg[4] , arg[5])', 'mview_fcmview_f':'vsip_rcfftmop_create_f(arg[0] , arg[1] , arg[2] , arg[3] , arg[4] , arg[5])' } assert t in f,'Type <:%s:> not supported by FFT create.'%t return eval(f[t]) def fftip(fftobj,a): f={ 'cvview_d':vsip_ccfftip_d, 'cvview_f':vsip_ccfftip_f, 'cmview_d':vsip_ccfftmip_d, 'cmview_f':vsip_ccfftmip_f} t=getType(a)[1] assert t in f,'Type <:%s:> not supported by fftip.'%t return f[t](fftobj,a) def fftop(fftobj,a,b): f={ 'cvview_dcvview_d':vsip_ccfftop_d, 'cvview_fcvview_f':vsip_ccfftop_f, 'vview_dcvview_d':vsip_rcfftop_d, 'vview_fcvview_f':vsip_rcfftop_f, 'cvview_dvview_d':vsip_crfftop_d, 'cvview_fvview_f':vsip_crfftop_f, 'cmview_dcmview_d':vsip_ccfftmop_d, 'cmview_fcmview_f':vsip_ccfftmop_f, 'cmview_dmview_d':vsip_crfftmop_d, 'cmview_fmview_f':vsip_crfftmop_f, 'mview_dcmview_d':vsip_rcfftmop_d, 'mview_fcmview_f':vsip_rcfftmop_f} t=getType(a)[1]+getType(b)[1] assert t in f,'Type <:%s:> not supported by fftop.'%t return f[t](fftobj,a,b) def fftDestroy(fftobj): f={ 'fft_d':vsip_fft_destroy_d, 'fft_f':vsip_fft_destroy_f, 'fftm_d':vsip_fftm_destroy_d, 'fftm_f':vsip_fftm_destroy_f} t=getType(fftobj)[1] assert t in f,'Type <:%s:> not supported by fftDestroy.'%t return f[t](fftobj) #Fir Functions #TVCPP does not seem to handle the rcfir case. may need to fix that. #rcfir case breaks my key-value coding below. def firCreate(kernel,sym,length,decimation,state,ntimes,alghint): """ create a fir object. Call with same arguments as in VSIPL API document. """ f={ 'cvview_d':vsip_cfir_create_d, 'cvview_f':vsip_cfir_create_f, 'vview_d':vsip_fir_create_d, 'vview_f':vsip_fir_create_f} t=getType(kernel)[1] assert t in f,'Type <:%s:> not a supported kernel type for fir Create.'%t return f[t](kernel,sym,length,decimation,state,ntimes,alghint) def firDestroy(fir): f={ 'cfir_d':vsip_cfir_destroy_d, 'cfir_f':vsip_cfir_destroy_f, 'fir_d': vsip_fir_destroy_d, 'fir_f': vsip_fir_destroy_f} t=getType(fir)[1] assert t in f,'Type <:%s:> not supported by firDestroy.'%t f[t](fir) def firfilt(fir,input,output): f={ 'cfir_d': vsip_cfirflt_d, 'cfir_f': vsip_cfirflt_f, 'fir_d': vsip_firflt_d, 'fir_f': vsip_firflt_f} t=getType(fir)[1] assert t in f,'Type <:%s:> not supported by firfilt.'%t return f[t](fir,input,output) def firReset(fir): f={ 'cfir_d': vsip_cfir_reset_d, 'cfir_f': vsip_cfir_reset_f, 'fir_d': vsip_fir_reset_d, 'fir_f': vsip_fir_reset_f} t=getType(fir)[1] assert t in f,'Type <:%s:> not a fir object.'%t f[t](fir) return fir # Miscellaneous def histo(src,min_bin,max_bin,opt,hist): t=getType(src)[1] f={'mview_d': vsip_mhisto_d, 'mview_f': vsip_mhisto_f, 'mview_i': vsip_mhisto_i, 'mview_si': vsip_mhisto_si, 'vview_d':vsip_vhisto_d, 'vview_f':vsip_vhisto_f, 'vview_i': vsip_vhisto_i, 'vview_si': vsip_vhisto_si} assert t in f,'Type <:%s:> not supported by historgram'%t f[t](src,min_bin,max_bin,opt,hist) return hist def freqswap(x): """Swaps halves of a vector, or quadrants of a matrix, to remap zero frequencies from the origin to the middle. """ f = { 'cvview_d':vsip_cvfreqswap_d, 'vview_d':vsip_vfreqswap_d, 'cmview_d':vsip_cmfreqswap_d, 'mview_d':vsip_mfreqswap_d, 'cvveiw_f':vsip_cvfreqswap_f, 'vview_f':vsip_vfreqswap_f, 'cmview_f':vsip_cmfreqswap_f, 'mview_f':vsip_mfreqswap_f} t=getType(x)[1] assert t in f,'Type <:%s:> not supported for freqswap'%t f[t](x) return x # Matrix and Vector Operations def herm(a,b): f = { 'cmview_d':vsip_cmherm_d, 'cmview_f':vsip_cmherm_f} t = getType(a) assert t[0] and t == getType(b) and t[1] in f,'Not a supported argument list for cmherm' f[t[1]](a,b) return b def jdot(a,b): f = { 'cvview_f':vsip_cvjdot_f, 'cvview_d':vsip_cvjdot_d} t=getType(a) assert t[0] and t == getType(b) and t[1] in f,'Not a supported argument list for cvjdot' return f[t[1]](a,b) def gemp(alpha,A,opa,B,opB,beta,C): f = { 'mview_f':vsip_gemp_f, 'mview_d':vsip_gemp_d, 'cmview_d':vsip_cgemp_d, 'cmview_f':vsip_cgemp_f} t=getType(A) assert t == getType(B) and t == getType(C) and t[0] and t[1] in f,'Not a supported argument type for gemp' f[t[1]](alpha,A,opa,B,opb,beta,C) return C def gems(alpha,A,opa,beta,C): f = { 'mview_f':vsip_gems_f, 'mview_d':vsip_gems_d, 'cmview_d':vsip_cgems_d, 'cmview_f':vsip_cgems_f} t=getType(A) assert t == getType(C) and t[0] and t[1] in f,'Not a supported argument list for gems' f[t[1]](alpha,A,opa,beta,C) return C def kron(alpha,a,b,C): f={ 'cmview_dcmview_d':vsip_cmkron_d, 'cmview_fcmview_f':vsip_cmkron_f, 'cvview_dcmview_d':vsip_cvkron_d, 'cvview_fcmview_f':vsip_cvkron_f, 'mview_dmview_d':vsip_mkron_d, 'mview_fmview_f':vsip_mkron_f, 'vview_dmview_d':vsip_vkron_d, 'vview_fmview_f':vsip_vkron_f} t1=getType(a) t2=getType(C) t=str() if t1[0]: t=t1[1]+t2[1] assert t in f,'Type <:%s:> not a supported type for function kron.'%t f[t](alpha,a,b,C) return C def prod3(A,B,C): f = { 'mview_fmview_f':vsip_mprod3_f, 'mview_dmview_d':vsip_mprod3_d, 'cmview_dcmview_d':vsip_cmprod3_d, 'cmview_fcmview_f':vsip_cmprod3_f, 'mview_fvview_f':vsip_mvprod3_f, 'mview_dvview_d':vsip_mvprod3_d, 'cmview_fcvview_f':vsip_cmvprod3_f, 'cmview_dcvview_d':vsip_cmvprod3_d} t1=getType(A) t2=getType(B) t=str() if t1[0]: t=t1[1]+t2[1] assert t in f,'Type <:%s:> not a supported type for function prod3.'%t f[t](A,B,C) return C def prod4(A,B,C): f = { 'mview_fmview_f':vsip_mprod4_f, 'mview_dmview_d':vsip_mprod4_d, 'cmview_dcmview_d':vsip_cmprod4_d, 'cmview_fcmview_f':vsip_cmprod4_f, 'mview_fvview_f':vsip_mvprod4_f, 'mview_dvview_d':vsip_mvprod4_d, 'cmview_fcvview_f':vsip_cmvprod4_f, 'cmview_dcvview_d':vsip_cmvprod4_d} t1=getType(A) t2=getType(B) t=str() if t1[0]: t=t1[1]+t2[1] assert t in f,'Type <:%s:> not a supported type for function prod4.'%t f[t](A,B,C) return C def prod(A,B,C): f={ 'mview_dmview_d':vsip_mprod_d, 'mview_fmview_f':vsip_mprod_f, 'cmview_dcmview_d':vsip_cmprod_d, 'cmview_fcmview_f':vsip_cmprod_f, 'mview_dvview_d':vsip_mvprod_d, 'mview_fvview_f':vsip_mvprod_f, 'cmview_dcvview_d':vsip_cmvprod_d, 'cmview_fcvview_f':vsip_cmvprod_f, 'vview_dmview_d':vsip_vmprod_d, 'vview_fmview_f':vsip_vmprod_f, 'cvview_dcmview_d':vsip_cvmprod_d, 'cvview_fcmview_f':vsip_cvmprod_f} t1=getType(A) t2=getType(B) t=str() if t1[0]: t=t1[1]+t2[1] assert t in f,'Type <:%s:> not a supported type for function prod.'%t f[t](A,B,C) return C def prodh(A,B,C): f = {'cmview_d':vsip_cmprodh_d,'cmview_f':vsip_cmprodh_f} t=getType(A) assert t[0] and t==getType(B) and t==getType(C) and t[1] in f,'Not a supported argument type for prodh.' f[t[1]](A,B,C) return C def prodj(A,B,C): f = {'cmview_d':vsip_cmprodj_d,'cmview_f':vsip_cmprodj_f} t=getType(A) assert t[0] and t==getType(B) and t==getType(C) and t[1] in f,'Not a supported argument type for prodj' f[t[1]](A,B,C) return C def prodt(A,B,C): f = {'cmview_d':vsip_cmprodt_d,'cmview_f':vsip_cmprodt_f, 'mview_d':vsip_mprodt_d,'mview_f':vsip_mprodt_f} t=getType(A) assert t[0] and t==getType(B) and t==getType(C) and t[1] in f,'Not a supported argument type for prodt.' f[t[1]](A,B,C) return C def trans(A,C): f = {'cmview_d':vsip_cmtrans_d,'cmview_f':vsip_cmtrans_f, 'mview_d':vsip_mtrans_d, 'mview_f':vsip_mtrans_f} t=getType(A) assert t[0] and t==getType(C) and t[1] in f,'Not a supported argument type for trans.' f[t[1]](A,C) return C def outer(alpha,x,y,C): f = { 'scalarvview_f':vsip_vouter_f, 'scalarvview_d':vsip_vouter_d, 'cscalar_dcvview_d':vsip_cvouter_d, 'cscalar_fcvview_f':vsip_cvouter_f} t1=getType(alpha) t2=getType(x) t=str() if t2[0] and t1[0]: t=t1[1] + t2[1] assert t in f,'Not a supported argument list for outer product' f[t](alpha,x,y,C) return C def dot(a,b): """ The dot product can be done on vview_f, vview_d, cvview_f and cvview_d. It returns a scalar or cscalar of the appropriate type. s = dot(a,b) """ f = { 'vview_f':vsip_vdot_f, 'vview_d':vsip_vdot_d, 'cvview_f':vsip_cvdot_f, 'cvview_d':vsip_cvdot_d} t=getType(a) assert t[0] and t == getType(b) and t[1] in f,'Not a supported argument list for dot' return f[t[1]](a,b) # General Square System Solver (LU Decompositon) def lud_create(t,N): """ lu = lud_create(t,N) where t is a type N is the size types supported are 'lu_f', 'clu_f', 'lu_d', 'clu_d' """ f={'lu_f':vsip_lud_create_f, 'clu_f':vsip_clud_create_f, 'lu_d':vsip_lud_create_d, 'clu_d':vsip_clud_create_d} assert t in f,'Type <:%s:> not a supported type for function lud_create.'%t return f[t](N) def lud_destroy(lu): t=getType(lu)[1] f=f={'lu_f':vsip_lud_destroy_f, 'clu_f':vsip_clud_destroy_f, 'lu_d':vsip_lud_destroy_d, 'clu_d':vsip_clud_destroy_d} assert t in f,'Type <:%s:> not a supported type for function lud_destroy.'%t return f[t](lu) def lud(lu,A): f=f={'lu_fmview_f':vsip_lud_f, 'clu_fcmview_f':vsip_clud_f, 'lu_dmview_d':vsip_lud_d, 'clu_dcmview_d':vsip_clud_d} t=getType(lu)[1] + getType(A)[1] assert t in f,'Type <:%s:> not a supported type for function lud.'%t ret= f[t](lu,A) return (ret,lu) def lusol(lu,op,A): f=f={'lu_fmview_f':vsip_lusol_f, 'clu_fcmview_f':vsip_clusol_f, 'lu_dmview_d':vsip_lusol_d, 'clu_dcmview_d':vsip_clusol_d} t=getType(lu)[1] + getType(A)[1] assert t in f,'Type <:%s:> not a supported type for function lusol.'%t ret= f[t](lu,op,A) return (ret,A) # Symetric square system solver (Cholesky decomposition) def chold(ch,A): f={'chol_fmview_f':vsip_chold_f, 'cchol_fcmview_f':vsip_cchold_f, 'chol_dmview_d':vsip_chold_d, 'cchol_dcmview_d':vsip_cchold_d} t=getType(ch)[1]+getType(A)[1] assert t in f,'Type <:%s:> not a supported type for function chold.'%t ret= f[t](ch,A) return(ret,ch) def chold_create(t,op,N): f={'chol_f':vsip_chold_create_f, 'cchol_f':vsip_cchold_create_f, 'chol_d':vsip_chold_create_d, 'cchold_d':vsip_cchold_create_d} assert t in f,'Type <:%s:> not a supported type for function chold_create.'%t return f[t](op,N) def chold_destroy(ch): t=getType(ch)[1] f=f={'chol_f':vsip_chold_destroy_f, 'cchol_f':vsip_cchold_destroy_f, 'chol_d':vsip_chold_destroy_d, 'cchol_d':vsip_cchold_destroy_d} assert t in f,'Type <:%s:> not a supported type for function chold_destroy.'%t return f[t](ch) def cholsol(ch,XB): f={'chol_fmview_f':vsip_cholsol_f, 'cchol_fcmview_f':vsip_ccholsol_f, 'chol_dmview_d':vsip_cholsol_d, 'cchol_dcmview_d':vsip_ccholsol_d} t=getType(ch)[1]+getType(XB)[1] assert t in f,'Type <:%s:> not a supported type for function cholsol.'%t ret= f[t](ch,XB) return(ret,XB) # Over-determined Linear System Solver (QR Decomposition) def qrd(qr,A): f={'qr_fmview_f':vsip_qrd_f, 'cqr_fcmview_f':vsip_cqrd_f, 'qr_dmview_d':vsip_qrd_d, 'cqr_dcmview_d':vsip_cqrd_d} t=getType(qr)[1]+getType(A)[1] assert t in f,'Type <:%s:> not supported by qrd.'%t ret= f[t](qr,A) return(ret,qr) def qrd_create(t,M,N,op): f={'qr_f':vsip_qrd_create_f, 'cqr_f':vsip_cqrd_create_f, 'qr_d':vsip_qrd_create_d, 'cqr_d':vsip_cqrd_create_d} assert t in f,'Type <:%s:> not supported by qrd_create.'%t return f[t](M,N,op) def qrd_destroy(qr): t=getType(qr)[1] f=f={'qr_f':vsip_qrd_destroy_f, 'cqr_f':vsip_cqrd_destroy_f, 'qr_d':vsip_qrd_destroy_d, 'cqr_d':vsip_cqrd_destroy_d} assert t in f,'Type <:%s:> not supported by qrd_destroy.'%t return f[t](qr) def qrdprodq(qr,op,side,A): f={'qr_fmview_f':vsip_qrdprodq_f, 'cqr_fcmview_f':vsip_cqrdprodq_f, 'qr_dmview_d':vsip_qrdprodq_d, 'cqr_dcmview_d':vsip_cqrdprodq_d} t=getType(qr)[1] + getType(A)[1] assert t in f,'Type <:%s:> not supported by qrdprodq.'%t ret=f[t](qr,op,side,A) return(ret,A) def qrdsolr(qr,op,scl,XB): f={'qr_fmview_f':vsip_qrdsolr_f, 'cqr_fcmview_f':vsip_cqrdsolr_f, 'qr_dmview_d':vsip_qrdsolr_d, 'cqr_dcmview_d':vsip_cqrdsolr_d} t=getType(qr)[1] + getType(XB)[1] assert t in f,'Type <:%s:> not supported by qrdsolr.'%t ret=f[t](qr,op,scl,XB) return(ret,XB) def qrsol(qr,op,XB): f={'qr_fmview_f':vsip_qrsol_f, 'cqr_fcmview_f':vsip_cqrsol_f, 'qr_dmview_d':vsip_qrsol_d, 'cqr_dcmview_d':vsip_cqrsol_d} t=getType(qr)[1] + getType(XB)[1] assert t in f,'Type <:%s:> not supported by qrsol.'%t ret=f[t](qr,op,XB) return(ret,XB) # Singular Value Decomposition def svd_create(t,M,N,Usave,Vsave): f={'sv_f':vsip_svd_create_f, 'sv_d':vsip_svd_create_d, 'csv_f':vsip_csvd_create_f, 'csv_d':vsip_csvd_create_f} assert t in f,'Type <:%s:> not supported by svd_create.'%t return f[t](M,N,Usave,Vsave) def svd_destroy(sv): f={'sv_f':vsip_svd_destroy_f, 'sv_d':vsip_svd_destroy_d, 'csv_f':vsip_csvd_destroy_f, 'csv_d':vsip_csvd_destroy_d} t=getType(sv) assert t in f,'Type <:%s:> not supported by svd_destroy'%t return f[t](sv) def svd(sv,A,s): f={'sv_f':vsip_svd_f, 'sv_d':vsip_svd_d, 'csv_f':vsip_csvd_f, 'csv_d':vsip_csvd_f} t=getType(sv) assert t in f,'Type <:%s:> not supported by svd.'%t ret= f[t](sv,A,s) return (ret,A,s) def svdmatu(sv,low,high,C): f={'sv_f':vsip_svdmatu_f, 'sv_d':vsip_svdmatu_d, 'csv_f':vsip_csvdmatu_f, 'csv_d':vsip_cvsdmatu_d} t=getType(sv) assert t in f,'Type <:%s:> not supported by svdmatu.'%t ret= f[t](sv,low,high,C) return (ret,C) def svdmatv(svd,low,high,C): f={'sv_f':vsip_svdmatv_f, 'sv_d':vsip_svdmatv_d, 'csv_f':vsip_csvdmatv_f, 'csv_d':vsip_cvsdmatv_d} t=getType(sv) assert t in f,'Type <:%s:> not supported by svdmatv'%t ret= f[t](sv,low,high,C) return (ret,C) <file_sep>/* Created RJudd */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cchol_f.h,v 2.2 2006/04/09 20:58:37 judd Exp $ */ #include"VU_cmprintm_f.include" static void cchol_f(void){ printf("********\nTEST cchol_f\n"); { vsip_index i,j; vsip_cblock_f *ablock = vsip_cblockcreate_f(200,VSIP_MEM_NONE); vsip_cmview_f *R = vsip_cmcreate_f(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *RH = vsip_cmcreate_f(4,4,VSIP_ROW,VSIP_MEM_NONE); /* vsip_cmview_f *A = vsip_cmcreate_f(4,4,VSIP_ROW,VSIP_MEM_NONE); */ vsip_cmview_f *A = vsip_cmbind_f(ablock,40,-9,4,-2,4); /* vsip_cmview_f *B = vsip_cmcreate_f(4,3,VSIP_COL,VSIP_MEM_NONE); */ vsip_cmview_f *B = vsip_cmbind_f(ablock,100,10,4,3,3); vsip_cchol_f *chol = vsip_cchold_create_f(VSIP_TR_UPP,4); vsip_cmview_f *ans = vsip_cmcreate_f(4,3,VSIP_ROW,VSIP_MEM_NONE); vsip_scalar_f chk; vsip_scalar_f data_R[4][4] = { {1.0, -2.0, 3.0, 1.0}, {0.0, 2.0, 4.0, -1.0}, {0.0, 0.0, 4.0, 3.0}, {0.0, 0.0, 0.0, 6.0} }; vsip_scalar_f data_I[4][4] = { { 0.0, 2.0, 2.0, 1.0}, { 0.0, 0.0, 2.0, -4.0}, { 0.0, 0.0, 0.0, 2.0}, { 0.0, 0.0, 0.0, 0.0} }; vsip_scalar_f data_Br[4][3] = { {1.0, 2.0, 3.0}, {0.0, 1.0, 2.0}, {3.0, 0.0, 1.0}, {3.0, 4.0, 5.0}}; vsip_scalar_f data_Bi[4][3] = { {1.0, 0.5, 3.2}, {2.0, 0.0, 0.6}, {0.6, 2.0, 0.0}, {5.0, 7.0, 8.0}}; vsip_scalar_f data_ans_r[4][3] = { {13.6236, 27.5451, 43.1573}, {-0.1104, 5.2370, 3.3312}, {-0.8403, -1.9410, -2.9823}, { 0.7000, 0.8125, 1.7375} }; vsip_scalar_f data_ans_i[4][3] = { {19.4965, 5.3707, 40.9604}, { 6.7292, 5.4896, 15.8781}, {-1.4021, -0.3776, -2.9688}, { 0.3694, -0.1632, 0.4667} }; for(i=0; i<4; i++) for(j=0; j<4; j++) vsip_cmput_f(R,i,j,vsip_cmplx_f(data_R[i][j],data_I[i][j])); for(i=0; i<4; i++){ for(j=0; j<3; j++){ vsip_cmput_f(B,i,j,vsip_cmplx_f(data_Br[i][j],data_Bi[i][j])); vsip_cmput_f(ans,i,j,vsip_cmplx_f(data_ans_r[i][j],data_ans_i[i][j])); } } vsip_cmherm_f(R,RH); vsip_cmprod_f(RH,R,A); printf("R = \n");VU_cmprintm_f("4.2",R); printf("RH = \n");VU_cmprintm_f("4.2",RH); printf("A = R * RH\n");VU_cmprintm_f("4.2",A); printf("B \n");VU_cmprintm_f("4.2",B); vsip_cchold_f(chol,A); vsip_ccholsol_f(chol,B); printf("Solve using cholesky AX = B\n X = \n");VU_cmprintm_f("4.2",B); vsip_cchold_destroy_f(chol); printf("right answer \n ans = \n");VU_cmprintm_f("4.2",ans); vsip_cmsub_f(ans,B,B); chk = vsip_cmmeansqval_f(B); if(chk > .001) printf("error\n"); else printf("correct\n"); { vsip_clu_f *lu = vsip_clud_create_f(4); vsip_cmview_f *Bans = vsip_cmcreate_f(4,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cmprod_f(RH,R,A); for(i=0; i<4; i++) for(j=0; j<3; j++) vsip_cmput_f(B,i,j,vsip_cmplx_f(data_Br[i][j],data_Bi[i][j])); vsip_clud_f(lu,A); vsip_clusol_f(lu,VSIP_MAT_NTRANS,B); printf("Solve using LUD AX = B\n X = \n");VU_cmprintm_f("4.2",B); vsip_clud_destroy_f(lu); vsip_cmprod_f(RH,R,A); vsip_cmprod_f(A,B,Bans); printf("Bans = A X \n");VU_cmprintm_f("4.2",Bans); vsip_cmsub_f(ans,B,B); chk = vsip_cmmeansqval_f(B); if(chk > .001) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(Bans); } vsip_cmalldestroy_f(R); vsip_cmalldestroy_f(RH); vsip_cmdestroy_f(B); vsip_cmalldestroy_f(A); } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: tsubview_i.h,v 2.0 2003/02/22 15:23:35 judd Exp $ */ static void tsubview_i(void){ printf("********\nTEST tsubview_i\n"); { vsip_scalar_i data[4][5][4] = {{{ 0, 1, 2, 3}, { 10, 11, 12, 13}, { 20, 21, 22, 23}, {30, 31, 32, 33}, { 40, 41, 42, 43}}, {{100, 101 ,102 ,103}, { 110, 111 ,112 ,113}, {120, 121 ,122 ,123}, {130, 131 ,132 ,133}, {140, 141, 142, 143}}, {{200, 201 ,202 ,203}, { 210, 211 ,212 ,213}, {220, 221 ,222 ,223}, {230, 231 ,232 ,233}, {240, 241, 242, 243}}, {{300, 301 ,302 ,303}, { 310, 311 ,312 ,313}, {320, 321 ,322 ,323}, {330, 331 ,332 ,333}, {340, 341, 342, 343}}}; vsip_offset o = 7; vsip_stride zs = 1, ys = 8, xs = 42; vsip_length zl = 4, yl = 5, xl = 4; vsip_block_i *b = vsip_blockcreate_i(200,VSIP_MEM_NONE); vsip_tview_i *v = vsip_tbind_i(b,o,zs,zl,ys,yl,xs,xl); vsip_index szi = 2, syi = 1, sxi = 0; vsip_length szl = 2, syl = 3, sxl = 3; vsip_tview_i *sv = vsip_tsubview_i(v,szi,syi,sxi,szl,syl,sxl); vsip_scalar_i chk = 0; int i,j,k; for(i=0; i< (int)zl; i++) for(j=0; j< (int)yl; j++) for(k=0; k< (int)xl; k++) vsip_tput_i(v,i,j,k,data[i][j][k]); for(i=0; i< (int)szl; i++) for(j=0; j< (int)syl; j++) for(k=0; k< (int)sxl; k++) chk += abs(vsip_tget_i(sv,i,j,k) - data[szi+i][syi+j][sxi+k]); (chk > .0001) ? printf("error \n") : printf("correct \n"); fflush(stdout); vsip_tdestroy_i(sv); vsip_talldestroy_i(v); } return; } <file_sep>import Foundation public func setRGB(ptr: inout [UInt8], val: Double) { var v = Int(val * 767) if (v < 0) { v = 0 } else if (v > 767){ v = 767 } let offset: Int = v % 256 if (v<256) { ptr[0] = 0; ptr[1] = 0; ptr[2] = UInt8(offset) } else if (v<512) { ptr[0] = 0; ptr[1] = UInt8(offset); ptr[2] = 255 - UInt8(offset) } else { ptr[0] = UInt8(offset); ptr[1] = 255 - UInt8(offset); ptr[2] = 0 } ptr[3] = 255 } <file_sep>/* Created RJudd September 16, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_blockbind_mi.c,v 2.2 2009/05/20 17:11:15 judd Exp $ */ #include"vsip.h" #include"vsip_blockattributes_mi.h" vsip_block_mi* (vsip_blockbind_mi)( vsip_scalar_vi* const p, vsip_length N, vsip_memory_hint h) { vsip_block_mi* b = (vsip_block_mi*)malloc(sizeof(vsip_block_mi)); { if(b != (vsip_block_mi*)NULL){ b->kind = VSIP_USER_BLOCK; b->admit = VSIP_RELEASED_BLOCK; b->markings = VSIP_VALID_STRUCTURE_OBJECT; b->array = p; /* user data array */ b->size = N; /* size in block elements */ b->bindings = 0; b->hint = h; } } return b; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: lud_f.h,v 2.0 2003/02/22 15:23:14 judd Exp $ */ #include"VU_mprintm_f.include" static void lud_f(void){ printf("********\nTEST lud_f\n"); { vsip_index i,j; /* make up some data space and views */ vsip_block_f *block = vsip_blockcreate_f(500,VSIP_MEM_NONE); vsip_mview_f *AC = vsip_mbind_f(block,0,6,6,1,6); vsip_mview_f *AG = vsip_mbind_f(block,36,2,6,18,6); vsip_mview_f *IC = vsip_mbind_f(block,150,1,6,6,6); vsip_mview_f *IG = vsip_mbind_f(block,200,2,6,14,6); vsip_mview_f *B = vsip_mbind_f(block,300,6,6,1,6); vsip_mview_f *A = vsip_mbind_f(block,350,6,6,1,6); vsip_mview_f *X = vsip_mbind_f(block,400,5,6,1,3); vsip_mview_f *Y = vsip_mbind_f(block,450,3,6,1,3); vsip_lu_f* ludC = vsip_lud_create_f(6); vsip_lu_f* ludG = vsip_lud_create_f(6); vsip_mview_f *AT = vsip_mtransview_f(A); vsip_scalar_f chk; vsip_scalar_f data[6][6] = { {0.50, 7.00, 10.00, 12.00, -3.00, 0.00}, {2.00, 13.00, 18.00, 6.00, 0.00, 130.00}, {3.00, -9.00, 2.00, 3.00, 2.00, -9.00}, {4.00, 2.00, 2.00, 4.00, 1.00, 2.00}, {0.20, 2.00, 9.00, 4.00, 1.00, 2.00}, {0.10, 2.00, 0.30, 4.00, 1.00, 2.00}}; vsip_scalar_f ydata[6][3] = {{ 77.85, 155.70, 311.40}, { 942.00, 1884.00, 3768.00}, { 1.00, 2.00, 4.00}, { 68.00, 136.00, 272.00}, { 85.20, 170.40, 340.80}, { 59.00, 118.00, 236.00}}; vsip_scalar_f Ident[6][6] = {{1, 0, 0, 0, 0, 0}, {0, 1, 0, 0, 0, 0}, {0, 0, 1, 0, 0, 0}, {0, 0, 0, 1, 0, 0}, {0, 0, 0, 0, 1, 0}, {0, 0, 0, 0, 0, 1}}; for(i=0; i<6; i++){ for(j=0; j<6; j++){ vsip_mput_f(A, i,j,data[i][j]); vsip_mput_f(AC,i,j,data[i][j]); vsip_mput_f(AG,i,j,data[i][j]); vsip_mput_f(IC,i,j,Ident[i][j]); vsip_mput_f(IG,i,j,Ident[i][j]); } } for(i=0; i<6; i++) for(j=0; j<3; j++) vsip_mput_f(X,i,j,ydata[i][j]); printf("Matrix A = \n");VU_mprintm_f("7.2",A);fflush(stdout); vsip_lud_f(ludC,AC); vsip_lud_f(ludG,AG); printf("vsip_lusol(lud,VSIP_MAT_NTRANS,X)\n"); printf("Solve A X = I \n"); fflush(stdout); vsip_lusol_f(ludC,VSIP_MAT_NTRANS,IC); vsip_lusol_f(ludG,VSIP_MAT_NTRANS,IG); printf("for compact case X = \n");VU_mprintm_f("8.4",IC); fflush(stdout); printf("for general case X = \n");VU_mprintm_f("8.4",IG); fflush(stdout); chk = 0; for(i=0; i<6; i++) for(j=0; j<6; j++) chk += fabs(vsip_mget_f(IC,i,j) - vsip_mget_f(IG,i,j)); (chk > .01) ? printf("error\n") : printf("agree\n"); fflush(stdout); vsip_mprod_f(A,IC,B); chk = 0; for(i=0; i<6; i++) for(j=0; j<6; j++) chk += fabs(vsip_mget_f(B,i,j) - Ident[i][j]); vsip_mprod_f(A,IG,B); for(i=0; i<6; i++) for(j=0; j<6; j++) chk += fabs(vsip_mget_f(B,i,j) - Ident[i][j]); printf("mprod(A,X) = \n"); VU_mprintm_f("8.3",B); fflush(stdout); (chk > .01) ? printf("error\n") : printf("correct\n"); fflush(stdout); /************************************************/ /* check case VSIP_MAT_TRANS */ printf("Matrix Transpose A = \n");VU_mprintm_f("7.2",AT);fflush(stdout); for(i=0; i<6; i++){ for(j=0; j<6; j++){ vsip_mput_f(IC,i,j,Ident[i][j]); vsip_mput_f(IG,i,j,Ident[i][j]); } } printf("vsip_lusol(lud,VSIP_MAT_TRANS,X)\n"); printf("Solve trans(A) X = I \n"); fflush(stdout); vsip_lusol_f(ludC,VSIP_MAT_TRANS,IC); vsip_lusol_f(ludG,VSIP_MAT_TRANS,IG); printf("for compact case X = \n");VU_mprintm_f("8.4",IC); fflush(stdout); printf("for general case X = \n");VU_mprintm_f("8.4",IG); fflush(stdout); chk = 0; for(i=0; i<6; i++) for(j=0; j<6; j++) chk += fabs(vsip_mget_f(IC,i,j) - vsip_mget_f(IG,i,j)); (chk > .01) ? printf("error\n") : printf("agree\n"); fflush(stdout); vsip_mprod_f(AT,IC,B); chk = 0; for(i=0; i<6; i++) for(j=0; j<6; j++) chk += fabs(vsip_mget_f(B,i,j) - Ident[i][j]); vsip_mprod_f(AT,IG,B); for(i=0; i<6; i++) for(j=0; j<6; j++) chk += fabs(vsip_mget_f(B,i,j) - Ident[i][j]); printf("mprod(trans(A),X) = \n"); VU_mprintm_f("8.3",B); fflush(stdout); (chk > .01) ? printf("error\n") : printf("correct\n"); fflush(stdout); /************************************************/ /* check case A X = B for VSIP_MAT_NTRANS */ printf("check A X = Y; VSIP_MAT_NTRANS\n"); printf("Y = \n");VU_mprintm_f("8.4",X); vsip_lusol_f(ludC,VSIP_MAT_NTRANS,X); printf("X = \n"); VU_mprintm_f("8.4",X); vsip_mprod_f(A,X,Y); printf(" Y = A X\n");VU_mprintm_f("8.4",Y); chk = 0; for(i=0; i<6; i++) for(j=0; j<3; j++) chk += fabs(vsip_mget_f(Y,i,j) - ydata[i][j]); (chk > .01) ? printf("error\n") : printf("agree\n"); fflush(stdout); /************************************************/ /* check case trans(A) X = B for VSIP_MAT_TRANS */ for(i=0; i<6; i++) for(j=0; j<3; j++) vsip_mput_f(X,i,j,ydata[i][j]); printf("Y = \n");VU_mprintm_f("8.4",X); vsip_lusol_f(ludG,VSIP_MAT_TRANS,X); vsip_mprod_f(AT,X,Y); printf("X = \n");VU_mprintm_f("8.4",X); printf("Y = trans(A) X\n");VU_mprintm_f("8.4",Y); chk = 0; for(i=0; i<6; i++) for(j=0; j<3; j++) chk += fabs(vsip_mget_f(Y,i,j) - ydata[i][j]); (chk > .01) ? printf("error\n") : printf("agree\n"); fflush(stdout); /***************************************************/ /* destroy stuff */ vsip_mdestroy_f(AC); vsip_mdestroy_f(AG); vsip_mdestroy_f(IC); vsip_mdestroy_f(IG); vsip_mdestroy_f(B); vsip_mdestroy_f(A); vsip_mdestroy_f(X); vsip_mdestroy_f(Y); vsip_malldestroy_f(AT); vsip_lud_destroy_f(ludC); vsip_lud_destroy_f(ludG); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: tmisc_view_i.h,v 2.1 2009/09/05 18:01:45 judd Exp $ */ static void tmisc_view_i(void){ printf("********\nTEST tmisc_view_i\n"); { vsip_index k,j,i; vsip_scalar_i data_r[4][3][4] = {{{0, 001, 002, 003}, \ {01, 011, 012, 013}, \ {02, 021, 022, 023}}, \ {{10, 101, 102, 103}, \ {11, 111, 112, 113}, \ {12, 121, 122, 123}}, \ {{20, 201, 202, 203}, \ {21, 211, 212, 213}, \ {22, 221, 222, 223}}, \ {{30, 301, 302, 303}, \ {31, 311, 312, 313}, \ {32, 321, 322, 323}}}; /* if a problem with tcreate is suspected check both leading and trailing options here */ vsip_tview_i *tview_a = vsip_tcreate_i(12,9,12,VSIP_LEADING,VSIP_MEM_NONE); /* vsip_tview_i *tview_a = vsip_tcreate_i(12,9,12,VSIP_TRAILING,VSIP_MEM_NONE); */ vsip_block_i *block_a = vsip_tgetblock_i(tview_a); vsip_tview_i *tview_b = vsip_tsubview_i(tview_a,1,2,3,4,3,4); vsip_stride z_a_st = vsip_tgetzstride_i(tview_a); vsip_stride y_a_st = vsip_tgetystride_i(tview_a); vsip_stride x_a_st = vsip_tgetxstride_i(tview_a); vsip_offset b_o_calc = z_a_st + 2 * y_a_st + 3 * x_a_st; vsip_offset b_o_get = vsip_tgetoffset_i(tview_b); vsip_tview_i *v = vsip_tbind_i(block_a,b_o_calc, z_a_st,4, y_a_st,3, x_a_st,4); vsip_mview_i *mview = (vsip_mview_i*)NULL; vsip_vview_i *vview = (vsip_vview_i*)NULL; vsip_tview_i *tview = (vsip_tview_i*)NULL; vsip_scalar_i a; int chk = 0; printf("z_a_st %d; y_a_st %d; x_a_st %d\n",(int)z_a_st,(int)y_a_st,(int)x_a_st); fflush(stdout); printf("b_o_calc %u; b_o_get %u\n",(unsigned)b_o_calc,(unsigned)b_o_get); fflush(stdout); for(k = 0; k < 4; k++){ for(j = 0; j < 3; j++){ for(i = 0; i < 4; i++){ a = data_r[k][j][i]; vsip_tput_i(v,k,j,i,a); } } } printf("test tmatrixview_i\n"); printf("TMZY\n"); fflush(stdout); for(i = 0; i < 4; i++){ mview = vsip_tmatrixview_i(v,VSIP_TMZY,i); for(j = 0; j < 3; j++){ for(k = 0; k < 4; k++){ a = vsip_mget_i(mview,k,j); a -= data_r[k][j][i]; chk += a * a; } } vsip_mdestroy_i(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TMYX\n"); fflush(stdout); for(k = 0; k < 4; k++){ mview = vsip_tmatrixview_i(v,VSIP_TMYX,k); for(j = 0; j < 3; j++){ for(i = 0; i < 4; i++){ a = vsip_mget_i(mview,j,i); a -= data_r[k][j][i]; chk += a * a; } } vsip_mdestroy_i(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TMZX\n"); fflush(stdout); for(j = 0; j < 3; j++){ mview = vsip_tmatrixview_i(v,VSIP_TMZX,j); for(k = 0; k < 4; k++){ for(i = 0; i < 4; i++){ a = vsip_mget_i(mview,k,i); a -= data_r[k][j][i]; chk += a * a; } } vsip_mdestroy_i(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test tvectview_i\n"); printf("TVX \n"); fflush(stdout); for(k=0; k<4; k++){ for(j=0; j<3; j++){ vview = vsip_tvectview_i(v,VSIP_TVX,k,j); for(i=0; i<4; i++){ a = vsip_vget_i(vview,i); a -= data_r[k][j][i]; chk += a * a; } } vsip_vdestroy_i(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test tvectview_i\n"); printf("TVY \n"); fflush(stdout); for(k=0; k<4; k++){ for(i=0; i<4; i++){ vview = vsip_tvectview_i(v,VSIP_TVY,k,i); for(j=0; j<3; j++){ a = vsip_vget_i(vview,j); a -= data_r[k][j][i]; chk += a * a ; } } vsip_vdestroy_i(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TVZ \n"); fflush(stdout); for(j=0; j<3; j++){ for(i=0; i<4; i++){ vview = vsip_tvectview_i(v,VSIP_TVZ,j,i); for(k=0; k<4; k++){ a = vsip_vget_i(vview,k); a -= data_r[k][j][i]; chk += a * a; } } vsip_vdestroy_i(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test ttransview_i\n"); fflush(stdout); printf("NOP\n"); fflush(stdout); tview = vsip_ttransview_i(v,VSIP_TTRANS_NOP); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_i(tview,k,j,i); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_i(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YX\n"); fflush(stdout); tview = vsip_ttransview_i(v,VSIP_TTRANS_YX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_i(tview,k,i,j); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_i(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("ZY\n"); fflush(stdout); tview = vsip_ttransview_i(v,VSIP_TTRANS_ZY); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_i(tview,j,k,i); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_i(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("ZX\n"); fflush(stdout); tview = vsip_ttransview_i(v,VSIP_TTRANS_ZX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_i(tview,i,j,k); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_i(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YXZY\n"); fflush(stdout); tview = vsip_ttransview_i(v,VSIP_TTRANS_YXZY); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_i(tview,i,k,j); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_i(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YXZX\n"); fflush(stdout); tview = vsip_ttransview_i(v,VSIP_TTRANS_YXZX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_i(tview,j,i,k); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_i(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; vsip_tdestroy_i(v); vsip_tdestroy_i(tview_b); vsip_talldestroy_i(tview_a); } return; } <file_sep>#!/usr/bin/env python # Designed to work for JVSIP with libraries in the standard locations as built with the # makefile in the JVSIP home directory. Extension parmaeters listing should be self # explanatory for library and include directory expected locations. # to build use from the command line # python setup.py build_ext # to build and install use from the command line # python setup.py build_ext install # Note # To use another vsip implementation you need to edit vsip.i to include the proper vsip.h # and to list the functionality available (or desired) with the other implementation. # Edit Extension and setup calls as needed """ Python setup file for distutils. Creates JVSIP vsip module. Requirements: C Compiler Python installation and distribution utilities module SWIG program installed (www.swig.org) Need to have built the JVSIP vsip library (libvsip.a) """ from distutils.core import setup, Extension vsip_module = Extension('_vsip', sources=['vsip.i', './c_src/copyToList.c', './c_src/indexptr.c', './c_src/py_jdot.c', './c_src/vsipScalarFunctions.c', './c_src/jvsip_mprod.c'], include_dirs=['../../c_VSIP_src','./c_src'], library_dirs=['../../lib'], libraries=['vsip'] ) setup (name = 'vsip', version = '0.6', author = "<NAME>", description = """VSIP Extension Module""", ext_modules = [vsip_module], py_modules=['vsip'], ) <file_sep>import pyJvsip as pjv from math import pi as pi L=50 # A length aBlock = pjv.Block('block_d',L) a=aBlock.bind(0,1,L).fill(0.0) b=a.empty.ramp(0.0,2.0*pi/float(L-1)).cos ab_bl = b.lgt(a) assert ab_bl.anytrue,'No true values in boolean vector.' ab_vi=ab_bl.indexbool pjv.gather(b,ab_vi,a.putlength(ab_vi.length)) b.fill(0.0) pjv.scatter(a,b,ab_vi) for i in range(L): print('%.3f'%b[i]) <file_sep>/********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: example18.c,v 1.1 2003/04/22 02:17:53 judd Exp $ */ #include<vsip.h> #define ripple 100 #define Nlength 101 int main(){vsip_init((void*)0); { void VU_vfprintyg_d(char*,vsip_vview_d*,char*); void VU_vfreqswapIP_d(vsip_vview_d*); vsip_vview_d* Cw = vsip_vcreate_cheby_d(Nlength,ripple,0); vsip_fft_d *fft = vsip_ccfftip_create_d(Nlength,1.0,VSIP_FFT_FWD,0,0); vsip_cvview_d* FCW = vsip_cvcreate_d(Nlength,0); /*printf("CW = "); VU_vprintm_d("%6.8f ;\n",Cw); */ VU_vfprintyg_d("%6.8f\n",Cw,"Cheby_Window"); vsip_cvfill_d(vsip_cmplx_d(0,0),FCW); { vsip_vview_d *rv = vsip_vrealview_d(FCW); vsip_vcopy_d_d(Cw,rv); vsip_ccfftip_d(fft,FCW); vsip_vcmagsq_d(FCW,rv); { vsip_index ind; vsip_scalar_d max = vsip_vmaxval_d(rv,&ind); vsip_scalar_d min = max/(10e12); vsip_vclip_d(rv,min,max,min,max,rv); } vsip_vlog10_d(rv,rv); vsip_svmul_d(10,rv,rv); VU_vfreqswapIP_d(rv); VU_vfprintyg_d("%6.8f\n",rv,"Cheby_Window_Frequency_Response"); vsip_vdestroy_d(rv); } vsip_fft_destroy_d(fft); vsip_valldestroy_d(Cw); vsip_cvalldestroy_d(FCW); } vsip_finalize((void*)0); return 0; } void VU_vfreqswapIP_d(vsip_vview_d* b) { vsip_length N = vsip_vgetlength_d(b); if(N%2){/* odd */ vsip_vview_d *a1 = vsip_vsubview_d(b, (vsip_index)(N/2)+1, (vsip_length)(N/2)); vsip_vview_d *a2 = vsip_vsubview_d(b, (vsip_index)0, (vsip_length)(N/2)+1); vsip_vview_d *a3 = vsip_vcreate_d((vsip_length)(N/2)+1, VSIP_MEM_NONE); vsip_vcopy_d_d(a2,a3); vsip_vputlength_d(a2,(vsip_length)(N/2)); vsip_vcopy_d_d(a1,a2); vsip_vputlength_d(a2,(vsip_length)(N/2) + 1); vsip_vputoffset_d(a2,(vsip_offset)(N/2)); vsip_vcopy_d_d(a3,a2); vsip_vdestroy_d(a1); vsip_vdestroy_d(a2); vsip_valldestroy_d(a3); }else{ /* even */ vsip_vview_d *a1 = vsip_vsubview_d(b, (vsip_index)(N/2), (vsip_length)(N/2)); vsip_vputlength_d(b,(vsip_length)(N/2)); vsip_vswap_d(b,a1); vsip_vdestroy_d(a1); vsip_vputlength_d(b,N); } return; } void VU_vfprintyg_d(char* format, vsip_vview_d* a,char* fname) { vsip_length N = vsip_vgetlength_d(a); vsip_length i; FILE *of = fopen(fname,"w"); for(i=0; i<N; i++) fprintf(of,format, vsip_vget_d(a,i)); fclose(of); return; } <file_sep>""" Example of debugging c file using vsip module. Code was developed in pyJvsip. When working it was converted to c. To aid in debugging C code was converted back to python using just the vsip module. Counterpart file of svd_f.c (and svd_f.h) Note: In C we have typedef struct { } newType; Here we have instead classes defined. See svdCorner, givensObj_f and svdObj_f for examples. """ from vsip import * def msv_f(B, BS, i,j): attr = vsip_mattr_f() vsip_mgetattrib_f(B,attr) attr.row_length -= j attr.col_length -= i attr.offset += j * attr.row_stride + i * attr.col_stride vsip_mputattrib_f(BS,attr) return BS def vsv_f( v, vs, i): attr = vsip_vattr_f() vsip_vgetattrib_f(v,attr) attr.offset += i * attr.stride attr.length -= i vsip_vputattrib_f(vs,attr) return vs def col_sv_f(Am,vv,col): A = vsip_mattr_f() v = vsip_vattr_f() vsip_mgetattrib_f(Am, A) v.offset = A.offset + col * A.row_stride v.stride = A.col_stride v.length = A.col_length vsip_vputattrib_f(vv,v) return vv def row_sv_f(Am,vv,row): A= vsip_mattr_f() v= vsip_vattr_f() vsip_mgetattrib_f(Am,A) v.offset = A.offset + row * A.col_stride v.stride = A.row_stride v.length = A.row_length vsip_vputattrib_f(vv,v) return vv def imsv_f( B, BS, i1,j1, i2, j2): attr = vsip_mattr_f() vsip_mgetattrib_f(B,attr) if(j1 == 0): j1 =attr.col_length if(j2 == 0): j2 =attr.row_length attr.col_length = (j1 - i1) attr.row_length = (j2 - i2) attr.offset += i2 * attr.row_stride + i1 * attr.col_stride vsip_mputattrib_f(BS,attr) return BS def ivsv_f(v, vs, i,j): attr = vsip_vattr_f() vsip_vgetattrib_f(v,attr) if(j==0): j=attr.length attr.offset += i * attr.stride attr.length = j-i vsip_vputattrib_f(vs,attr) return vs def diag_sv_f(Am,a, i): A = vsip_mattr_f() v = vsip_vattr_f() vsip_mgetattrib_f(Am,A) vsip_vgetattrib_f(a,v) v.stride=A.row_stride + A.col_stride if(i==0): v.length = A.row_length v.offset = A.offset elif (i == 1): v.offset = A.offset + A.row_stride v.length = A.row_length - 1 else : print("Failed in diag_sv_f\n") vsip_vputattrib_f(a,v) return a def vclone_f(x, v): vsip_vputlength_f(v,vsip_vgetlength_f(x)) vsip_vcopy_f_f(x,v) return v def meye_f(n): retval = vsip_mcreate_f(n,n,VSIP_ROW,VSIP_MEM_NONE) d = vsip_mdiagview_f(retval,0) vsip_mfill_f(0.0,retval) vsip_vfill_f(1.0,d) vsip_vdestroy_f(d) return retval def sign_f(a_in): if(a_in < 0.0): return -1.0 else: return 1.0 def vnormFro_f(v): return vsip_sqrt_f(vsip_vsumsqval_f(v)) def vnorm2_f(v): return vnormFro_f(v) def mnormFro_f(v): return vsip_sqrt_f(vsip_msumsqval_f(v)) def gtProd_f(i, j, c,s, svd): R = svd.Rs a1= row_sv_f(R,svd.rs_one, i) a2= row_sv_f(R,svd.rs_two, j) a1c=vclone_f(a1,svd.t) vsip_svmul_f(c,a1c,a1); vsip_vsma_f(a2,s,a1,a1) vsip_svmul_f(-s,a1c,a1c); vsip_vsma_f(a2,c,a1c,a2) def prodG_f(svd,i, j,c, s): L = svd.Ls a1= col_sv_f(L,svd.ls_one,i) a2= col_sv_f(L,svd.ls_two,j) a1c=vclone_f(a1,svd.t) vsip_svmul_f(c,a1c,a1); vsip_vsma_f(a2,s,a1,a1) vsip_svmul_f(-s,a1c,a1c);vsip_vsma_f(a2,c,a1c,a2) def houseVector_f(x): nrm=vnorm2_f(x) t = vsip_vget_f(x,0) s = t + sign_f(t) * nrm vsip_vput_f(x,0,s) nrm = vnorm2_f(x) if (nrm == 0.0): vsip_vput_f(x,0,1.0) else: vsip_svmul_f(1.0/nrm,x,x) return x def prodHouse_f(A, v): a_atr = vsip_mattr_f() vsip_mgetattrib_f(A,a_atr) B=vsip_mcreate_f(a_atr.col_length,a_atr.row_length,VSIP_ROW,VSIP_MEM_NONE) w = vsip_vcreate_f(a_atr.col_length,VSIP_MEM_NONE) beta = 2.0/vsip_vdot_f(v,v) vsip_mvprod_f(A,v,w) vsip_vouter_f(beta,w,v,B) vsip_msub_f(A,B,A) vsip_valldestroy_f(w) vsip_malldestroy_f(B) def houseProd_f(v, A): a_atr = vsip_mattr_f() vsip_mgetattrib_f(A,a_atr) B=vsip_mcreate_f(a_atr.col_length,a_atr.row_length,VSIP_ROW,VSIP_MEM_NONE) w = vsip_vcreate_f(a_atr.row_length,VSIP_MEM_NONE) beta = 2.0/vsip_vdot_f(v,v) vsip_vmprod_f(v,A,w) vsip_vouter_f(beta,v,w,B) vsip_msub_f(A,B,A) vsip_valldestroy_f(w) vsip_malldestroy_f(B) def bidiag_f(svd): B = svd.B Bs = svd.Bs m = vsip_mgetcollength_f(B) n = vsip_mgetrowlength_f(B) x=col_sv_f(B,svd.bs,0) v=vclone_f(x,svd.t) vs = svd.ts for i in range(n-1): vsip_vputlength_f(v,m-i) vsip_vcopy_f_f(col_sv_f(msv_f(B,Bs,i,i),x,0),v) houseVector_f(v) vsip_svmul_f(1.0/vsip_vget_f(v,0),v,v) houseProd_f(v,Bs) vsip_vcopy_f_f(vsv_f(v,vs,1),vsv_f(x,x,1)) if(i < n-2): j = i+1 vsip_vputlength_f(v,n-j) vsip_vcopy_f_f(row_sv_f(msv_f(B,Bs,i,j),x,0),v) houseVector_f(v) vsip_svmul_f(1.0/vsip_vget_f(v,0),v,v) prodHouse_f(Bs,v) vsip_vcopy_f_f(vsv_f(v,vs,1),vsv_f(x,x,1)) if(m > n): i=n-1 vsip_vputlength_f(v,m-i) vsip_vcopy_f_f(col_sv_f(msv_f(B,Bs,i,i),x,0),v) houseVector_f(v) vsip_svmul_f(1.0/vsip_vget_f(v,0),v,v) houseProd_f(v,Bs) vsip_vcopy_f_f(vsv_f(v,vs,1),vsv_f(x,x,1)) def UmatExtract_f(svd): B=svd.B U=svd.L m = vsip_mgetcollength_f(B) n = vsip_mgetrowlength_f(B) Bs=svd.Bs Us=svd.Ls v = col_sv_f(B,svd.bs,0) if (m > n): i=n-1 col_sv_f(msv_f(B,Bs,i,i),v,0) t=vsip_vget_f(v,0); vsip_vput_f(v,0,1.0) houseProd_f(v,msv_f(U,Us,i,i)) vsip_vput_f(v,0,t) for i in range(n-2,-1,-1): col_sv_f(msv_f(B,Bs,i,i),v,0) t=vsip_vget_f(v,0); vsip_vput_f(v,0,1.0) houseProd_f(v,msv_f(U,Us,i,i)) vsip_vput_f(v,0,t) def VHmatExtract_f(svd): B = svd.B n = vsip_mgetrowlength_f(B) Bs=svd.Bs V=svd.R Vs=svd.Rs if(n < 3): return v = row_sv_f(B,svd.bs,0) for i in range(n-3,-1,-1): j=i+1 row_sv_f(msv_f(B,Bs,i,j),v,0) t=vsip_vget_f(v,0);vsip_vput_f(v,0,1.0) prodHouse_f(msv_f(V,Vs,j,j),v) vsip_vput_f(v,0,t) def svdZeroCheckAndSet_f(e, b0, b1): n = vsip_vgetlength_f(b1) z = 0.0 for i in range(n): b = vsip_mag_f(vsip_vget_f(b1,i)) a = e*(vsip_mag_f(vsip_vget_f(b0,i)) + vsip_mag_f(vsip_vget_f(b0,i+1))) if( b < a ): vsip_vput_f(b1,i,z) def biDiagPhaseToZero_f( svd): L = svd.L d = svd.d f = svd.f R = svd.R eps0 = svd.eps0 n_d=vsip_vgetlength_f(d) n_f=vsip_vgetlength_f(f) l = svd.ls_one r = svd.rs_one for i in range(n_d): ps=vsip_vget_f(d,i) m = vsip_mag_f(ps) ps=sign_f(ps) if(m > eps0): col_sv_f(L,l,i);vsip_svmul_f(ps,l,l) vsip_vput_f(d,i,m) if (i < n_f): vsip_vput_f(f,i,ps*vsip_vget_f(f,i)) else: vsip_vput_f(d,i,0.0) svdZeroCheckAndSet_f(eps0,d,f) for i in range(n_f-1): j=i+1 ps = vsip_vget_f(f,i) m = vsip_mag_f(ps) ps=sign_f(ps) col_sv_f(L, l, j);vsip_svmul_f(ps,l,l) row_sv_f(R,r,j);vsip_svmul_f(ps,r,r) vsip_vput_f(f,i,m) vsip_vput_f(f,j,ps * vsip_vget_f(f,j)) j=n_f i=j-1 ps=vsip_vget_f(f,i) m=vsip_mag_f(ps) ps=sign_f(ps) vsip_vput_f(f,i,m) col_sv_f(L, l, j);vsip_svmul_f(ps,l,l) row_sv_f(R,r,j);vsip_svmul_f(ps,r,r) def svdBidiag_f(svd): B = svd.B sv = mnormFro_f(B)/vsip_mgetrowlength_f(B) bidiag_f(svd) vsip_vcopy_f_f(diag_sv_f(B,svd.bs,0),svd.d) vsip_vcopy_f_f(diag_sv_f(B,svd.bs,1),svd.f) UmatExtract_f(svd) VHmatExtract_f(svd) svd.eps0=sv*1E-10 biDiagPhaseToZero_f(svd) def givensCoef_f(x1, x2): retval = givensObj_f() t = vsip_hypot_f(x1,x2) if (x2 == 0.0): retval.c=1.0;retval.s=0.0;retval.r=x1 elif (x1 == 0.0): retval.c=0.0;retval.s=sign_f(x2);retval.r=t else: sn = sign_f(x1) retval.c=vsip_mag_f(x1)/t;retval.s=sn*x2/t; retval.r=sn*t return retval def svdCorners_f(f): crnr = svdCorner() j=vsip_vgetlength_f(f)-1 while((j > 0) and (vsip_vget_f(f,j) == 0.0)): j-=1 if(j == 0 and vsip_vget_f(f,0) == 0.0): crnr.i=0 crnr.j=0 else: i = j j += 1 while((i > 0) and (vsip_vget_f(f,i) != 0.0)): i -= 1 if((i == 0) and (vsip_vget_f(f,0)== 0.0)): crnr.i=1 crnr.j=j+1 elif (i==0): crnr.i=0 crnr.j=j+1 else: crnr.i=i+1 crnr.j=j+1 return crnr def phaseCheck_f(svd): biDiagPhaseToZero_f(svd) def zeroFind_f(d, eps0): j = vsip_vgetlength_f(d) xd=vsip_vget_f(d,j-1) while(xd > eps0): if (j > 1): j -= 1 xd=vsip_vget_f(d,j-1) else: break if(xd <= eps0): vsip_vput_f(d,j-1,0.0) if (j == 1): j=0 return j def zeroRow_f(svd): L = svd.Ls d = svd.ds f = svd.fs n = vsip_vgetlength_f(d) g = givensObj_f() xd=vsip_vget_f(d,0) xf=vsip_vget_f(f,0) g=givensCoef_f(xd,xf) if (n == 1): vsip_vput_f(f,0,0.0) vsip_vput_f(d,0,g.r) else: vsip_vput_f(f,0,0.0) vsip_vput_f(d,0,g.r) xf=vsip_vget_f(f,1) t= -xf * g.s; xf *= g.c vsip_vput_f(f,1,xf) prodG_f(svd,1,0,g.c,g.s) for i in range(1,n-1): xd=vsip_vget_f(d,i) g=givensCoef_f(xd,t) prodG_f(svd,i+1,0,g.c,g.s) vsip_vput_f(d,i,g.r) xf=vsip_vget_f(f,i+1) t=-xf * g.s; xf *= g.c vsip_vput_f(f,i+1,xf) xd=vsip_vget_f(d,n-1) g=givensCoef_f(xd,t) vsip_vput_f(d,n-1,g.r) prodG_f(svd,n,0,g.c,g.s) def zeroCol_f(svd): d=svd.ds f=svd.fs R=svd.Rs n = vsip_vgetlength_f(f) g = givensObj_f() if (n == 1): xd=vsip_vget_f(d,0) xf=vsip_vget_f(f,0) g=givensCoef_f(xd,xf) vsip_vput_f(d,0,g.r) vsip_vput_f(f,0,0.0) gtProd_f(0,1,g.c,g.s,svd) elif (n == 2): xd=vsip_vget_f(d,1) xf=vsip_vget_f(f,1) g=givensCoef_f(xd,xf) vsip_vput_f(d,1,g.r) vsip_vput_f(f,1,0.0) xf=vsip_vget_f(f,0) t= -xf * g.s; xf *= g.c vsip_vput_f(f,0,xf) gtProd_f(1,2,g.c,g.s,svd) xd=vsip_vget_f(d,0) g=givensCoef_f(xd,t) vsip_vput_f(d,0,g.r) gtProd_f(0,2,g.c,g.s,svd) else: i=n-1; j=i-1; k=i xd=vsip_vget_f(d,i) xf=vsip_vget_f(f,i) g=givensCoef_f(xd,xf) xf=vsip_vget_f(f,j) vsip_vput_f(f,i,0.0) vsip_vput_f(d,i,g.r) t=-xf*g.s; xf*=g.c vsip_vput_f(f,j,xf) gtProd_f(i,k+1,g.c,g.s,svd) while (i > 1): i = j; j = i-1 xd=vsip_vget_f(d,i) g=givensCoef_f(xd,t) vsip_vput_f(d,i,g.r) xf=vsip_vget_f(f,j) t= -xf * g.s; xf *= g.c vsip_vput_f(f,j,xf) gtProd_f(i,k+1,g.c,g.s,svd) xd=vsip_vget_f(d,0) g=givensCoef_f(xd,t) vsip_vput_f(d,0,g.r) gtProd_f(0,k+1,g.c,g.s,svd) def svdMu_f(d2,f1,d3,f2): cu=d2 * d2 + f1 * f1 cl=d3 * d3 + f2 * f2 cd = d2 * f2 D = (cu * cl - cd * cd) T = (cu + cl) root = vsip_sqrt_f(T*T - 4 * D) lambda1 = (T + root)/(2.) lambda2 = (T - root)/(2.) if(vsip_mag_f(lambda1 - cl) < vsip_mag_f(lambda2 - cl)): mu = lambda1 else: mu = lambda2 return mu def svdStep_f(svd): L = svd.Ls d = svd.ds f = svd.fs R = svd.Rs g = givensObj_f() n = vsip_vgetlength_f(d) mu=0.0; x1=0.0; x2=0.0 t=0.0 if(n >= 3): d2=vsip_vget_f(d,n-2);f1= vsip_vget_f(f,n-3);d3 = vsip_vget_f(d,n-1);f2= vsip_vget_f(f,n-2) elif(n == 2): d2=vsip_vget_f(d,0);f1= 0.0;d3 = vsip_vget_f(d,1);f2= vsip_vget_f(f,0) else: d2=vsip_vget_f(d,0);f1 = 0.0;d3 = 0.0;f2 = 0.0 mu = svdMu_f(d2,f1,d3,f2) x1=vsip_vget_f(d,0) x2 = x1 * vsip_vget_f(f,0) x1 *= x1; x1 -= mu g=givensCoef_f(x1,x2) x1=vsip_vget_f(d,0);x2=vsip_vget_f(f,0) vsip_vput_f(f,0,g.c * x2 - g.s * x1) vsip_vput_f(d,0,x1 * g.c + x2 * g.s) t=vsip_vget_f(d,1); vsip_vput_f(d,1,t*g.c) t*=g.s gtProd_f(0,1,g.c,g.s,svd) for i in range(n-2): j=i+1; k=i+2 g = givensCoef_f(vsip_vget_f(d,i),t) vsip_vput_f(d,i,g.r) x1=vsip_vget_f(d,j)*g.c x2=vsip_vget_f(f,i)*g.s t= x1 - x2; x1=vsip_vget_f(f,i) * g.c x2=vsip_vget_f(d,j) * g.s vsip_vput_f(f,i,x1+x2) vsip_vput_f(d,j,t); x1=vsip_vget_f(f,j) t=g.s * x1 vsip_vput_f(f,j, x1*g.c) prodG_f(svd,i, j, g.c, g.s) g=givensCoef_f(vsip_vget_f(f,i),t) vsip_vput_f(f,i,g.r) x1=vsip_vget_f(d,j); x2=vsip_vget_f(f,j) vsip_vput_f(d,j,g.c * x1 + g.s * x2); vsip_vput_f(f,j,g.c * x2 - g.s * x1) x1=vsip_vget_f(d,k) t=g.s * x1; vsip_vput_f(d,k,x1*g.c) gtProd_f(j,k, g.c, g.s,svd) i=n-2; j=n-1 g = givensCoef_f(vsip_vget_f(d,i),t) vsip_vput_f(d,i,g.r) x1=vsip_vget_f(d,j)*g.c; x2=vsip_vget_f(f,i)*g.s t=x1 - x2 x1 = vsip_vget_f(f,i) * g.c; x2=vsip_vget_f(d,j) * g.s vsip_vput_f(f,i,x1+x2) vsip_vput_f(d,j,t) prodG_f(svd,i, j, g.c, g.s) def svdIteration_f(svd): L0 = svd.L; L = svd.Ls d0 = svd.d; d = svd.ds f0 = svd.f; f = svd.fs R0 = svd.R; R= svd.Rs eps0 = svd.eps0 cnr = svdCorner() cntr=0 maxcntr=20*vsip_vgetlength_f(d0) while (cntr < maxcntr): cntr += 1 phaseCheck_f(svd) cnr=svdCorners_f(f0) if (cnr.j == 0): break ivsv_f(d0,d,cnr.i,cnr.j) ivsv_f(f0,f,cnr.i,cnr.j-1) imsv_f(L0,L,0,0,cnr.i,cnr.j) imsv_f(R0,R,cnr.i,cnr.j,0,0) n=vsip_vgetlength_f(f) k=zeroFind_f(d,eps0) if (k > 0): if(vsip_vget_f(d,n) == 0.0): zeroCol_f(svd) else: imsv_f(L,L,0,0,k-1,0) ivsv_f(d0,d,k,0) ivsv_f(f0,f,k-1,0) zeroRow_f(svd) else: svdStep_f(svd) def svdSort_f(svd): d = svd.d n=vsip_vgetlength_f(d) indx_L = svd.indx_L indx_R = svd.indx_R L0 = svd.L L=svd.Ls R0 = svd.R vsip_vsortip_f(d,VSIP_SORT_BYVALUE,VSIP_SORT_DESCENDING,1,indx_L) vsip_vcopy_vi_vi(indx_L,indx_R) imsv_f( L0, L, 0,0, 0, n) vsip_mpermute_once_f(L,VSIP_COL,indx_L,L) vsip_mpermute_once_f(R0,VSIP_ROW,indx_R,R0) class svdCorner: def __init__(self): self.i=0 self.j=0 class givensObj_f: def __init__(self): self.c=0.0 self.s=0.0 self.r=0.0 class svdObj_f: def __init__(self,m,n): if(m < n): print("Column length must not be less than row length") return self.t = vsip_vcreate_f(m,VSIP_MEM_NONE) self.ts = vsip_vcloneview_f(self.t) self.B=vsip_mcreate_f(m,n,VSIP_ROW,VSIP_MEM_NONE) self.Bs=vsip_mcloneview_f(self.B) self.bs=vsip_mrowview_f(self.B,0) self.L=meye_f(m) self.Ls = vsip_mcloneview_f(self.L) self.ls_two = vsip_mrowview_f(self.Ls,0) self.ls_one = vsip_mrowview_f(self.Ls,0) self.R=meye_f(n) self.Rs = vsip_mcloneview_f(self.R) self.rs_two = vsip_mrowview_f(self.Rs,0) self.rs_one = vsip_mrowview_f(self.Rs,0) self.indx_L=vsip_vcreate_vi(n,VSIP_MEM_NONE) self.indx_R=vsip_vcreate_vi(n,VSIP_MEM_NONE) self.d=vsip_vcreate_f(n,VSIP_MEM_NONE); self.f=vsip_vcreate_f(n-1,VSIP_MEM_NONE) self.ds=vsip_vcloneview_f(self.d) self.fs=vsip_vcloneview_f(self.f) def __del__(self): vsip_vdestroy_f(self.ts) vsip_valldestroy_f(self.t) vsip_vdestroy_f(self.rs_one) vsip_vdestroy_f(self.rs_two) vsip_mdestroy_f(self.Rs) vsip_vdestroy_f(self.ls_one) vsip_vdestroy_f(self.ls_two) vsip_mdestroy_f(self.Ls) vsip_mdestroy_f(self.Bs) vsip_vdestroy_f(self.bs) vsip_malldestroy_f(self.B) vsip_malldestroy_f(self.R) vsip_malldestroy_f(self.L) vsip_valldestroy_vi(self.indx_L) vsip_valldestroy_vi(self.indx_R) vsip_vdestroy_f(self.ds);vsip_valldestroy_f(self.d) vsip_vdestroy_f(self.fs);vsip_valldestroy_f(self.f) def svd_f(A): svd = svdObj_f(vsip_mgetcollength_f(A),vsip_mgetrowlength_f(A)) vsip_mcopy_f_f(A,svd.B) svdBidiag_f(svd) svdIteration_f(svd) svdSort_f(svd) return svd <file_sep>def mgetsub(v1, v2, i,j, cs,rs, cl,rl): attr=v1.attrib o='offset';rows='rowstride';cols='colstride' rowl='rowlength';coll='collength' attr[o] +=i*attr[cols]+j*attr[rows] attr[rows]*= rs; attr[cols] *= cs attr[rowl] = rl; attr[coll] = cl v2.putattrib(attr) <file_sep>/* Created R Judd */ /* Copyright (c) 2006 <NAME> */ /* MIT style license, see Copyright notice in top level directory */ /* $Id: ctoeplitz_d.h,v 1.1 2006/05/16 16:45:18 judd Exp $ */ #include"VU_cvprintm_d.include" static void ctoeplitz_d(void) { vsip_cmview_d *A = vsip_cmcreate_d(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *B = vsip_cmcreate_d(4,1,VSIP_ROW,VSIP_MEM_NONE); vsip_cvview_d *b = vsip_cmcolview_d(B,0); vsip_cvview_d *t = vsip_cvcreate_d(4,VSIP_MEM_NONE), *x = vsip_cvcreate_d(4,VSIP_MEM_NONE), *w = vsip_cvcreate_d(4,VSIP_MEM_NONE), *y = vsip_cvcreate_d(4,VSIP_MEM_NONE); printf("\ntest ctoeplitz_d\n"); vsip_cvput_d(t,(vsip_index)0,vsip_cmplx_d(1.0,0)); vsip_cvput_d(t,(vsip_index)1,vsip_cmplx_d(0.0,.4)); vsip_cvput_d(t,(vsip_index)2,vsip_cmplx_d(0.0,.2)); vsip_cvput_d(t,(vsip_index)3,vsip_cmplx_d(0.0,.15)); vsip_cvput_d(y,(vsip_index)0,vsip_cmplx_d(4.0,1)); vsip_cvput_d(y,(vsip_index)1,vsip_cmplx_d(-1.0,2)); vsip_cvput_d(y,(vsip_index)2,vsip_cmplx_d(3.0,3)); vsip_cvput_d(y,(vsip_index)3,vsip_cmplx_d(-2.0,-4)); /* place full (lower diagonal) matrix in A */ vsip_cmput_d(A,0,0,vsip_cvget_d(t,0)); vsip_cmput_d(A,1,0,vsip_conj_d(vsip_cvget_d(t,1)));vsip_cmput_d(A,1,1,vsip_cvget_d(t,0)); vsip_cmput_d(A,2,0,vsip_conj_d(vsip_cvget_d(t,2)));vsip_cmput_d(A,2,1,vsip_conj_d(vsip_cvget_d(t,1)));vsip_cmput_d(A,2,2,vsip_cvget_d(t,0)); vsip_cmput_d(A,3,0,vsip_conj_d(vsip_cvget_d(t,3)));vsip_cmput_d(A,3,1,vsip_conj_d(vsip_cvget_d(t,2)));vsip_cmput_d(A,3,2,vsip_conj_d(vsip_cvget_d(t,1)));vsip_cmput_d(A,3,3,vsip_cvget_d(t,0)); vsip_cvcopy_d_d(y,b); /* solve using cholesky */ { vsip_cchol_d *chol = vsip_cchold_create_d(VSIP_TR_LOW,4); vsip_cchold_d(chol,A); vsip_ccholsol_d(chol,B); vsip_cchold_destroy_d(chol); } printf("the solution using cholesky is\n"); VU_cvprintm_d("7.5",b); printf("t=\n");VU_cvprintm_d("6.4",t); printf("y=\n");VU_cvprintm_d("6.4",y); vsip_ctoepsol_d(t,y,w,x); printf("t=\n");VU_cvprintm_d("6.4",t); printf("y=\n");VU_cvprintm_d("6.4",y); printf("the solution using toeplitz is\n"); printf("x=\n");VU_cvprintm_d("6.4",x); vsip_cvsub_d(x,b,w); if(vsip_cmag_d(vsip_cvsumval_d(w)) < .00001) printf("\ncorrect\n"); else printf("\nerror\n"); vsip_cvalldestroy_d(t); vsip_cvalldestroy_d(x); vsip_cvalldestroy_d(w); vsip_cvalldestroy_d(y); vsip_cmalldestroy_d(A); vsip_cvdestroy_d(b); vsip_cmalldestroy_d(B); } <file_sep># -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <markdowncell> # ### LU Decomposition # <codecell> import pyJvsip as pv f='%.5f' # <markdowncell> # Solve using LU Class # <markdowncell> # Create some data A x = b # Note we create an x and calculate a b directly. To demonstrate we use A and b to estimate x. # <codecell> n=5 A=pv.create('mview_d',n,n).fill(0.0) A.randn(5) x=pv.create('vview_d',n).randn(9) print('Matrix A');A.mprint(f) print('Known x vector');x.mprint(f) b=A.prod(x) print('Calculated b=Ax vector');b.mprint(f) # <markdowncell> # Both LU and SV overwrite the input matrix; so to preserve our original matrix we use a copy. The LU (and SV) object will keep a reference to the copy (which means python will not garbage collect it). We solve this first using SVD. We don't overwrite our original vector so we can compare the estimated solution to the actual solution. SVD does not have a solver so we do it long hand. # <codecell> u,s,v=A.copy.svd s.mprint(f) xe=v.prod(u.transview.prod(b)/s) x.mprint(f) xe.mprint(f) print('Forbenius norm of x estimate - x is %.5e'%(xe-x).normFro) # <markdowncell> # Now we solve using LU. We start with the LU class directly. # <markdowncell> # Note that the class instance varialbe LU.luSel is a dictionary which lets you select the LU decomposition type using the matrix type. # <codecell> print('Example of LU.luSel: %s'%pv.LU.luSel[A.type]) luObj = pv.LU(pv.LU.luSel[A.type],n) _=luObj.decompose(A.copy) print('Solve for x using b. Done in place. Here we make a copy of b first. ') xe = b.copy luObj.solve(pv.VSIP_MAT_NTRANS,xe).mprint(f) print('Forbenius norm of x estimate - x is %.5e'%(xe-x).normFro) # <markdowncell> # In pyJvsip a method is defined on matrix views which will create the LU object for you. We do the same problem. # <codecell> xe=b.copy luObj=A.copy.lu luObj.solve(pv.VSIP_MAT_NTRANS,xe).mprint(f) print('Forbenius norm of x estimate - x is %.5e'%(xe-x).normFro) # <markdowncell> # For a simple solver we can also just solve directly. If we wanted to solve using matrix operator 'HERM' or 'TRANS' then we would need the more complicated version. # <codecell> xe=b.copy A.copy.luSolve(xe).mprint(f) print('Forbenius norm of x estimate - x is %.5e'%(xe-x).normFro) # <markdowncell> # We also have a pyJvsip method to calculate an inverse using the LU methods. # <codecell> Ainv=A.copy.luInv print('A inverse') Ainv.mprint(f) print('Origional A') A.mprint(f) print('check to see if we have an inverse by doing a matrix product') A.prod(Ainv).mprint(f) # <codecell> <file_sep>from vsip import * def __isSizeCompatible(a,b): if 'mview' in a.type and 'mview' in b.type: if (a.rowlength == b.rowlength) and (a.collength == b.collength): return True elif 'vview' in a.type and 'vview' in b.type: if a.length == b.length: return True else: return False #vsip_dvam_p #vsip_dvsam_p def am(a,b,c,d): """ vector add and multiply add two vectors and multiply times a vector, elementwise or add a vector and a scalar, elementwise, and mutiply times a vector elementwise """ f={'cvview_dcvview_dcvview_dcvview_d':vsip_cvam_d, 'cvview_dcscalarcvview_dcvview_d':vsip_cvsam_d, 'cvview_fcscalarcvview_fcvview':vsip_cvsam_f, 'vview_dscalarvview_dvview_d':vsip_vsam_d, 'vview_fscalarvview_fvview_f':vsip_vsam_f, 'cvview_fcvview_fcvview_fcvview_f':vsip_cvam_f, 'vview_dvview_dvview_dvview_d':vsip_vam_d, 'vview_fvview_fvview_fvview_f':vsip_vam_f} assert 'pyJvsip' in repr(a),'Argument one must be a pyJvsip view object in am' t1=a.type assert __isSizeCompatible(a,c),'Size error in add-multiply (am)' assert __isSizeCompatible(a,d),'Size error in add-multiply (am)' if isinstance(b,int) or isinstance(b,float): t2='scalar' elif isinstance(b,complex): t2='cscalar' else: assert 'pyJvsip' in repr(b),\ 'Argument two must be a scalar or a pyJvsip view object in am' t2=b.type assert a.type==b.type,'View types must agree in am' assert 'pyJvsip' in repr(c),'Argument three must be a pyJvsip view object in am' assert __isSizeCompatible(a,c),'Size error in add-multiply (am)' t3=c.type assert a.type==c.type,'View types must agree in am' assert 'pyJvsip' in repr(d),'Argument four must be a pyJvsip view object in am' assert __isSizeCompatible(a,d),'Size error in add-multiply (am)' assert a.type==d.type,'View types must agree in am' t4=d.type if 'scalar' in t2 and 'cvview' in t1: t2='cscalar' t=t1+t2+t3+t4 assert t in f, 'Type <:'+t+':> not recognized for am' if 'cscalar' in t: if 'cvview_d' in t: f[t](a.vsip,vsip_cmplx_d(b.real,b.imag),c.vsip,d.vsip) else: f[t](a.vsip,vsip_cmplx_f(b.real,b.imag),c.vsip,d.vsip) elif 'scalar' in t: f[t](a.vsip,b,c.vsip.d.vsip) else: f[t](a.vsip,b.vsip,c.vsip,d.vsip) return d #vsip_vma_p #vsip_dvmsa_p #vsip_dvsma_p #vsip_dvsmsa_p def ma(a,b,c,d): """ Multiply-Add ma(a,b,c,d) a=>vector view b=> vector view or scalar c=> vector view or scalar d=> vector view of same type as a a and d can be the same view (in-place) """ f={'cvview_dcvview_dcvview_dcvview_d':vsip_cvma_d, 'cvview_fcvview_fcvview_fcvview_f':vsip_cvma_f, 'vview_dvview_dvview_dvview_d':vsip_vma_d, 'vview_fvview_fvview_fvview_f':vsip_vma_f, 'cvview_dcscalarcvview_dcvview_d':vsip_cvsma_d, 'cvview_fcscalarcvview_fcvview_f':vsip_cvsma_f, 'vview_dscalarvview_dvview_d':vsip_vsma_d, 'vview_fscalarvview_fvview_f':vsip_vsma_f, 'cvview_dcvview_dcscalarcvview_d':vsip_cvmsa_d, 'cvview_fcvview_fcscalarcvview_f':vsip_cvmsa_f, 'vview_dvview_dscalarvview_d':vsip_vmsa_d, 'vview_fvview_fscalarvview_f':vsip_vmsa_f, 'cvview_dcscalarcscalarcvview_d':vsip_cvsmsa_d, 'cvview_fcscalarcscalarcvview_f':vsip_cvsmsa_f, 'vview_dscalarscalarvview_d':vsip_vsmsa_d, 'vview_fscalarscalarvview_f':vsip_vsmsa_f} assert 'pyJvsip' in repr(a),'Argument one must be a pyJvsip view object in am' t1=a.type assert 'pyJvsip' in repr(d),'Argument four must be a pyJvsip view object in am' t4=d.type assert t1 == t4,'Views in ma must be the same type' assert __isSizeCompatible(a,d),'Size error in ma (multiply-add)' if isinstance(b,int) or isinstance(b,float): if 'cvview_d' in t1: t2='cscalar' b0=vsip_cmplx_d(float(b),0.0) elif 'cvview_f' in t1: t2='cscalar' b0=vsip_cmplx_f(float(b),0.0) else: t2='scalar' b0=float(b) elif isinstance(b,complex): t2='cscalar' if 'cvview_d' in t1: b0=vsip_cmplx_d(b.real,b.imag) else: b0=vsip_cmplx_f(b.real,b.imag) else: assert 'pyJvsip' in repr(b),\ 'Argument two must be a pyJvsip view object or scalar in am' assert __isSizeCompatible(a,b),'Size error in ma (multiply-add)' t2=b.type b0=b.vsip if isinstance(c,int) or isinstance(c,float): if 'cvview_d' in t1: t3='cscalar' c0=vsip_cmplx_d(float(c),0.0) elif 'cvview_f' in t1: t3='cscalar' c0=vsip_cmplx_f(float(c),0.0) else: t3='scalar' c0=float(c) elif isinstance(c,complex): t3='cscalar' if 'cvview_d' in t1: c0=vsip_cmplx_d(c.real,c.imag) else: c0=vsip_cmplx_f(c.real,c.imag) else: assert 'pyJvsip' in repr(c),\ 'Argument three must be a pyJvsip view object or scalar in ma' assert __isSizeCompatible(a,c),'Size error in ma (multiply-add)' t3=c.type c0=c.vsip t=t1+t2+t3+t4 assert t in f, 'Type <:'+t+':> not recognized for ma' f[t](a.vsip,b0,c0,d.vsip) return d #vsip_dvmsb_p def msb(a,b,c,d): """ vector multiply - vector subtract msb(a,b,c,d) d == a * b - c (elementwise) a=>vector view b=>vector view c=>vector view d=>vector view May be done in place so d may be a, b, or c """ f={'cvview_dcvview_dcvview_dcvview_d':vsip_cvmsb_d, 'cvview_fcvview_fcvview_fcvview_f':vsip_cvmsb_f, 'vview_dvview_dvview_dvview_d':vsip_vmsb_d, 'vview_fvview_fvview_fvview_f':vsip_vmsb_f} assert 'pyJvsip' in repr(a),'Argument one must be a pyJvsip view object in msb' assert 'pyJvsip' in repr(b),'Argument two must be a pyJvsip view object in msb' assert 'pyJvsip' in repr(c),'Argument three must be a pyJvsip view object in msb' assert 'pyJvsip' in repr(d),'Argument four must be a pyJvsip view object in msb' assert __isSizeCompatible(a,b) and __isSizeCompatible(a,c) and __isSizeCompatible(a,b)\ ,'Size error in ma (multiply-add)' t=a.type+b.type+c.type+d.type assert t in f, 'Type <:'+t+':> not recognized for msb' f[t](a.vsip,b.vsip,c.vsip,d.vsip) return d #vsip_dvsbm_p def sbm(a,b,c,d): """ vector subtract - vector multiply sbm(a,b,c,d) d == (a - b) * c (elementwise) a=>vector view b=>vector view c=>vector view d=>vector view May be done in place so d may be a, b, or c """ f={'cvview_dcvview_dcvview_dcvview_d':vsip_cvsbm_d, 'cvview_fcvview_fcvview_fcvview_f':vsip_cvsbm_f, 'vview_dvview_dvview_dvview_d':vsip_vsbm_d, 'vview_fvview_fvview_fvview_f':vsip_vsbm_f} assert 'pyJvsip' in repr(a),'Argument one must be a pyJvsip view object in msb' assert 'pyJvsip' in repr(b),'Argument two must be a pyJvsip view object in msb' assert 'pyJvsip' in repr(c),'Argument three must be a pyJvsip view object in msb' assert 'pyJvsip' in repr(d),'Argument four must be a pyJvsip view object in msb' assert __isSizeCompatible(a,b) and __isSizeCompatible(a,c) and __isSizeCompatible(a,b)\ ,'Size error in ma (multiply-add)' t=a.type+b.type+c.type+d.type assert t in f, 'Type <:'+t+':> not recognized for msb' f[t](a.vsip,b.vsip,c.vsip,d.vsip) return d <file_sep>// // scalar.h // cppJvsip // // Created by <NAME> on 4/21/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #ifndef __cppJvsip__scalar__ #define __cppJvsip__scalar__ #include <cstring> #include <iostream> #include <cassert> extern "C"{ #include<vsip.h> } namespace jvsip { using std::string; class Scalar{ friend std::ostream &operator<<(std::ostream &, const Scalar &); private: string p; //precision string d; //depth string s; //shape union { float re_f; double re_d; vsip_scalar_i i; vsip_scalar_vi vi; vsip_stride stride; } rvalue; union { float im_f; double im_d; } cvalue; public: Scalar(float); Scalar(double); Scalar(vsip_cscalar_f); Scalar(vsip_cscalar_d); Scalar(vsip_scalar_i); Scalar(vsip_scalar_vi); Scalar(vsip_stride); //copy constructor Scalar(const Scalar& other) : p(other.p),s(other.s),d(other.d){ if(p=="f"){ rvalue.re_f=other.scalar_f(); cvalue.im_f=0.0f; } else if (p=="d"){ rvalue.re_d=other.scalar_d(); cvalue.im_d=0.0; } else if (p=="i"){ rvalue.i=other.scalar_i(); } else{ rvalue.vi=other.scalar_vi(); } } ~Scalar(){} string precision() const{ return p; } string depth() const{ return d; } string shape() const{ return s; } float scalar_f() const; double scalar_d() const; vsip_cscalar_f scalar_cf() const; vsip_cscalar_d scalar_cd() const; vsip_scalar_i scalar_i() const; vsip_scalar_vi scalar_vi() const; vsip_stride stride() const; vsip_length length() const { return scalar_vi();} vsip_offset offset() const { return scalar_vi();} }; } #endif /* defined(__cppJvsip__scalar__) */ <file_sep>import vsiputils as vsip class Kw(object): def __init__(self,param): mem=vsip.VSIP_MEM_NONE col=vsip.VSIP_COL row=vsip.VSIP_ROW fftfwd=vsip.VSIP_FFT_FWD vsip.init() Nsens=param['Nsens'] Nts=param['Nts'] Nfreq=int(Nts/2) + 1 self.Navg=param['Navg'] self.Nfreq=Nfreq self.cm_freq=vsip.create('cmview_d',(Nsens,Nfreq,col,mem)) self.rm_freq=vsip.realview(self.cm_freq) self.m_gram=vsip.create('mview_d',(Nsens,Nfreq,col,mem)) self.rcfftm=vsip.create('rcfftmop_d',(Nsens,Nts,1,row,0,0)) self.ccfftm=vsip.create('ccfftmip_d',(Nsens,Nfreq,fftfwd,1,col,0,0)) self.ts_taper=vsip.create('hanning_d',(Nts,0)) self.array_taper=vsip.create('hanning_d',(Nsens,0)); def __del__(self): vsip.destroy(self.rm_freq) vsip.allDestroy(self.cm_freq) vsip.allDestroy(self.m_gram) vsip.allDestroy(self.ts_taper) vsip.allDestroy(self.array_taper) vsip.destroy(self.rcfftm) vsip.destroy(self.ccfftm) vsip.finalize() def zero(self): vsip.fill(0.0,self.m_gram) def kw(self,m_data): row=vsip.VSIP_ROW col=vsip.VSIP_COL vsip.vmmul(self.ts_taper,m_data,row,m_data); vsip.vmmul(self.array_taper,m_data,col,m_data); vsip.fftop(self.rcfftm,m_data,self.cm_freq) vsip.fftip(self.ccfftm,self.cm_freq) vsip.magsq(self.cm_freq,self.rm_freq) #check rm_freq real part? vsip.mul(1.0/self.Navg,self.rm_freq, self.rm_freq) vsip.add(self.rm_freq,self.m_gram,self.m_gram) def instance(self): return self.m_gram <file_sep>/* Created RJudd */ /* */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* */ /* $Id: mprod4_f.h,v 2.2 2006/04/27 01:40:55 judd Exp $ */ #include"VU_mprintm_f.include" static void mprod4_f(void){ printf("********\nTEST mprod4_f\n"); { vsip_scalar_f datal[] = {1.0, 2.0, 3.0, 4.0, 5.0, 5.0, 0.1, 0.2, 0.3, 0.4, 4.0, 3.0, 2.0, 0.0, -1.0, 1.0}; vsip_scalar_f datar[] = {0.1, 0.2, 0.3, 0.4, 1.0, 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 2.4, -1.1, -1.2, -1.3, -1.4, 2.1, 2.2, 2.3, 3.4, 2.0, 3.0, 4.0, 5.0, 2.1, 2.2, 0.3, 3.2, 2.1, 2.2, 1.0, 5.1}; vsip_scalar_f ans_data[] = {19.00, 20.00, 13.00, 28.20, 13.20, 16.50, 14.60, 33.90, 11.63, 12.66, 13.29, 14.98, 0.12, 0.24, 0.10, 1.02, 15.57, 16.34, 11.11, 24.28, 14.16, 18.45, 18.84, 35.13, 0.20, 0.40, -1.40, 0.60, 2.10, 1.40, -0.60, 2.70}; vsip_block_f *blockl = vsip_blockbind_f(datal,16,VSIP_MEM_NONE); vsip_block_f *blockr = vsip_blockbind_f(datar,32,VSIP_MEM_NONE); vsip_block_f *block_ans = vsip_blockbind_f(ans_data,32,VSIP_MEM_NONE); vsip_block_f *block = vsip_blockcreate_f(200,VSIP_MEM_NONE); vsip_mview_f *ml = vsip_mbind_f(blockl,0,4,4,1,4); vsip_mview_f *mr = vsip_mbind_f(blockr,0,8,4,1,8); vsip_mview_f *ans = vsip_mbind_f(block_ans,0,8,4,1,8); vsip_mview_f *a = vsip_mbind_f(block,20,-1,4,-4,4); vsip_mview_f *a_cm = vsip_mcreate_f(4,4,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *a_rm = vsip_mcreate_f(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *b_cm = vsip_mcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *b_rm = vsip_mcreate_f(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *c_cm = vsip_mcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *c_rm = vsip_mcreate_f(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *b = vsip_mbind_f(block,100,-1,4,-6,8); vsip_mview_f *c = vsip_mbind_f(block,150,-8,4,-1,8); vsip_mview_f *chk = vsip_mcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *aa = vsip_mcreate_f(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *bb = vsip_mcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *cc = vsip_mcreate_f(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *c_cc = vsip_cmcreate_f(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *c_bb = vsip_cmcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *i_cc = vsip_mimagview_f(c_cc); vsip_mview_f *r_bb = vsip_mrealview_f(c_bb); vsip_blockadmit_f(blockl,VSIP_TRUE); vsip_blockadmit_f(blockr,VSIP_TRUE); vsip_blockadmit_f(block_ans,VSIP_TRUE); vsip_mcopy_f_f(ml,a); vsip_mcopy_f_f(ml,a_cm); vsip_mcopy_f_f(ml,a_rm); vsip_mcopy_f_f(mr,b); vsip_mcopy_f_f(mr,b_cm); vsip_mcopy_f_f(mr,b_rm); vsip_mcopy_f_f(mr,r_bb); vsip_mcopy_f_f(a,aa); vsip_mcopy_f_f(b,bb); vsip_mprod4_f(a,b,c); printf("vsip_mprod4_f(a,b,c)\n"); printf("a\n"); VU_mprintm_f("6.4",a); printf("b\n"); VU_mprintm_f("6.4",b); printf("c\n"); VU_mprintm_f("6.4",c); printf("right answer\n"); VU_mprintm_f("6.4",ans); vsip_msub_f(c,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_mprod4_f(aa,bb,cc); printf("vsip_mprod4_f(aa,bb,cc)\n"); printf("aa\n"); VU_mprintm_f("6.4",aa); printf("bb\n"); VU_mprintm_f("6.4",bb); printf("cc\n"); VU_mprintm_f("6.4",cc); printf("right answer\n"); VU_mprintm_f("6.4",ans); vsip_msub_f(cc,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_mprod4_f(aa,r_bb,i_cc); printf("vsip_mprod4_f(aa,bb,cc)\n"); printf("aa\n"); VU_mprintm_f("6.4",aa); printf("bb\n"); VU_mprintm_f("6.4",r_bb); printf("cc\n"); VU_mprintm_f("6.4",i_cc); printf("right answer\n"); VU_mprintm_f("6.4",ans); vsip_msub_f(i_cc,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check ccc\n"); vsip_mprod4_f(a_cm,b_cm,c_cm); vsip_msub_f(c_cm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check ccr\n"); vsip_mprod4_f(a_cm,b_cm,c_rm); vsip_msub_f(c_rm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check crc\n"); vsip_mprod4_f(a_cm,b_rm,c_cm); vsip_msub_f(c_cm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check crr\n"); vsip_mprod4_f(a_cm,b_rm,c_rm); vsip_msub_f(c_rm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check rcc\n"); vsip_mprod4_f(a_rm,b_cm,c_cm); vsip_msub_f(c_cm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check rcr\n"); vsip_mprod4_f(a_rm,b_cm,c_rm); vsip_msub_f(c_rm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check rrc\n"); vsip_mprod4_f(a_rm,b_rm,c_cm); vsip_msub_f(c_cm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check rrr\n"); vsip_mprod4_f(a_rm,b_rm,c_rm); vsip_msub_f(c_rm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_f(ml); vsip_malldestroy_f(mr); vsip_mdestroy_f(a); vsip_malldestroy_f(aa); vsip_mdestroy_f(b); vsip_malldestroy_f(bb); vsip_malldestroy_f(c); vsip_malldestroy_f(cc); vsip_malldestroy_f(ans); vsip_malldestroy_f(chk); vsip_mdestroy_f(i_cc); vsip_mdestroy_f(r_bb); vsip_cmalldestroy_f(c_cc); vsip_cmalldestroy_f(c_bb); vsip_malldestroy_f(a_cm); vsip_malldestroy_f(a_rm); vsip_malldestroy_f(b_cm); vsip_malldestroy_f(b_rm); vsip_malldestroy_f(c_cm); vsip_malldestroy_f(c_rm); } return; } <file_sep>/* Created RJudd */ /* */ #include"VU_vprintm_f.include" static void vfreqswap_f(void){ printf("*********\nTEST vfreqswap_f\n"); { vsip_length M=8,N=9; vsip_vview_f *even = vsip_vcreate_f(M,VSIP_MEM_NONE); vsip_vview_f *ans_even=vsip_vcreate_f(M,VSIP_MEM_NONE); vsip_vview_f *odd = vsip_vcreate_f(N,VSIP_MEM_NONE); vsip_vview_f *ans_odd=vsip_vcreate_f(N,VSIP_MEM_NONE); vsip_scalar_f even_ans[] = {4, 5, 6, 7, 0, 1, 2, 3}; vsip_scalar_f odd_ans[] = {4, 5, 6, 7, 8, 0, 1, 2, 3}; vsip_vcopyfrom_user_f(even_ans, ans_even); vsip_vcopyfrom_user_f(odd_ans, ans_odd); vsip_vramp_f(0,1,even); vsip_vramp_f(0,1,odd); vsip_vfreqswap_f(even); printf("For even expect\n");VU_vprintm_f("2.1",ans_even); printf("for even result\n");VU_vprintm_f("2.1",even); { vsip_vsub_f(even,ans_even,ans_even); if(fabs(vsip_vmaxval_f(ans_even,NULL)) > .00001){ printf("error\n"); }else{ printf("correct\n"); } } vsip_vfreqswap_f(odd); printf("For odd expect\n");VU_vprintm_f("2.1",ans_odd); printf("for odd result\n");VU_vprintm_f("2.1",odd); { vsip_vsub_f(odd,ans_odd,ans_odd); if(fabs(vsip_vmaxval_f(ans_odd,NULL)) > .00001){ printf("error\n"); }else{ printf("correct\n"); } } vsip_valldestroy_f(even); vsip_valldestroy_f(odd); } } <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmcopyfrom_user_f.h,v 1.1 2007/04/18 03:59:06 judd Exp $ */ #include"VU_cmprintm_f.include" static void cmcopyfrom_user_f(void){ vsip_index i,j; printf("********\nTEST cmcopyfrom_user_f\n"); { /* check row copy interleaved */ vsip_cblock_f *block = vsip_cblockcreate_f(200,VSIP_MEM_NONE); vsip_scalar_f input[40]={0,0,0,1,0,2,0,3,1,0,1,1,1,2,1,3,2,0,2,1,2,2,2,3,3,0,3,1,3,2,3,3,4,0,4,1,4,2,4,3}; vsip_cmview_f *view = vsip_cmbind_f(block,100,2,5,12,4); vsip_cvview_f *all = vsip_cvbind_f(block,0,1,200); vsip_scalar_f check = 0; vsip_cvfill_f(vsip_cmplx_f(-1,-1),all); vsip_cmcopyfrom_user_f(input,(vsip_scalar_f*)NULL,VSIP_ROW,view); printf("check row copy interleaved\n"); VU_cmprintm_f("3.2",view); for(i=0; i<5; i++) { for(j=0; j < 4; j++) { check += fabs(input[2*(i * 4 + j)] - vsip_real_f(vsip_cmget_f(view,i,j))); check += fabs(input[2*(i * 4 + j)+1] - vsip_imag_f(vsip_cmget_f(view,i,j))); } } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_cvdestroy_f(all); vsip_cmdestroy_f(view); vsip_cblockdestroy_f(block); } { /* check col copy interleaved*/ vsip_cblock_f *block = vsip_cblockcreate_f(200,VSIP_MEM_NONE); vsip_scalar_f input[40]={0,0,1,0,2,0,3,0,4,0,0,1,1,1,2,1,3,1,4,1,0,2,1,2,2,2,3,2,4,2,0,3,1,3,2,3,3,3,4,3}; vsip_cmview_f *view = vsip_cmbind_f(block,100,2,5,12,4); vsip_cvview_f *all = vsip_cvbind_f(block,0,1,200); vsip_scalar_f check = 0; vsip_cvfill_f(vsip_cmplx_f(-1,-1),all); vsip_cmcopyfrom_user_f(input,(vsip_scalar_f*)NULL,VSIP_COL,view); printf("check col copy interleaved\n"); VU_cmprintm_f("3.2",view); for(j=0; j<4; j++) { for(i=0; i < 5; i++) { check += fabs(input[2*(i + j * 5)] - vsip_real_f(vsip_cmget_f(view,i,j))); check += fabs(input[2*(i + j * 5)+1] - vsip_imag_f(vsip_cmget_f(view,i,j))); } } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_cvdestroy_f(all); vsip_cmdestroy_f(view); vsip_cblockdestroy_f(block); } { /* check row copy split */ vsip_cblock_f *block = vsip_cblockcreate_f(200,VSIP_MEM_NONE); vsip_scalar_f input_r[20]={0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4}; vsip_scalar_f input_i[20]={0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3}; vsip_cmview_f *view = vsip_cmbind_f(block,100,2,5,12,4); vsip_cvview_f *all = vsip_cvbind_f(block,0,1,200); vsip_scalar_f check = 0; vsip_cvfill_f(vsip_cmplx_f(-1,-1),all); vsip_cmcopyfrom_user_f(input_r,input_i,VSIP_ROW,view); printf("check row copy split\n"); VU_cmprintm_f("3.2",view); for(i=0; i<5; i++) { for(j=0; j < 4; j++) { check += fabs(input_r[i * 4 + j] - vsip_real_f(vsip_cmget_f(view,i,j))); check += fabs(input_i[i * 4 + j] - vsip_imag_f(vsip_cmget_f(view,i,j))); } } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_cvdestroy_f(all); vsip_cmdestroy_f(view); vsip_cblockdestroy_f(block); } { /* check col copy split*/ vsip_cblock_f *block = vsip_cblockcreate_f(200,VSIP_MEM_NONE); vsip_scalar_f input_r[20]={0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4}; vsip_scalar_f input_i[20]={0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3}; vsip_cmview_f *view = vsip_cmbind_f(block,100,2,5,12,4); vsip_cvview_f *all = vsip_cvbind_f(block,0,1,200); vsip_scalar_f check = 0; vsip_cvfill_f(vsip_cmplx_f(-1,-1),all); vsip_cmcopyfrom_user_f(input_r,input_i,VSIP_COL,view); printf("check col copy split\n"); VU_cmprintm_f("3.2",view); for(j=0; j<4; j++) { for(i=0; i < 5; i++) { check += fabs(input_r[i + j * 5] - vsip_real_f(vsip_cmget_f(view,i,j))); check += fabs(input_i[i + j * 5] - vsip_imag_f(vsip_cmget_f(view,i,j))); } } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_cvdestroy_f(all); vsip_cmdestroy_f(view); vsip_cblockdestroy_f(block); } return; } <file_sep>/* Created <NAME> 18, 2012 */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"vsip.h" #include"VI_mrealview_f.h" #include"VI_mcopy_f_f.h" void vsip_mreal_f(const vsip_cmview_f* a, const vsip_mview_f* r){ vsip_mview_f R; VI_mrealview_f(a,&R); VI_mcopy_f_f(&R,r); } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cvouter_covariance_d.h,v 2.1 2004/05/16 05:02:34 judd Exp $ */ #include"VU_cmprintm_d.include" #include"VU_cvprintm_d.include" static void cvouter_covariance_d(void){ printf("********\nTEST cvouter_d\n"); { vsip_cscalar_d alpha = vsip_cmplx_d(4.0,0.0); vsip_scalar_d data_a_r[] = { 1.1, 1.2, 2.1, 2.2, -3.1, -3.3}; vsip_scalar_d data_a_i[] = { -1.1, -2.2, -3.1, -4.2, 0.1, -2.3}; vsip_cblock_d *block_a = vsip_cblockbind_d(data_a_r,data_a_i,6,VSIP_MEM_NONE); vsip_cvview_d *a = vsip_cvbind_d(block_a,0,1,6); vsip_cmview_d *ansm = vsip_cmcreate_d(6,6,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *chk = vsip_cmcreate_d(6,6,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *R = vsip_cmcreate_d(6,6,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *chk_i = vsip_mimagview_d(chk); vsip_cblockadmit_d(block_a,VSIP_TRUE); { /* make the answer matrix */ vsip_index i,j; for(i=0; i< vsip_cvgetlength_d(a); i++){ vsip_cscalar_d a1 = vsip_cvget_d(a,i); vsip_cmput_d(ansm,i,i,vsip_cmplx_d(vsip_cmagsq_d(a1),0)); for(j=i+1; j<vsip_cvgetlength_d(a); j++){ vsip_cscalar_d a2 = vsip_cmul_d(a1,vsip_conj_d(vsip_cvget_d(a,j))); vsip_cmput_d(ansm,i,j,a2); vsip_cmput_d(ansm,j,i,vsip_conj_d(a2)); } } vsip_rscmmul_d(4.0,ansm,ansm); } printf("vsip_cvouter_d(alpha,a,a,R)\n"); vsip_cvouter_d(alpha,a,a,R); printf("alpha = (%f %+fi) \n",vsip_real_d(alpha),vsip_imag_d(alpha)); printf("vector a\n");VU_cvprintm_d("8.6",a); printf("matrix R\n");VU_cmprintm_d("8.6",R); printf("right answer\n");VU_cmprintm_d("8.4",ansm); vsip_cmsub_d(R,ansm,chk); vsip_cmmag_d(chk,chk_i); vsip_mclip_d(chk_i,.0001,.0001,0,1,chk_i); if(vsip_msumval_d(chk_i) > .5) printf("error\n"); else printf("correct\n"); vsip_cvalldestroy_d(a); vsip_cmalldestroy_d(R); vsip_mdestroy_d(chk_i); vsip_cmalldestroy_d(chk); vsip_cmalldestroy_d(ansm); } return; } <file_sep>import pyJvsip as pjv L = 9 a=pjv.create('vview_f',L); b=a.empty ab_bl=pjv.create('vview_bl',L); a.ramp(-2.0,1) b.ramp(2.0,-1) print('index A B\n') for i in range(L): print('%3i %7.1f %7.1f\n'%(i,a[i],b[i])) _=pjv.leq(a,b,ab_bl) if ab_bl.anytrue: ab_vi=ab_bl.indexbool for i in range(ab_vi.length): print('A = B at index %3i\n'%int(ab_vi[i])) else: print('No true cases') <file_sep>// // Elementwise.swift // SwiftVsip // // Created by <NAME> on 9/3/16. // Copyright © 2016 <NAME>. All rights reserved. // import Cocoa import vsip public final class Vsip { fileprivate static func sizeEqual(_ check: Vector, against: Vector) -> Bool{ return check.length == against.length } fileprivate static func sizeEqual(_ check: Matrix, against: Matrix) -> Bool{ return (check.rowLength == against.rowLength && check.columnLength == against.columnLength) } // MARK: Conversion to String and Print public static func scalarString(_ format : String, value : Scalar) -> String{ var retval = "" switch value.type{ case .f: let fmt = "%" + format + "f" retval = String(format: fmt, value.realf) case .d: let fmt = "%" + format + "f" retval = String(format: fmt, value.reald) case .cf: let fmt1 = "%" + format + "f" let fmt2 = "%+" + format + "f" let r = String(format: fmt1, value.realf) let i = String(format: fmt2, value.imagf) retval = r + i + "i" case .cd: let fmt1 = "%" + format + "f" let fmt2 = "%+" + format + "f" let r = String(format: fmt1, value.reald) let i = String(format: fmt2, value.imagd) retval = r + i + "i" case .mi: let fmt1 = "(%d," let fmt2 = " %d)" let r = String(format: fmt1, value.row) let c = String(format: fmt2, value.col) retval = r + c default: let fmt = "%d" retval = String(format: fmt, value.int) } return retval } public static func formatFmt(_ fmt: String) -> String{ var retval = "" func charCheck(_ char: Character) -> Bool { let validChars = "0123456789." for item in validChars{ if char == item { return true } } return false } for char in fmt{ if charCheck(char){ retval.append(char) } } return retval } // MARK: - Scalar public struct Scalar { var value: (Block.Types?, NSNumber?, NSNumber?) public init(_ type: Block.Types,_ valueOne: NSNumber?,_ valueTwo: NSNumber?){ value.0 = type value.1 = valueOne value.2 = valueTwo } public init(_ value: Double){ self.value.0 = .d self.value.1 = NSNumber(value: value) self.value.2 = nil } public init(_ value: Float){ self.value.0 = .f self.value.1 = NSNumber(value: value) self.value.2 = nil } public init(_ value: Int){ self.value.0 = .i self.value.1 = NSNumber(value: value) self.value.2 = nil } public init(_ value: vsip_cscalar_d){ self.value.0 = .cd self.value.1 = NSNumber(value: value.r) self.value.2 = NSNumber(value: value.i) } public init(_ value: vsip_cscalar_f){ self.value.0 = .cf self.value.1 = NSNumber(value: value.r) self.value.2 = NSNumber(value: value.i) } public init(_ value: vsip_scalar_mi){ self.value.0 = .mi self.value.1 = NSNumber(value: value.r) self.value.2 = NSNumber(value: value.c) } public init(_ value: vsip_scalar_i){ self.value.0 = .i self.value.1 = NSNumber(value: value) self.value.2 = nil } public init(_ value: vsip_scalar_vi){ self.value.0 = .vi self.value.1 = NSNumber(value: value) self.value.2 = nil } public init(_ value: vsip_scalar_si){ self.value.0 = .si self.value.1 = NSNumber(value: value) self.value.2 = nil } public init(_ value: vsip_scalar_uc){ self.value.0 = .uc self.value.1 = NSNumber(value: value) self.value.2 = nil } public var type: Block.Types { return value.0! } public var realf: Float{ return Float((value.1?.floatValue)!) } public var reald: Double{ return Double((value.1?.doubleValue)!) } public var imagf: Float{ if let i = value.2 { return i.floatValue } else { return 0.0 } } public var imagd: Double{ if let i = value.2 { return i.doubleValue } else { return 0.0 } } public var int: Int{ return Int((value.1?.intValue)!) } public var row: Int{ return Int((value.1?.intValue)!) } public var col: Int{ return Int((value.2?.intValue)!) } public var cmplxf: Scalar{ var c = vsip_cmplx_f(vsip_scalar_f(0.0),(0.0)) if let r = value.1 { c.r = vsip_scalar_f(r.floatValue) } if let i = value.2 { c.i = vsip_scalar_f(i.floatValue) } return Scalar(c) } public var cmplxd: Scalar{ var c = vsip_cmplx_d(vsip_scalar_d(0.0),vsip_scalar_d(0.0)) if let r = value.1 { c.r = vsip_scalar_d(r.doubleValue) } if let i = value.2 { c.i = vsip_scalar_d(i.doubleValue) } return Scalar(c) } public var vsip_f: vsip_scalar_f { return vsip_scalar_f((value.1?.floatValue)!) } public var vsip_d: vsip_scalar_d { return vsip_scalar_d((value.1?.doubleValue)!) } public var vsip_cf: vsip_cscalar_f { var c = vsip_cmplx_f(vsip_scalar_f(0.0),vsip_scalar_f(0.0)) if let r = value.1 { c.r = vsip_scalar_f(r.floatValue) } if let i = value.2 { c.i = vsip_scalar_f(i.floatValue) } return c } public var vsip_cd: vsip_cscalar_d { var c = vsip_cmplx_d(vsip_scalar_d(0.0),vsip_scalar_d(0.0)) if let r = value.1 { c.r = vsip_scalar_d(r.doubleValue) } if let i = value.2 { c.i = vsip_scalar_d(i.doubleValue) } return c } public var vsip_i: vsip_scalar_i{ return vsip_scalar_i((value.1?.int32Value)!) } public var vsip_li: vsip_scalar_li{ return vsip_scalar_li((value.1?.intValue)!) } public var vsip_vi: vsip_scalar_vi{ return vsip_scalar_vi((value.1?.uintValue)!) } public var vsip_si: vsip_scalar_si{ return vsip_scalar_si((value.1?.int16Value)!) } public var vsip_uc: vsip_scalar_uc{ return vsip_scalar_uc((value.1?.uint8Value)!) } public var vsip_mi: vsip_scalar_mi{ var i = vsip_matindex(vsip_scalar_vi(0), vsip_scalar_vi(0)) if let row = value.1 { i.r = vsip_scalar_vi(row.uintValue) } if let col = value.2 { i.c = vsip_scalar_vi(col.uintValue) } return i } public static func + (left: Scalar, right: Scalar) -> Scalar { switch (left.type, right.type) { case (.f, .f): return Scalar( left.realf + right.realf) case (.d, .d): return Scalar( left.reald + right.reald) case (.cf, .f): return Scalar(vsip_cmplx_f(left.realf + right.realf, left.imagf)) case (.cd, .d): return Scalar(vsip_cmplx_d(left.reald + right.reald, left.imagd)) case (.f, .cf): return Scalar(vsip_cmplx_f(left.realf + right.realf, right.imagf)) case (.d, .cd): return Scalar(vsip_cmplx_d(left.reald + right.reald, right.imagd)) case(.cf, .cf): return Scalar(vsip_cmplx_f(left.realf + right.realf, left.imagf + right.imagf)) case(.cd, .cd): return Scalar(vsip_cmplx_d(left.reald + right.reald, left.imagd + right.imagd)) default: preconditionFailure("Vsip Scalar types (\(left.type), \(right.type)) not supported for +") } } public static func * (left: Scalar, right: Scalar) -> Scalar { switch (left.type, right.type) { case (.f, .f): return Scalar( left.realf * right.realf) case (.d, .d): return Scalar( left.reald * right.reald) case (.cf, .f): return Scalar(vsip_rcmul_f(right.vsip_f, left.vsip_cf)) case (.cd, .d): return Scalar(vsip_rcmul_d(right.vsip_d, left.vsip_cd)) case (.f, .cf): return Scalar(vsip_rcmul_f(left.vsip_f, right.vsip_cf)) case (.d, .cd): return Scalar(vsip_rcmul_d(left.vsip_d, right.vsip_cd)) case(.cf, .cf): return Scalar(vsip_cmul_f(left.vsip_cf, right.vsip_cf)) case(.cd, .cd): return Scalar(vsip_cmul_d(left.vsip_cd, right.vsip_cd)) default: preconditionFailure("Vsip Scalar types (\(left.type), \(right.type)) not supported for *") } } public static func - (left: Scalar, right: Scalar) -> Scalar { switch (left.type, right.type) { case (.f, .f): return Scalar( left.realf - right.realf) case (.d, .d): return Scalar( left.reald - right.reald) case (.cf, .f): return Scalar(vsip_cmplx_f(left.realf - right.realf, left.imagf)) case (.cd, .d): return Scalar(vsip_cmplx_d(left.reald - right.reald, left.imagd)) case (.f, .cf): return Scalar(vsip_cmplx_f(left.realf - right.realf, -right.imagf)) case (.d, .cd): return Scalar(vsip_cmplx_d(left.reald - right.reald, -right.imagd)) case(.cf, .cf): return Scalar(vsip_cmplx_f(left.realf - right.realf, left.imagf - right.imagf)) case(.cd, .cd): return Scalar(vsip_cmplx_d(left.reald - right.reald, left.imagd - right.imagd)) case(.f, .i): return Scalar( left.realf - right.realf) case(.i, .f): return Scalar( left.realf - right.realf) case(.d, .i): return Scalar( left.reald - right.reald) case(.i, .d): return Scalar( left.reald - right.reald) default: preconditionFailure("Vsip Scalar types (\(left.type), \(right.type)) not supported for - ") } } public var sqrt: Scalar { switch self.type { case .f: return Scalar(sqrtf(self.realf)) case .d: let x = Foundation.sqrt(self.reald) return Scalar(x) case .cf: return Scalar(vsip_csqrt_f(self.vsip_cf)) case .cd: return Scalar(vsip_csqrt_d(self.vsip_cd)) default: preconditionFailure("sqrt not supported for type \(self.type)") } } public func string(format fmt: String) -> String { return Vsip.scalarString(Vsip.formatFmt(fmt), value:self) } } // MARK: - Support Classes // // An instance of JVSIP class is stored in every VSIP object. // The first time it is called it will call vsip_init // When the garbage collector has collected the last one vsip_finalize is called // The reference count is kept as a class variable class JVSIP { static var vsipInit : UInt = 0 static var num = NSNumber(value: 0 as Int32) var myId: NSNumber fileprivate func initInc() { JVSIP.vsipInit += 1; } fileprivate func initDec() { JVSIP.vsipInit -= 1; } fileprivate func vsipInitGTzero() -> Bool{ if JVSIP.vsipInit > 0{ return true } else { return false } } fileprivate func vsipInitEQzero() -> Bool{ if JVSIP.vsipInit == 0{ return true } else { return false } } init() { self.myId = JVSIP.num if self.vsipInitGTzero(){ self.initInc() } else { let jInit = vsip_init(nil) if jInit != 0 { print("vsip_init failed; returned \(jInit)") } if _isDebugAssertConfiguration(){ print("called vsip_init") } self.initInc() } let n = JVSIP.num.int32Value + 1 JVSIP.num = NSNumber(value: n as Int32) self.myId = JVSIP.num if _isDebugAssertConfiguration(){ print("called jinit id \(self.myId)") } } deinit{ self.initDec() if self.vsipInitEQzero(){ vsip_finalize(nil) if _isDebugAssertConfiguration(){ print("called vsip_finalize") } } } } // MARK: - Block Class public class Block { public enum Types: String{ case f case d case cf case cd case si case i case li case uc case vi case mi case bl } fileprivate class Block_f{ var vsip : OpaquePointer? let owner = true let jInit : JVSIP let precision = "f" let depth = "r" init(length : Int){ self.vsip = vsip_blockcreate_f(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_blockdestroy_f(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_f id \(jInit.myId.int32Value)") } } } fileprivate class DBlock_f{ // Derived Block var vsip : OpaquePointer? var parent : Block let owner = false let precision = "f" let depth = "r" let jInit : JVSIP init(block : Block, cVsipDerivedBlock : OpaquePointer){ self.parent = block self.vsip = cVsipDerivedBlock jInit = JVSIP() } deinit{ vsip_blockdestroy_f(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_f (derived) id \(jInit.myId.int32Value)") } } } fileprivate class Block_d{ var vsip : OpaquePointer? let owner = true let jInit : JVSIP let precision = "d" let depth = "r" init(length : Int){ self.vsip = vsip_blockcreate_d(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_blockdestroy_d(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_d id \(jInit.myId.int32Value)") } } } fileprivate class DBlock_d{ var vsip : OpaquePointer? var parent : Block let owner = false let precision = "f" let depth = "r" let jInit : JVSIP init(block : Block, cVsipDerivedBlock : OpaquePointer){ self.parent = block self.vsip = cVsipDerivedBlock jInit = JVSIP() } deinit{ vsip_blockdestroy_d(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_d (derived) id \(jInit.myId.int32Value)") } } } fileprivate class Block_cf{ var vsip : OpaquePointer? let jInit : JVSIP let precision = "f" let depth = "c" init(length : Int){ self.vsip = vsip_cblockcreate_f(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_cblockdestroy_f(self.vsip!) if _isDebugAssertConfiguration(){ print("cblockdestroy_f id \(jInit.myId.int32Value)") } } } fileprivate class Block_cd{ var vsip : OpaquePointer? let jInit : JVSIP let precision = "f" let depth = "r" init(length : Int){ self.vsip = vsip_cblockcreate_d(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_cblockdestroy_d(self.vsip!) if _isDebugAssertConfiguration(){ print("cblockdestroy_d id \(jInit.myId.int32Value)") } } } fileprivate class Block_vi{ var vsip : OpaquePointer? let jInit : JVSIP let precision = "vi" let depth = "r" init(length : Int){ self.vsip = vsip_blockcreate_vi(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_blockdestroy_vi(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_vi id \(jInit.myId.int32Value)") } } } fileprivate class Block_si{ var vsip : OpaquePointer? let jInit : JVSIP let precision = "si" let depth = "r" init(length : Int){ self.vsip = vsip_blockcreate_si(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_blockdestroy_si(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_si id \(jInit.myId.int32Value)") } } } fileprivate class Block_i{ var vsip : OpaquePointer? let jInit : JVSIP let precision = "i" let depth = "r" init(length : Int){ self.vsip = vsip_blockcreate_i(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_blockdestroy_i(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_i id \(jInit.myId.int32Value)") } } } fileprivate class Block_li{ var vsip : OpaquePointer? let jInit : JVSIP let precision = "li" let depth = "r" init(length : Int){ self.vsip = vsip_blockcreate_li(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_blockdestroy_li(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_li id \(jInit.myId.int32Value)") } } } fileprivate class Block_bl{ var vsip : OpaquePointer? let jInit : JVSIP let precision = "bool" let depth = "r" init(length : Int){ self.vsip = vsip_blockcreate_bl(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_blockdestroy_bl(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_bl id \(jInit.myId.int32Value)") } } } fileprivate class Block_uc{ var vsip : OpaquePointer? let jInit : JVSIP let precision = "uc" let depth = "r" init(length : Int){ self.vsip = vsip_blockcreate_uc(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_blockdestroy_uc(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_uc id \(jInit.myId.int32Value)") } } } fileprivate class Block_mi{ var vsip : OpaquePointer? let jInit : JVSIP let precision = "vi" let depth = "m" init(length : Int){ self.vsip = vsip_blockcreate_mi(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_blockdestroy_mi(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_mi id \(jInit.myId.int32Value)") } } } // MARK: Block Attributes fileprivate(set) public var type: Block.Types fileprivate(set) var jVsip : AnyObject? fileprivate(set) public var length : Int fileprivate var owner = true var myId : NSNumber? // create normal block public init(length : Int, type : Block.Types){ switch type { case .f: let b = Block_f(length : length) jVsip = b self.myId = b.jInit.myId case .d: let b = Block_d(length : length) jVsip = b self.myId = b.jInit.myId case .cf: let b = Block_cf(length : length) jVsip = b self.myId = b.jInit.myId case .cd: let b = Block_cd(length : length) jVsip = b self.myId = b.jInit.myId case .i: let b = Block_i(length : length) jVsip = b self.myId = b.jInit.myId case .li: let b = Block_li(length : length) jVsip = b self.myId = b.jInit.myId case .si: let b = Block_si(length : length) jVsip = b self.myId = b.jInit.myId case .uc: let b = Block_uc(length : length) jVsip = b self.myId = b.jInit.myId case .vi: let b = Block_vi(length : length) jVsip = b self.myId = b.jInit.myId case .mi: let b = Block_mi(length : length) jVsip = b self.myId = b.jInit.myId case .bl: let b = Block_bl(length : length) jVsip = b self.myId = b.jInit.myId } self.length = length self.type = type } // create special block for derived blocks public init(block : Block, cVsipDerivedBlock : OpaquePointer){ self.length = block.length self.owner = false switch block.type{ case .cf: let b = DBlock_f(block: block, cVsipDerivedBlock: cVsipDerivedBlock) jVsip = b type = Block.Types.f myId = b.jInit.myId case .cd: let b = DBlock_d(block: block, cVsipDerivedBlock: cVsipDerivedBlock) jVsip = b type = Block.Types.d myId = b.jInit.myId default: jVsip = nil type = block.type } } // Vector bind returns vsip object (may be null on malloc failure) var vsip: OpaquePointer?{ switch self.type { case .f: let blk = self.jVsip as! Block_f if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } case .d: let blk = self.jVsip as! Block_d if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } case .cf: let blk = self.jVsip as! Block_cf if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } case .cd: let blk = self.jVsip as! Block_cd if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } case .i: let blk = self.jVsip as! Block_i if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } case .li: let blk = self.jVsip as! Block_li if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } case .si: let blk = self.jVsip as! Block_si if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } case .uc: let blk = self.jVsip as! Block_uc if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } case .vi: let blk = self.jVsip as! Block_vi if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } case .mi: let blk = self.jVsip as! Block_mi if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } case .bl: let blk = self.jVsip as! Block_bl if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } } } // Return JVSIP Swift View object. Allows block.bind for shape vector public func bind(_ offset : Int, stride : Int, length : Int) -> Vector { return Vector(block: self, offset: offset, stride: stride, length: length) } // Return JVSIP Swift View object. Allows block.bind for shape matrix public func bind(_ offset : Int, columnStride : Int, columnLength : Int, rowStride : Int, rowLength : Int) -> Matrix { return Matrix(block: self, offset: offset, columnStride: columnStride, columnLength: columnLength, rowStride: rowStride, rowLength: rowLength) } public func vector() -> Vector{ return self.bind(0, stride: 1, length: self.length) } } public class View: NSObject { public enum Shape: String { case v // vector case m // matrix } let block: Block let shape : Shape public var type: Block.Types{ return block.type } let jInit : JVSIP var myId = NSNumber(value: 0 as Int32) // Used to initialize a derived JVSIP View object public init(block: Block, shape: View.Shape){ self.block = block self.shape = shape jInit = JVSIP() myId = jInit.myId super.init() } func real(_ vsip: OpaquePointer) -> (Block, OpaquePointer){ let t = (self.type, self.shape) switch t{ case (.cf, .v): if let cRealView = vsip_vrealview_f(vsip) { let blk = vsip_vgetblock_f(cRealView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cRealView) } else { break } case(.cf, .m): if let cRealView = vsip_mrealview_f(vsip){ let blk = vsip_mgetblock_f(cRealView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cRealView) } else { break } case (.cd, .v): if let cRealView = vsip_vrealview_d(vsip){ let blk = vsip_vgetblock_d(cRealView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cRealView) } else { break } case (.cd, .m): if let cRealView = vsip_mrealview_d(vsip){ let blk = vsip_mgetblock_d(cRealView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cRealView) } else { break } default: print("Case not found") break } preconditionFailure("Failure of imag method") } public func imag(_ vsip: OpaquePointer) -> (Block?, OpaquePointer?){ let t = (self.type, self.shape) switch t{ case (.cf, .v): if let cImagView = vsip_vimagview_f(vsip){ let blk = vsip_vgetblock_f(cImagView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cImagView) } else { break } case(.cf, .m): if let cImagView = vsip_mimagview_f(vsip){ let blk = vsip_mgetblock_f(cImagView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cImagView) } else { break } case (.cd, .v): if let cImagView = vsip_vimagview_d(vsip){ let blk = vsip_vgetblock_d(cImagView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cImagView) } else { break } case (.cd, .m): if let cImagView = vsip_mimagview_d(vsip){ let blk = vsip_mgetblock_d(cImagView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cImagView) } else { break } default: print("Case not found") break } preconditionFailure("Failure of imag method") } // MARK: Attribute get/put options public func get(_ vsip:OpaquePointer, index: vsip_index) -> Scalar { let t = self.type switch t{ case .f: return Scalar(vsip_vget_f(vsip, index)) case .d: return Scalar(vsip_vget_d(vsip, index)) case .cf: return Scalar(vsip_cvget_f(vsip, index)) case .cd: return Scalar(vsip_cvget_d(vsip, index)) case .vi: return Scalar(vsip_vget_vi(vsip, index)) case .mi: return Scalar(vsip_vget_mi(vsip,index)) case .li: return Scalar(vsip_vget_li(vsip, index)) case .i: return Scalar(vsip_vget_i(vsip, index)) case .si: return Scalar(vsip_vget_si(vsip, index)) case .uc: return Scalar(vsip_vget_uc(vsip, index)) default: preconditionFailure("No Scalar Found for this case") } } public func get(_ vsip:OpaquePointer, rowIndex: vsip_index, columnIndex: vsip_index) -> Scalar { let t = self.type switch t{ case .f: return Scalar(vsip_mget_f(vsip, rowIndex, columnIndex)) case .d: return Scalar(vsip_mget_d(vsip, rowIndex, columnIndex)) case .cf: return Scalar(vsip_cmget_f(vsip, rowIndex, columnIndex)) case .cd: return Scalar(vsip_cmget_d(vsip,rowIndex, columnIndex)) case .li: return Scalar(vsip_mget_li(vsip,rowIndex, columnIndex)) case .i: return Scalar(vsip_mget_i(vsip,rowIndex, columnIndex)) case .si: return Scalar(vsip_mget_si(vsip,rowIndex, columnIndex)) case .uc: return Scalar(vsip_mget_uc(vsip,rowIndex, columnIndex)) default: preconditionFailure("No Scalar Found for this case") } } public func put(_ vsip:OpaquePointer, index: vsip_index, value: Scalar){ let t = self.type switch t{ case .f: vsip_vput_f(vsip, index, value.vsip_f) case .d: vsip_vput_d(vsip, index, value.vsip_d) case .cf: vsip_cvput_f(vsip,index,value.vsip_cf) case .cd: vsip_cvput_d(vsip,index,value.vsip_cd) case .vi: vsip_vput_vi(vsip,index,value.vsip_vi) case .mi: vsip_vput_mi(vsip,index,value.vsip_mi) case .li: vsip_vput_li(vsip, index, value.vsip_li) case .i: vsip_vput_i(vsip,index,value.vsip_i) case .si: vsip_vput_si(vsip,index,value.vsip_si) case .uc: vsip_vput_uc(vsip,index,value.vsip_uc) default: preconditionFailure("No Scalar Found for this case") } } public func put(_ vsip:OpaquePointer, rowIndex: vsip_index, columnIndex: vsip_index, value: Scalar){ let t = self.type switch t{ case .f: vsip_mput_f(vsip, rowIndex, columnIndex, value.vsip_f) case .d: vsip_mput_d(vsip, rowIndex, columnIndex, value.vsip_d) case .cf: vsip_cmput_f(vsip, rowIndex, columnIndex,value.vsip_cf) case .cd: vsip_cmput_d(vsip, rowIndex, columnIndex,value.vsip_cd) case .li: vsip_mput_li(vsip, rowIndex, columnIndex, value.vsip_li) case .i: vsip_mput_i(vsip, rowIndex, columnIndex,value.vsip_i) case .si: vsip_mput_si(vsip, rowIndex, columnIndex,value.vsip_si) case .uc: vsip_mput_uc(vsip, rowIndex, columnIndex,value.vsip_uc) default: preconditionFailure("No Scalar Found for this case") } } } // MARK: - Vector Class public class Vector : View, Sequence, NSTableViewDataSource { public func numberOfRows(in tableView: NSTableView) -> Int { return self.length } public func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? { return self[row] } public func tableView(_ tableView: NSTableView, setObjectValue object: Any?, for tableColumn: NSTableColumn?, row: Int) { self[row] = object as! Vsip.Scalar } fileprivate var tryVsip: OpaquePointer? = nil public var vsip: OpaquePointer { get { return tryVsip! } } public func makeIterator() -> AnyIterator<Vsip.Scalar> { var vindex = 0 return AnyIterator { let nextIndex = vindex guard vindex < self.length else { return nil } vindex += 1 // return DSPDoubleComplex(real: self.rdata[nextIndex], imag: self.idata[nextIndex]) return self[nextIndex] } } // vector bind private func vBind(_ offset : Int, stride : Int, length : Int) -> OpaquePointer? { let blk = self.block.vsip let t = self.block.type switch t { case .f: return vsip_vbind_f(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .d: return vsip_vbind_d(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .cf: return vsip_cvbind_f(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .cd: return vsip_cvbind_d(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .i: return vsip_vbind_i(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .li: return vsip_vbind_li(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .si: return vsip_vbind_si(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .uc: return vsip_vbind_uc(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .vi: return vsip_vbind_vi(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .mi: return vsip_vbind_mi(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .bl: return vsip_vbind_bl(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) } } public init(block: Block, offset: Int, stride: Int, length: Int){ super.init(block: block, shape: .v) if let v = self.vBind(offset, stride: stride, length: length){ self.tryVsip = v } else { preconditionFailure("Failed to bind to a vsip vector") } } // vector create public convenience init(length : Int, type : Block.Types){ let blk = Block(length: length, type: type) self.init(block: blk, offset: 0, stride: 1, length: length) } // create view to hold derived subview public init(block: Block, cView: OpaquePointer){ super.init(block: block, shape: .v) self.tryVsip = cView } deinit{ let t = self.block.type let id = self.myId.int32Value switch t { case .f: vsip_vdestroy_f(self.vsip) if _isDebugAssertConfiguration(){ print("vdestroy_f id \(id)") } case .d: vsip_vdestroy_d(self.vsip) if _isDebugAssertConfiguration(){ print("vdestroy_d id \(id)") } case .cf: vsip_cvdestroy_f(self.vsip) if _isDebugAssertConfiguration(){ print("cvdestroy_f id \(id)") } case .cd: vsip_cvdestroy_d(self.vsip) if _isDebugAssertConfiguration(){ print("cvdestroy_d id \(id)") } case .i: vsip_vdestroy_i(self.vsip) if _isDebugAssertConfiguration(){ print("vdestroy_i id \(id)") } case .li: vsip_vdestroy_li(self.vsip) if _isDebugAssertConfiguration(){ print("vdestroy_li id \(id)") } case .si: vsip_vdestroy_si(self.vsip) if _isDebugAssertConfiguration(){ print("vdestroy_si id \(id)") } case .uc: vsip_vdestroy_uc(self.vsip) if _isDebugAssertConfiguration(){ print("vdestroy_uc id \(id)") } case .vi: vsip_vdestroy_vi(self.vsip) if _isDebugAssertConfiguration(){ print("vdestroy_vi id \(id)") } case .mi: vsip_vdestroy_mi(self.vsip) if _isDebugAssertConfiguration(){ print("vdestroy_mi id \(id)") } case .bl: vsip_vdestroy_bl(self.vsip) if _isDebugAssertConfiguration(){ print("vdestroy_bl id \(id)") } } } // MARK: Attributes public var offset: Int { get{ switch self.type { case .f : return Int(vsip_vgetoffset_f(self.vsip)) case .d : return Int(vsip_vgetoffset_d(self.vsip)) case .cf : return Int(vsip_cvgetoffset_f(self.vsip)) case .cd : return Int(vsip_cvgetoffset_d(self.vsip)) case .si : return Int(vsip_vgetoffset_si(self.vsip)) case .i : return Int(vsip_vgetoffset_i(self.vsip)) case .li : return Int(vsip_vgetoffset_li(self.vsip)) case .uc : return Int(vsip_vgetoffset_uc(self.vsip)) case .vi : return Int(vsip_vgetoffset_vi(self.vsip)) case .mi : return Int(vsip_vgetoffset_mi(self.vsip)) case .bl : return Int(vsip_vgetoffset_bl(self.vsip)) } } set(offset){ switch self.type { case .f : vsip_vputoffset_f(self.vsip, vsip_offset(offset)) case .d : vsip_vputoffset_d(self.vsip, vsip_offset(offset)) case .cf : vsip_cvputoffset_f(self.vsip, vsip_offset(offset)) case .cd : vsip_cvputoffset_d(self.vsip, vsip_offset(offset)) case .si : vsip_vputoffset_si(self.vsip, vsip_offset(offset)) case .i : vsip_vputoffset_i(self.vsip, vsip_offset(offset)) case .li : vsip_vputoffset_li(self.vsip, vsip_offset(offset)) case .uc : vsip_vputoffset_uc(self.vsip, vsip_offset(offset)) case .mi : vsip_vputoffset_mi(self.vsip, vsip_offset(offset)) case .vi : vsip_vputoffset_vi(self.vsip, vsip_offset(offset)) case .bl : vsip_vputoffset_bl(self.vsip, vsip_offset(offset)) } } } public var stride: Int { get{ switch self.type { case .f : return Int(vsip_vgetstride_f(self.vsip)) case .d : return Int(vsip_vgetstride_d(self.vsip)) case .cf : return Int(vsip_cvgetstride_f(self.vsip)) case .cd : return Int(vsip_cvgetstride_d(self.vsip)) case .si : return Int(vsip_vgetstride_si(self.vsip)) case .i : return Int(vsip_vgetstride_i(self.vsip)) case .li : return Int(vsip_vgetstride_li(self.vsip)) case .uc : return Int(vsip_vgetstride_uc(self.vsip)) case .vi : return Int(vsip_vgetstride_vi(self.vsip)) case .mi : return Int(vsip_vgetstride_mi(self.vsip)) case .bl : return Int(vsip_vgetstride_bl(self.vsip)) } } set(stride){ switch self.type { case .f : vsip_vputstride_f(self.vsip, vsip_stride(stride)) case .d : vsip_vputstride_d(self.vsip, vsip_stride(stride)) case .cf : vsip_cvputstride_f(self.vsip, vsip_stride(stride)) case .cd : vsip_cvputstride_d(self.vsip, vsip_stride(stride)) case .si : vsip_vputstride_si(self.vsip, vsip_stride(stride)) case .i : vsip_vputstride_i(self.vsip, vsip_stride(stride)) case .li : vsip_vputstride_li(self.vsip, vsip_stride(stride)) case .uc : vsip_vputstride_uc(self.vsip, vsip_stride(stride)) case .mi : vsip_vputstride_mi(self.vsip, vsip_stride(stride)) case .vi : vsip_vputstride_vi(self.vsip, vsip_stride(stride)) case .bl : vsip_vputstride_bl(self.vsip, vsip_stride(stride)) } } } public var length: Int { get{ switch self.type { case .f : return Int(vsip_vgetlength_f(self.vsip)) case .d : return Int(vsip_vgetlength_d(self.vsip)) case .cf : return Int(vsip_cvgetlength_f(self.vsip)) case .cd : return Int(vsip_cvgetlength_d(self.vsip)) case .si : return Int(vsip_vgetlength_si(self.vsip)) case .i : return Int(vsip_vgetlength_i(self.vsip)) case .li : return Int(vsip_vgetlength_li(self.vsip)) case .uc : return Int(vsip_vgetlength_uc(self.vsip)) case .vi : return Int(vsip_vgetlength_vi(self.vsip)) case .mi : return Int(vsip_vgetlength_mi(self.vsip)) case .bl : return Int(vsip_vgetlength_bl(self.vsip)) } } set(length){ switch self.type { case .f : vsip_vputlength_f(self.vsip, vsip_length(length)) case .d : vsip_vputlength_d(self.vsip, vsip_length(length)) case .cf : vsip_cvputlength_f(self.vsip, vsip_length(length)) case .cd : vsip_cvputlength_d(self.vsip, vsip_length(length)) case .si : vsip_vputlength_si(self.vsip, vsip_length(length)) case .i : vsip_vputlength_i(self.vsip, vsip_length(length)) case .li : vsip_vputlength_li(self.vsip, vsip_length(length)) case .uc : vsip_vputlength_uc(self.vsip, vsip_length(length)) case .mi : vsip_vputlength_mi(self.vsip, vsip_length(length)) case .vi : vsip_vputlength_vi(self.vsip, vsip_length(length)) case .bl : vsip_vputlength_bl(self.vsip, vsip_length(length)) } } } // MARK: sub views public var real: Vector{ get{ let ans = super.real(self.vsip) // C VSIP real view let blk = ans.0 let v = ans.1 return Vector(block: blk, cView: v) } } public var imag: Vector{ get{ let ans = super.imag(self.vsip) // C VSIP imag view let blk = ans.0! let v = ans.1! return Vector(block: blk, cView: v) } } // vector subscript operator public subscript(index: Int) -> Scalar { get{ return super.get(self.vsip, index: vsip_index(index)) } set(value){ super.put(self.vsip, index: vsip_index(index), value: value) } } public subscript() -> Scalar{ get{ return self[0] } set(value){ self.fill(value) } } public static func + (left: Vector, right: Vector) -> Vector { let retval = left.empty Vsip.add(left, right, resultsIn: retval) return retval } public static func - (left: Vector, right: Vector) -> Vector { let retval = left.empty Vsip.sub(left, subtract: right, resultsIn: retval) return retval } // create empty vector of same type and view size. New data space created public var empty: Vector { return Vector(length: self.length, type: self.type) } public func empty(_ type: Block.Types) -> Vector { return Vector(length: self.length, type: type) } public var newCopy: Vector { let view = self.empty switch view.type{ case .f: vsip_vcopy_f_f(self.vsip,view.vsip) case .d: vsip_vcopy_d_d(self.vsip, view.vsip) case .cf: vsip_cvcopy_f_f(self.vsip,view.vsip) case .cd: vsip_cvcopy_d_d(self.vsip, view.vsip) case .i: vsip_vcopy_i_i(self.vsip,view.vsip) case .si: vsip_vcopy_si_si(self.vsip, view.vsip) case .vi: vsip_vcopy_vi_vi(self.vsip,view.vsip) case .mi: vsip_vcopy_mi_mi(self.vsip, view.vsip) default: break } return view } public func copy(_ resultsIn: Vector) -> Vector{ let t = (self.type, resultsIn.type) switch t{ case (.f,.f): vsip_vcopy_f_f(self.vsip,resultsIn.vsip) case (.f,.cf): let r = resultsIn.real;let i = resultsIn.real vsip_vcopy_f_f(self.vsip,r.vsip) vsip_vfill_f(0.0,i.vsip) case (.d,.d): vsip_vcopy_d_d(self.vsip,resultsIn.vsip) case (.d,.cd): let r = resultsIn.real;let i = resultsIn.real vsip_vcopy_d_d(self.vsip,r.vsip) vsip_vfill_d(0.0,i.vsip) case (.d,.f): vsip_vcopy_d_f(self.vsip,resultsIn.vsip) case (.f,.d): vsip_vcopy_f_d(self.vsip,resultsIn.vsip) case (.i,.f): vsip_vcopy_i_f(self.vsip,resultsIn.vsip) case (.i,.d): vsip_vcopy_i_d(self.vsip, resultsIn.vsip) case (.i,.i): vsip_vcopy_i_i(self.vsip, resultsIn.vsip) case (.i,.uc): vsip_vcopy_i_uc(self.vsip, resultsIn.vsip) case (.i,.vi): vsip_vcopy_i_vi(self.vsip, resultsIn.vsip) case (.si, .si): vsip_vcopy_si_si(self.vsip, resultsIn.vsip) case (.si, .d): vsip_vcopy_si_d(self.vsip, resultsIn.vsip) case (.si, .f): vsip_vcopy_si_f(self.vsip, resultsIn.vsip) case (.vi,.vi): vsip_vcopy_vi_vi(self.vsip, resultsIn.vsip) case (.vi, .i): vsip_vcopy_vi_i(self.vsip, resultsIn.vsip) case (.vi,.d): vsip_vcopy_vi_d(self.vsip, resultsIn.vsip) default: break } return resultsIn } public var clone: Vector { return Vector(block: self.block, offset: self.offset, stride: self.stride, length: self.length) } // MARK: Vector Data Generators public func ramp(_ start : Scalar, increment : Scalar) -> Vector { switch self.type { case .d: vsip_vramp_d(start.vsip_d, increment.vsip_d, self.vsip) case .f: vsip_vramp_f(start.vsip_f, increment.vsip_f, self.vsip) case .i: vsip_vramp_i(start.vsip_i, increment.vsip_i, self.vsip) case .si: vsip_vramp_si(start.vsip_si, increment.vsip_si, self.vsip) case .uc: vsip_vramp_uc(start.vsip_uc, increment.vsip_uc, self.vsip) case .vi: vsip_vramp_vi(start.vsip_vi, increment.vsip_vi, self.vsip) default: preconditionFailure("Type " + self.type.rawValue + " not supported for ramp") } return self } public func fill(_ value: Scalar){ switch self.type{ case .d: vsip_vfill_d(value.vsip_d, self.vsip) case .f: vsip_vfill_f(value.vsip_f, self.vsip) case .cd: vsip_cvfill_d(value.vsip_cd,self.vsip) case .cf: vsip_cvfill_f(value.vsip_cf,self.vsip) case .vi: vsip_vfill_vi(value.vsip_vi,self.vsip) case .i: vsip_vfill_i(value.vsip_i,self.vsip) case .li: vsip_vfill_li(value.vsip_li,self.vsip) case .si: vsip_vfill_si(value.vsip_si,self.vsip) case .uc: vsip_vfill_uc(value.vsip_uc,self.vsip) default: preconditionFailure("Type " + self.type.rawValue + " not supported for fill") } } public func randn(_ seed: vsip_index, portable: Bool) -> Vector { let state = Vsip.Rand(seed: seed, portable: portable) state.randn(self) return self } public func randn(_ seed: vsip_index) -> Vector { return self.randn(seed, portable: true) } public func randu(_ seed: vsip_index, portable: Bool) -> Vector{ let state = Vsip.Rand(seed: seed, portable: portable) state.randu(self) return self } public func randu(_ seed: vsip_index) -> Vector { return self.randu(seed, portable: true) } // MARK: Print public func mString(_ format: String) -> String { let fmt = Vsip.formatFmt(format) var retval = "" let n = self.length - 1 for i in 0...n { retval += (i == 0) ? "[" : " " retval += Vsip.scalarString(fmt, value: self[i]) retval += (i == n) ? "]\n" : ";\n" } return retval } public func mPrint(_ format: String){ let m = mString(format) print(m) } // MARK: Elementary Functions public func acos(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vacos_d(self.vsip, out.vsip) case .f: vsip_vacos_f(self.vsip, out.vsip) default: return out } return out } public func asin(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vasin_d(self.vsip, out.vsip) case .f: vsip_vasin_f(self.vsip, out.vsip) default: return out } return out } public func atan(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vatan_d(self.vsip, out.vsip) case .f: vsip_vatan_f(self.vsip, out.vsip) default: return out } return out } public func cos(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vcos_d(self.vsip, out.vsip) case .f: vsip_vcos_f(self.vsip, out.vsip) default: return out } return out } public func sin(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vasin_d(self.vsip, out.vsip) case .f: vsip_vasin_f(self.vsip, out.vsip) default: return out } return out } public func tan(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vtan_d(self.vsip, out.vsip) case .f: vsip_vtan_f(self.vsip, out.vsip) default: return out } return out } public func exp(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vexp_d(self.vsip, out.vsip) case .f: vsip_vexp_f(self.vsip, out.vsip) default: return out } return out } public func exp10(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vexp10_d(self.vsip, out.vsip) case .f: vsip_vexp10_f(self.vsip, out.vsip) default: return out } return out } public func log(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vlog_d(self.vsip, out.vsip) case .f: vsip_vlog_f(self.vsip, out.vsip) default: return out } return out } public func log10(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vlog10_d(self.vsip, out.vsip) case .f: vsip_vlog10_f(self.vsip, out.vsip) default: return out } return out } // Mark: - Jvsip methods Vector public func put(_ data: Double...) { for i in 0..<data.count{ self[i] = Scalar(data[i]) } } var normFro: Double { get { return (Vsip.Jvsip.normFro(view: self).reald) } } } // MARK: - Matrix Class public class Matrix : View, Sequence, NSTableViewDataSource { public func numberOfRows(in tableView: NSTableView) -> Int { return self.columnLength } fileprivate var tryVsip: OpaquePointer? public var vsip: OpaquePointer { get { return tryVsip! } } public func makeIterator() -> AnyIterator<Vsip.Vector> { var vindex = 0 return AnyIterator { let nextIndex = vindex guard vindex < self.columnLength else { return nil } vindex += 1 // return DSPDoubleComplex(real: self.rdata[nextIndex], imag: self.idata[nextIndex]) return self.row(nextIndex) } } // matrix bind // matrix create // Matrix bind returns vsip object (may be null on malloc failure) private func mBind(_ offset : Int, columnStride : Int, columnLength : Int, rowStride : Int, rowLength : Int) -> OpaquePointer? { let blk = self.block.vsip let t = self.block.type switch t{ case .f: return vsip_mbind_f(blk, vsip_offset(offset), vsip_stride(columnStride), vsip_length(columnLength), vsip_stride(rowStride), vsip_length(rowLength)) case .d: return vsip_mbind_d(blk, vsip_offset(offset), vsip_stride(columnStride), vsip_length(columnLength), vsip_stride(rowStride), vsip_length(rowLength)) case .cf: return vsip_cmbind_f(blk, vsip_offset(offset), vsip_stride(columnStride), vsip_length(columnLength), vsip_stride(rowStride), vsip_length(rowLength)) case .cd: return vsip_cmbind_d(blk, vsip_offset(offset), vsip_stride(columnStride), vsip_length(columnLength), vsip_stride(rowStride), vsip_length(rowLength)) case .i: return vsip_mbind_i(blk, vsip_offset(offset), vsip_stride(columnStride), vsip_length(columnLength), vsip_stride(rowStride), vsip_length(rowLength)) case .li: return vsip_mbind_li(blk, vsip_offset(offset), vsip_stride(columnStride), vsip_length(columnLength), vsip_stride(rowStride), vsip_length(rowLength)) case .si: return vsip_mbind_si(blk, vsip_offset(offset), vsip_stride(columnStride), vsip_length(columnLength), vsip_stride(rowStride), vsip_length(rowLength)) case .uc: return vsip_mbind_uc(blk, vsip_offset(offset), vsip_stride(columnStride), vsip_length(columnLength), vsip_stride(rowStride), vsip_length(rowLength)) case .bl: return vsip_mbind_bl(blk, vsip_offset(offset), vsip_stride(columnStride), vsip_length(columnLength), vsip_stride(rowStride), vsip_length(rowLength)) default: print("Not supported.") return nil } } public init(block: Block, offset: Int, columnStride: Int, columnLength: Int, rowStride: Int, rowLength: Int){ super.init(block: block, shape: .m) if let m = self.mBind(offset, columnStride: columnStride, columnLength: columnLength, rowStride: rowStride, rowLength: rowLength){ self.tryVsip = m } else { preconditionFailure("Failed to bind to a vsip matrix") } } public convenience init(columnLength :Int, rowLength: Int, type : Block.Types, major : vsip_major){ let N = rowLength * columnLength let blk = Block(length: N, type: type) if major == VSIP_COL { self.init(block: blk, offset: 0, columnStride: 1, columnLength: columnLength, rowStride: Int(columnLength), rowLength: rowLength) } else { self.init(block: blk, offset: 0, columnStride: Int(rowLength), columnLength: columnLength, rowStride: 1, rowLength: rowLength) } } // create view to hold derived subview public init(block: Block, cView: OpaquePointer){ super.init(block: block, shape: .m) self.tryVsip = cView } deinit{ let t = self.block.type let id = self.myId.int32Value switch t { case .f: vsip_mdestroy_f(self.vsip) if _isDebugAssertConfiguration(){ print("deinit mdestroy_f \(id)") } case .d: vsip_mdestroy_d(self.vsip) if _isDebugAssertConfiguration(){ print("deinit mdestroy_d \(id)") } case .cf: vsip_cmdestroy_f(self.vsip) if _isDebugAssertConfiguration(){ print("deinit cmdestroy_f \(id)") } case .cd: vsip_cmdestroy_d(self.vsip) if _isDebugAssertConfiguration(){ print("cmdestroy_d id \(id)") } case .i: vsip_mdestroy_i(self.vsip) if _isDebugAssertConfiguration(){ print("mdestroy_i id \(id)") } case .li: vsip_mdestroy_li(self.vsip) if _isDebugAssertConfiguration(){ print("mdestroy_li id \(id)") } case .si: vsip_mdestroy_si(self.vsip) if _isDebugAssertConfiguration(){ print("mdestroy_si id \(id)") } case .uc: vsip_mdestroy_uc(self.vsip) if _isDebugAssertConfiguration(){ print("mdestroy_uc id \(id)") } case .bl: vsip_mdestroy_bl(self.vsip) if _isDebugAssertConfiguration(){ print("mdestroy_bl id \(id)") } default: break } } // MARK: Attributes public var offset: Int { get{ switch self.type { case .f : return Int(vsip_mgetoffset_f(self.vsip)) case .d : return Int(vsip_mgetoffset_d(self.vsip)) case .cf : return Int(vsip_cmgetoffset_f(self.vsip)) case .cd : return Int(vsip_cmgetoffset_d(self.vsip)) case .si : return Int(vsip_mgetoffset_si(self.vsip)) case .i : return Int(vsip_mgetoffset_i(self.vsip)) case .li : return Int(vsip_mgetoffset_li(self.vsip)) case .uc : return Int(vsip_mgetoffset_uc(self.vsip)) case .bl : return Int(vsip_mgetoffset_bl(self.vsip)) default: return 0 } } set(offset) { switch self.type { case .f : vsip_mputoffset_f(self.vsip, vsip_offset(offset)) case .d : vsip_mputoffset_d(self.vsip, vsip_offset(offset)) case .cf : vsip_cmputoffset_f(self.vsip, vsip_offset(offset)) case .cd : vsip_cmputoffset_d(self.vsip, vsip_offset(offset)) case .si : vsip_mputoffset_si(self.vsip, vsip_offset(offset)) case .i : vsip_mputoffset_i(self.vsip, vsip_offset(offset)) case .li : vsip_mputoffset_li(self.vsip, vsip_offset(offset)) case .uc : vsip_mputoffset_uc(self.vsip, vsip_offset(offset)) case .bl : vsip_mputoffset_bl(self.vsip, vsip_offset(offset)) default: break } } } public var rowStride: Int{ get{ switch self.type { case .f : return Int(vsip_mgetrowstride_f(self.vsip)) case .d : return Int(vsip_mgetrowstride_d(self.vsip)) case .cf : return Int(vsip_cmgetrowstride_f(self.vsip)) case .cd : return Int(vsip_cmgetrowstride_d(self.vsip)) case .i : return Int(vsip_mgetrowstride_i(self.vsip)) case .si : return Int(vsip_mgetrowstride_si(self.vsip)) case .li : return Int(vsip_mgetrowstride_li(self.vsip)) default : return 0 } } set(stride){ switch self.type{ case .f : vsip_mputrowstride_f(self.vsip,vsip_stride(stride)) case .d : vsip_mputrowstride_d(self.vsip,vsip_stride(stride)) case .cf : vsip_cmputrowstride_f(self.vsip,vsip_stride(stride)) case .cd : vsip_cmputrowstride_d(self.vsip,vsip_stride(stride)) case .i : vsip_mputrowstride_i(self.vsip,vsip_stride(stride)) case .si : vsip_mputrowstride_si(self.vsip,vsip_stride(stride)) case .li : vsip_mputrowstride_li(self.vsip,vsip_stride(stride)) default : break } } } public var columnStride: Int{ get{ switch self.type { case .f : return Int(vsip_mgetcolstride_f(self.vsip)) case .d : return Int(vsip_mgetcolstride_d(self.vsip)) case .cf : return Int(vsip_cmgetcolstride_f(self.vsip)) case .cd : return Int(vsip_cmgetcolstride_d(self.vsip)) case .i : return Int(vsip_mgetcolstride_i(self.vsip)) case .si : return Int(vsip_mgetcolstride_si(self.vsip)) case .li : return Int(vsip_mgetcolstride_li(self.vsip)) default : return 0 } } set(stride){ switch self.type{ case .f : vsip_mputcolstride_f(self.vsip,vsip_stride(stride)) case .d : vsip_mputcolstride_d(self.vsip,vsip_stride(stride)) case .cf : vsip_cmputcolstride_f(self.vsip,vsip_stride(stride)) case .cd : vsip_cmputcolstride_d(self.vsip,vsip_stride(stride)) case .i : vsip_mputcolstride_i(self.vsip,vsip_stride(stride)) case .si : vsip_mputcolstride_si(self.vsip,vsip_stride(stride)) case .li : vsip_mputcolstride_li(self.vsip,vsip_stride(stride)) default : break } } } public var rowLength: Int { get{ switch self.type { case .f : return Int(vsip_mgetrowlength_f(self.vsip)) case .d : return Int(vsip_mgetrowlength_d(self.vsip)) case .cf : return Int(vsip_cmgetrowlength_f(self.vsip)) case .cd : return Int(vsip_cmgetrowlength_d(self.vsip)) case .i : return Int(vsip_mgetrowlength_i(self.vsip)) case .si : return Int(vsip_mgetrowlength_si(self.vsip)) case .li : return Int(vsip_mgetrowlength_li(self.vsip)) default : return 0 } } set(length){ switch self.type{ case .f : vsip_mputrowlength_f(self.vsip,vsip_length(length)) case .d : vsip_mputrowlength_d(self.vsip,vsip_length(length)) case .cf : vsip_cmputrowlength_f(self.vsip,vsip_length(length)) case .cd : vsip_cmputrowlength_d(self.vsip,vsip_length(length)) case .i : vsip_mputrowlength_i(self.vsip,vsip_length(length)) case .si : vsip_mputrowlength_si(self.vsip,vsip_length(length)) case .li : vsip_mputrowlength_li(self.vsip,vsip_length(length)) default : break } } } public var columnLength: Int{ get{ switch self.type { case .f : return Int(vsip_mgetcollength_f(self.vsip)) case .d : return Int(vsip_mgetcollength_d(self.vsip)) case .cf : return Int(vsip_cmgetcollength_f(self.vsip)) case .cd : return Int(vsip_cmgetcollength_d(self.vsip)) case .i : return Int(vsip_mgetcollength_i(self.vsip)) case .si : return Int(vsip_mgetcollength_si(self.vsip)) case .li : return Int(vsip_mgetcollength_li(self.vsip)) default : return 0 } } set(length){ switch self.type{ case .f : vsip_mputcollength_f(self.vsip,vsip_length(length)) case .d : vsip_mputcollength_d(self.vsip,vsip_length(length)) case .cf : vsip_cmputcollength_f(self.vsip,vsip_length(length)) case .cd : vsip_cmputcollength_d(self.vsip,vsip_length(length)) case .i : vsip_mputcollength_i(self.vsip,vsip_length(length)) case .si : vsip_mputcollength_si(self.vsip,vsip_length(length)) case .li : vsip_mputcollength_li(self.vsip,vsip_length(length)) default : break } } } public var real: Matrix { get{ let ans = super.real(self.vsip) // C VSIP real view let blk = ans.0 let v = ans.1 return Matrix(block: blk, cView: v) } } public var imag: Matrix{ get{ let ans = super.imag(self.vsip) // C VSIP imag view let blk = ans.0! let v = ans.1! return Matrix(block: blk, cView: v) } } subscript(rowIndex: Int, columnIndex: Int) -> Scalar { get{ return super.get(self.vsip, rowIndex: vsip_index(rowIndex), columnIndex: vsip_index(columnIndex)) } set(value){ super.put(self.vsip, rowIndex: vsip_index(rowIndex), columnIndex: vsip_index(columnIndex), value: value) } } subscript() -> Scalar { get{ return self[0,0] } set(value){ self.fill(value) } } public static func + (left: Matrix, right: Matrix) -> Matrix { let retval = left.empty Vsip.add(left, right, resultsIn: retval) return retval } public static func - (left: Matrix, right: Matrix) -> Matrix { let retval = left.empty Vsip.sub(left, subtract: right, resultsIn: retval) return retval } // MARK: Matrix Data Generators public func fill(_ value: Scalar){ switch self.type{ case .d: vsip_mfill_d(value.vsip_d, self.vsip) case .f: vsip_mfill_f(value.vsip_f,self.vsip) case .cd: vsip_cmfill_d(value.vsip_cd,self.vsip) case .cf: vsip_cmfill_f(value.vsip_cf,self.vsip) case .i: vsip_mfill_i(value.vsip_i,self.vsip) case .li: vsip_mfill_li(value.vsip_li,self.vsip) case .si: vsip_mfill_si(value.vsip_si,self.vsip) case .uc: vsip_mfill_uc(value.vsip_uc,self.vsip) default: break } } public func randn(_ seed: vsip_index, portable: Bool) -> Matrix{ let state = Vsip.Rand(seed: seed, portable: portable) state.randn(self) return self } public func randu(_ seed: vsip_index, portable: Bool) -> Matrix{ let state = Vsip.Rand(seed: seed, portable: portable) state.randu(self) return self } // MARK: Views, Sub-Views, Copies, Clones and convenience creaters. // create empty Matrix of same type and view size. New data space created, created as row major public var empty: Matrix{ return Matrix(columnLength: self.columnLength, rowLength: self.rowLength, type: self.type, major: VSIP_ROW) } public func empty(_ type: Block.Types) -> Matrix{ return Matrix(columnLength: self.columnLength, rowLength: self.rowLength, type: type, major: VSIP_ROW) } // copy is new data space, view of same size, copy of data public var newCopy: Matrix { let view = self.empty switch view.type{ case .f: vsip_mcopy_f_f(self.vsip,view.vsip) case .d: vsip_mcopy_d_d(self.vsip, view.vsip) case .cf: vsip_cmcopy_f_f(self.vsip,view.vsip) case .cd: vsip_cmcopy_d_d(self.vsip, view.vsip) case .i: vsip_mcopy_i_i(self.vsip,view.vsip) default: break } return view } public func copy(_ resultsIn: Matrix) -> Matrix{ let t = (self.type, resultsIn.type) switch t{ case (.f,.f): vsip_mcopy_f_f(self.vsip,resultsIn.vsip) case (.f,.cf): let r = resultsIn.real;let i = resultsIn.real vsip_mcopy_f_f(self.vsip,r.vsip) vsip_mfill_f(0.0,i.vsip) case (.d,.d): vsip_mcopy_d_d(self.vsip,resultsIn.vsip) case (.d,.cd): let r = resultsIn.real;let i = resultsIn.real vsip_mcopy_d_d(self.vsip,r.vsip) vsip_mfill_d(0.0,i.vsip) case (.d,.f): vsip_mcopy_d_f(self.vsip,resultsIn.vsip) case (.f,.d): vsip_mcopy_f_d(self.vsip,resultsIn.vsip) case (.i,.f): vsip_mcopy_i_f(self.vsip,resultsIn.vsip) case (.i,.i): vsip_mcopy_i_i(self.vsip, resultsIn.vsip) case (.si,.f): vsip_mcopy_si_f(self.vsip, resultsIn.vsip) default: break } return resultsIn } // clone is same data space just new view public var clone: Matrix { return Matrix(block: self.block, offset: self.offset, columnStride: self.columnStride, columnLength: self.columnLength, rowStride: self.rowStride, rowLength: self.rowLength) } // transview is new view of same data space as a transpose. public var transview: Matrix { return Matrix(block: self.block, offset: self.offset, columnStride: self.rowStride, columnLength: self.rowLength, rowStride: self.columnStride, rowLength: self.columnLength) } public func diagview(diagIndex: Int) -> Vector { let blk = self.block switch self.type { case .f: if let v = vsip_mdiagview_f(self.vsip, vsip_stride(diagIndex)) { return Vector(block: blk, cView: v) } else { break } case .d: if let v = vsip_mdiagview_d(self.vsip, vsip_stride(diagIndex)){ return Vector(block: blk, cView: v) } else { break } case .cf: if let v = vsip_cmdiagview_f(self.vsip, vsip_stride(diagIndex)){ return Vector(block: blk, cView: v) } else { break } case .cd: if let v = vsip_cmdiagview_d(self.vsip, vsip_stride(diagIndex)){ return Vector(block: blk, cView: v) } else { break } case .i: if let v = vsip_mdiagview_i(self.vsip, vsip_stride(diagIndex)){ return Vector(block: blk, cView: v) } else { break } case .li: if let v = vsip_mdiagview_li(self.vsip, vsip_stride(diagIndex)){ return Vector(block: blk, cView: v) } else { break } case .si: if let v = vsip_mdiagview_si(self.vsip, vsip_stride(diagIndex)){ return Vector(block: blk, cView: v) } else { break } case .uc: if let v = vsip_mdiagview_uc(self.vsip, vsip_stride(diagIndex)){ return Vector(block: blk, cView: v) } else { break } case .bl: if let v = vsip_mdiagview_bl(self.vsip, vsip_stride(diagIndex)){ return Vector(block: blk, cView: v) } else { break } default: print("diagview not available for this view") } preconditionFailure("Failed to return valid vsip diagview") } public var diagview: Vector { return self.diagview(diagIndex: 0) } public func row(_ row: Int) -> Vector { let blk = self.block switch self.type { case .f: if let v = vsip_mrowview_f(self.vsip, vsip_index(row)) { return Vector(block: blk, cView: v) } else { break } case .d: if let v = vsip_mrowview_d(self.vsip, vsip_index(row)){ return Vector(block: blk, cView: v) } else { break } case .cf: if let v = vsip_cmrowview_f(self.vsip, vsip_index(row)){ return Vector(block: blk, cView: v) } else { break } case .cd: if let v = vsip_cmrowview_d(self.vsip, vsip_index(row)){ return Vector(block: blk, cView: v) } else { break } case .i: if let v = vsip_mrowview_i(self.vsip, vsip_index(row)){ return Vector(block: blk, cView: v) } else { break } case .li: if let v = vsip_mrowview_li(self.vsip, vsip_index(row)){ return Vector(block: blk, cView: v) } else { break } case .si: if let v = vsip_mrowview_si(self.vsip, vsip_index(row)){ return Vector(block: blk, cView: v) } else { break } case .uc: if let v = vsip_mrowview_uc(self.vsip, vsip_index(row)){ return Vector(block: blk, cView: v) } else { break } case .bl: if let v = vsip_mrowview_bl(self.vsip, vsip_index(row)){ return Vector(block: blk, cView: v) } else { break } default: print("diagview not available for this view") } preconditionFailure("Failed to return valid vsip diagview") } public func col(_ col: Int) -> Vector { let blk = self.block switch self.type { case .f: if let v = vsip_mcolview_f(self.vsip, vsip_index(col)) { return Vector(block: blk, cView: v) } else { break } case .d: if let v = vsip_mcolview_d(self.vsip, vsip_index(col)){ return Vector(block: blk, cView: v) } else { break } case .cf: if let v = vsip_cmcolview_f(self.vsip, vsip_index(col)){ return Vector(block: blk, cView: v) } else { break } case .cd: if let v = vsip_cmcolview_d(self.vsip, vsip_index(col)){ return Vector(block: blk, cView: v) } else { break } case .i: if let v = vsip_mcolview_i(self.vsip, vsip_index(col)){ return Vector(block: blk, cView: v) } else { break } case .li: if let v = vsip_mcolview_li(self.vsip, vsip_index(col)){ return Vector(block: blk, cView: v) } else { break } case .si: if let v = vsip_mcolview_si(self.vsip, vsip_index(col)){ return Vector(block: blk, cView: v) } else { break } case .uc: if let v = vsip_mcolview_uc(self.vsip, vsip_index(col)){ return Vector(block: blk, cView: v) } else { break } case .bl: if let v = vsip_mcolview_bl(self.vsip, vsip_index(col)){ return Vector(block: blk, cView: v) } else { break } default: print("diagview not available for this view") } preconditionFailure("Failed to return valid vsip diagview") } // MARK: Print public func mString(_ format: String) -> String { let fmt = Vsip.formatFmt(format) var retval = "" let m = self.columnLength - 1 let n = self.rowLength - 1 for i in 0...m{ retval += (i == 0) ? "[" : " " for j in 0...n{ retval += Vsip.scalarString(fmt, value: self[i,j]) if j < n { retval += ", " } } retval += (i == m) ? "]\n" : ";\n" } return retval } public func mPrint(_ format: String){ let m = mString(format) print(m) } // MARK: Jvsip methods on matrix var normFro: Double { get { return (Vsip.Jvsip.normFro(view: self).reald) } } } // MARK: - Elementary Math Functions public static func acos(_ input: Vector, resultsIn: Vector) { assert(sizeEqual(input, against: resultsIn), "vectors must be the same size") switch (input.type, resultsIn.type) { case (.f, .f): vsip_vacos_f(input.vsip, resultsIn.vsip) case (.d, .d): vsip_vacos_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for this type vector") } } public static func acos(_ input: Matrix, resultsIn: Matrix) { assert(sizeEqual(input, against: resultsIn), "vectors must be the same size") switch (input.type, resultsIn.type) { case (.f, .f): vsip_macos_f(input.vsip, resultsIn.vsip) case (.d, .d): vsip_macos_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for this type vector") } } public static func asin(_ input: Vector, resultsIn: Vector) { assert(sizeEqual(input, against: resultsIn), "vectors must be the same size") switch (input.type, resultsIn.type) { case (.f, .f): vsip_vasin_f(input.vsip, resultsIn.vsip) case (.d, .d): vsip_vasin_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for this type vector") } } public static func asin(_ input: Matrix, resultsIn: Matrix) { assert(sizeEqual(input, against: resultsIn), "vectors must be the same size") switch (input.type, resultsIn.type) { case (.f, .f): vsip_masin_f(input.vsip, resultsIn.vsip) case (.d, .d): vsip_masin_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for this type vector") } } public static func atan(_ input: Vector, resultsIn: Vector) { assert(sizeEqual(input, against: resultsIn), "View sizes must be the same") switch input.type { case .f: vsip_vatan_f(input.vsip, resultsIn.vsip) case .d: vsip_vatan_d(input.vsip, resultsIn.vsip) default: precondition(true, "function not supported for this type vector") break } } public static func atan(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_matan_f(input.vsip, resultsIn.vsip) case .d: vsip_matan_d(input.vsip, resultsIn.vsip) default: precondition(true, "function not supported for this type matrix") break } } public static func atan2(numerator: Vector, denominator: Vector, resultsIn: Vector) { let tn = numerator.type let td = denominator.type let to = resultsIn.type assert(tn == td && tn == to, "View types must agree") assert(sizeEqual(numerator, against: denominator) && sizeEqual(numerator, against: resultsIn), "View sizes musta be equal") switch tn{ case .f: vsip_vatan2_f(numerator.vsip,denominator.vsip,resultsIn.vsip) case .d: vsip_vatan2_d(numerator.vsip,denominator.vsip,resultsIn.vsip) default: preconditionFailure("function not supported for this type matrix") break } } public static func atan2(numerator: Matrix, denominator: Matrix, resultsIn: Matrix) { let tn = numerator.type let td = denominator.type let to = resultsIn.type assert(tn == td && tn == to, "input types must be the same") assert(sizeEqual(numerator, against: denominator) && sizeEqual(numerator, against: resultsIn), "View sizes musta be equal") switch tn { case .f: vsip_matan2_f(numerator.vsip,denominator.vsip,resultsIn.vsip) case .d: vsip_matan2_d(numerator.vsip,denominator.vsip,resultsIn.vsip) default: preconditionFailure("function not supported for this type matrix") break } } public static func cos(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vcos_f(input.vsip, resultsIn.vsip) case .d: vsip_vcos_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func cos(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_mcos_f(input.vsip, resultsIn.vsip) case .d: vsip_mcos_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func cosh(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vcosh_f(input.vsip, resultsIn.vsip) case .d: vsip_vcosh_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func cosh(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_mcosh_f(input.vsip, resultsIn.vsip) case .d: vsip_mcosh_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func sin(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vsin_f(input.vsip, resultsIn.vsip) case .d: vsip_vsin_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func sin(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_msin_f(input.vsip, resultsIn.vsip) case .d: vsip_msin_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func sinh(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vsinh_f(input.vsip, resultsIn.vsip) case .d: vsip_vsinh_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func sinh(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_msinh_f(input.vsip, resultsIn.vsip) case .d: vsip_msinh_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func exp(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vexp_f(input.vsip, resultsIn.vsip) case .d: vsip_vexp_d(input.vsip, resultsIn.vsip) case .cf: vsip_cvexp_f(input.vsip, resultsIn.vsip) case .cd: vsip_cvexp_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func exp(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_mexp_f(input.vsip, resultsIn.vsip) case .d: vsip_mexp_d(input.vsip, resultsIn.vsip) case .cf: vsip_cmexp_f(input.vsip, resultsIn.vsip) case .cd: vsip_cmexp_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func exp10(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vexp10_f(input.vsip, resultsIn.vsip) case .d: vsip_vexp10_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func exp10(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_mexp10_f(input.vsip, resultsIn.vsip) case .d: vsip_mexp10_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func log(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vlog_f(input.vsip, resultsIn.vsip) case .d: vsip_vlog_d(input.vsip, resultsIn.vsip) case .cf: vsip_cvlog_f(input.vsip, resultsIn.vsip) case .cd: vsip_cvlog_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func log(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_mlog_f(input.vsip, resultsIn.vsip) case .d: vsip_mlog_d(input.vsip, resultsIn.vsip) case .cf: vsip_cmlog_f(input.vsip, resultsIn.vsip) case .cd: vsip_cmlog_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func log10(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vlog10_f(input.vsip, resultsIn.vsip) case .d: vsip_vlog10_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func log10(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_mlog10_f(input.vsip, resultsIn.vsip) case .d: vsip_mlog10_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func sqrt(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vsqrt_f(input.vsip, resultsIn.vsip) case .d: vsip_vsqrt_d(input.vsip, resultsIn.vsip) case .cf: vsip_cvsqrt_f(input.vsip, resultsIn.vsip) case .cd: vsip_cvsqrt_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func sqrt(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_msqrt_f(input.vsip, resultsIn.vsip) case .d: vsip_msqrt_d(input.vsip, resultsIn.vsip) case .cf: vsip_cmsqrt_f(input.vsip, resultsIn.vsip) case .cd: vsip_cmsqrt_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func tan(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vtan_f(input.vsip, resultsIn.vsip) case .d: vsip_vtan_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func tan(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_mtan_f(input.vsip, resultsIn.vsip) case .d: vsip_mtan_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func tanh(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vtanh_f(input.vsip, resultsIn.vsip) case .d: vsip_vtanh_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func tanh(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_mtanh_f(input.vsip, resultsIn.vsip) case .d: vsip_mtanh_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } // MARK: - Unary Functions public static func arg(_ input: Vector, resultsIn: Vector) { let type = (input.type, resultsIn.type) assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch type { case (.cf, .f): vsip_varg_f(input.vsip, resultsIn.vsip) case (.cd, .d): vsip_varg_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for input/resultsIn views") } } public static func arg(_ input: Matrix, resultsIn: Matrix) { let type = (input.type, resultsIn.type) assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch type { case (.cf, .f): vsip_marg_f(input.vsip, resultsIn.vsip) case (.cd, .d): vsip_marg_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for input/resultsIn views") } } public static func ceil(_ input: Vector, resultsIn: Vector){ assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch (input.type, resultsIn.type) { case (.d, .d): vsip_vceil_d_d(input.vsip, resultsIn.vsip) case (.d,.i): vsip_vceil_d_i(input.vsip, resultsIn.vsip) case (.f, .f): vsip_vceil_f_f(input.vsip, resultsIn.vsip) case (.f,.i): vsip_vceil_f_i(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for input/resultsIn views") break } } public static func ceil(_ input: Matrix, resultsIn: Matrix){ assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch (input.type, resultsIn.type) { case (.d, .d): vsip_mceil_d_d(input.vsip, resultsIn.vsip) case (.d,.i): vsip_mceil_d_i(input.vsip, resultsIn.vsip) case (.f, .f): vsip_mceil_f_f(input.vsip, resultsIn.vsip) case (.f,.i): vsip_mceil_f_i(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for input/resultsIn views") break } } public static func conj(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .cf: vsip_cvconj_f(input.vsip, resultsIn.vsip) case .cd: vsip_cvconj_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func conj(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .cf: vsip_cmconj_f(input.vsip, resultsIn.vsip) case .cd: vsip_cmconj_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public static func neg(_ input: Vector, resultsIn: Vector){ assert(sizeEqual(input, against: resultsIn), "View size of input an resultsIn must be equal for neg") assert(input.type == resultsIn.type, "View types of input and resultsIn must be the same for neg") switch input.type { case .f: vsip_vneg_f(input.vsip,resultsIn.vsip) case .d: vsip_vneg_d(input.vsip,resultsIn.vsip) case .cf: vsip_cvneg_f(input.vsip,resultsIn.vsip) case .cd: vsip_cvneg_d(input.vsip,resultsIn.vsip) case .i: vsip_vneg_i(input.vsip,resultsIn.vsip) case .li: vsip_vneg_li(input.vsip,resultsIn.vsip) case .vi: vsip_vneg_si(input.vsip,resultsIn.vsip) default: assert(false, "type not found for neg") break } } public static func neg(_ input: Matrix, resultsIn: Matrix){ assert(sizeEqual(input, against: resultsIn), "View size of input an resultsIn must be equal for neg") assert(input.type == resultsIn.type, "View types of input and resultsIn must be the same for neg") switch input.type { case .f: vsip_mneg_f(input.vsip,resultsIn.vsip) case .d: vsip_mneg_d(input.vsip,resultsIn.vsip) case .cf: vsip_cmneg_f(input.vsip,resultsIn.vsip) case .cd: vsip_cmneg_d(input.vsip,resultsIn.vsip) default: assert(false, "type not found for neg") break } } public static func sumval(_ input: Vector) -> Scalar { switch input.type { case .d: return Scalar(vsip_vsumval_d(input.vsip)) case .f: return Scalar(vsip_vsumval_f(input.vsip)) case .cd: return Scalar(vsip_cvsumval_d(input.vsip)) case .cf: return Scalar(vsip_cvsumval_f(input.vsip)) case .i: return Scalar(vsip_vsumval_i(input.vsip)) case .bl: return Scalar(vsip_vsumval_bl(input.vsip)) default: preconditionFailure("sumval not supported for this type") } } public static func sumval(_ input: Matrix) -> Scalar { switch input.type { case .d: return Scalar(vsip_msumval_d(input.vsip)) case .f: return Scalar(vsip_msumval_f(input.vsip)) case .cd: return Scalar(vsip_cmsumval_d(input.vsip)) case .cf: return Scalar(vsip_cmsumval_f(input.vsip)) case .bl: return Scalar(vsip_msumval_bl(input.vsip)) default: preconditionFailure("sumval not supported for this type") } } public static func sumsqval(_ input: Vector) -> Scalar { switch input.type { case .d: return Scalar(Double(vsip_vsumsqval_d(input.vsip))) case .f: return Scalar(Float(vsip_vsumsqval_f(input.vsip))) default: preconditionFailure("sumsqval not supported for this type") break } } public static func sumsqval(_ input: Matrix) -> Scalar { switch input.type { case .d: return Scalar(Double(vsip_msumsqval_d(input.vsip))) case .f: return Scalar(Float(vsip_msumsqval_f(input.vsip))) default: preconditionFailure("sumsqval not supported for this type") break } } // MARK: - Binary Functions public static func add(_ one: Vector, _ to: Vector, resultsIn: Vector) { assert(sizeEqual(one, against: to),"Views must be the same size") assert(to.type == resultsIn.type, "Output view type not compliant with input") switch one.type { case .f: switch to.type{ case .f: vsip_vadd_f(one.vsip, to.vsip, resultsIn.vsip) case .cf: vsip_rcvadd_f(one.vsip, to.vsip, resultsIn.vsip) default: break } case .d: switch to.type{ case .d: vsip_vadd_d(one.vsip, to.vsip, resultsIn.vsip) case .cd: vsip_rcvadd_d(one.vsip, to.vsip, resultsIn.vsip) default: break } case .cf: vsip_cvadd_f(one.vsip, to.vsip, resultsIn.vsip) case .cd: vsip_cvadd_d(one.vsip, to.vsip, resultsIn.vsip) case .i: vsip_vadd_d(one.vsip, to.vsip, resultsIn.vsip) case .li: vsip_vadd_li(one.vsip, to.vsip, resultsIn.vsip) case .uc: vsip_vadd_li(one.vsip, to.vsip, resultsIn.vsip) case .si: vsip_vadd_si(one.vsip, to.vsip, resultsIn.vsip) case .vi: vsip_vadd_vi(one.vsip, to.vsip, resultsIn.vsip) default: preconditionFailure("View type not supported") break } } public static func add(_ one: Matrix, _ to: Matrix, resultsIn: Matrix) { assert(sizeEqual(one, against: to),"Views must be the same size") assert(to.type == resultsIn.type, "Output view type not compliant with input") switch one.type { case .f: switch to.type{ case .f: vsip_madd_f(one.vsip, to.vsip, resultsIn.vsip) case .cf: vsip_rcmadd_f(one.vsip, to.vsip, resultsIn.vsip) default: break } case .d: switch to.type{ case .d: vsip_madd_d(one.vsip, to.vsip, resultsIn.vsip) case .cd: vsip_rcmadd_d(one.vsip, to.vsip, resultsIn.vsip) default: break } case .cf: vsip_cmadd_f(one.vsip, to.vsip, resultsIn.vsip) case .cd: vsip_cmadd_d(one.vsip, to.vsip, resultsIn.vsip) case .i: vsip_madd_d(one.vsip, to.vsip, resultsIn.vsip) case .li: vsip_madd_li(one.vsip, to.vsip, resultsIn.vsip) case .si: vsip_madd_si(one.vsip, to.vsip, resultsIn.vsip) default: preconditionFailure("View type not supported") break } } public static func add(_ scalar: Double, _ vector: Vector, resultsIn: Vector){ Vsip.add(Scalar(scalar), vector, resultsIn: resultsIn) } public static func add(_ scalar: Float, _ vector: Vector, resultsIn: Vector){ Vsip.add(Scalar(scalar), vector, resultsIn: resultsIn) } public static func add(_ scalar: Int, _ vector: Vector, resultsIn: Vector){ Vsip.add(Scalar(scalar), vector, resultsIn: resultsIn) } public static func add(_ scalar: Scalar, _ vector: Vector, resultsIn: Vector){ assert(vector.type == resultsIn.type, "View types must agrees") let t = (scalar.type, vector.type, resultsIn.type) switch t { case (.f, .f, .f): vsip_svadd_f(scalar.vsip_f, vector.vsip, resultsIn.vsip) case (.d, .d, .d): vsip_svadd_d(scalar.vsip_d, vector.vsip, resultsIn.vsip) case (.f, .cf, .cf): vsip_rscvadd_f(scalar.vsip_f, vector.vsip, resultsIn.vsip) case (.d, .cd, .cd): vsip_rscvadd_d(scalar.vsip_d, vector.vsip, resultsIn.vsip) case (.cf, .cf, .cf): vsip_csvadd_f(scalar.vsip_cf, vector.vsip, resultsIn.vsip) case (.cd, .cd, .cd): vsip_csvadd_d(scalar.vsip_cd, vector.vsip, resultsIn.vsip) case (.i, .i, .i): vsip_svadd_i(scalar.vsip_i, vector.vsip, resultsIn.vsip) case (.li, .li, .li): vsip_svadd_li(scalar.vsip_li, vector.vsip, resultsIn.vsip) case (.si, .si, .si): vsip_svadd_si(scalar.vsip_si, vector.vsip, resultsIn.vsip) case (.uc, .uc, .uc): vsip_svadd_uc(scalar.vsip_uc, vector.vsip, resultsIn.vsip) case (.vi, .vi, .vi): vsip_svadd_vi(scalar.vsip_vi, vector.vsip, resultsIn.vsip) default: preconditionFailure("Argument string not supported for svadd") } } public static func add(_ scalar: Double, _ matrix: Matrix, resultsIn: Matrix){ Vsip.add(Scalar(scalar), matrix, resultsIn: resultsIn) } public static func add(_ scalar: Float, _ matrix: Matrix, resultsIn: Matrix){ Vsip.add(Scalar(scalar), matrix, resultsIn: resultsIn) } public static func add(_ scalar: Scalar, _ matrix: Matrix, resultsIn: Matrix){ assert(sizeEqual(matrix, against: resultsIn),"Views must be the same size") let t = (scalar.type, matrix.type, resultsIn.type) switch t { case (.f, .f, .f): vsip_smadd_f(scalar.vsip_f, matrix.vsip, resultsIn.vsip) case (.d, .d, .d): vsip_smadd_d(scalar.vsip_d, matrix.vsip, resultsIn.vsip) case (.f, .cf, .cf): vsip_rscmadd_f(scalar.vsip_f, matrix.vsip, resultsIn.vsip) case (.d, .cd, .cd): vsip_rscmadd_d(scalar.vsip_d, matrix.vsip, resultsIn.vsip) case (.cf, .cf, .cf): vsip_csmadd_f(scalar.vsip_cf, matrix.vsip, resultsIn.vsip) case (.cd, .cd, .cd): vsip_csmadd_d(scalar.vsip_cd, matrix.vsip, resultsIn.vsip) default: preconditionFailure("Argument string not supported for scalar matrix add") } } public static func div(numerator aView: Vector, denominator by: Vector, quotient resultsIn: Vector){ assert(sizeEqual(aView, against: by),"Views must be the same size") assert(sizeEqual(aView, against: resultsIn),"Views must be the same size") let t = (aView.type, by.type, resultsIn.type) switch t { case (.d, .cd, .cd): vsip_rcvdiv_d(aView.vsip, by.vsip, resultsIn.vsip) case (.f, .cf, .cf): vsip_rcvdiv_f(aView.vsip, by.vsip, resultsIn.vsip) case (.d, .d, .d): vsip_vdiv_d(aView.vsip, by.vsip, resultsIn.vsip) case (.f, .f, .f): vsip_vdiv_f(aView.vsip, by.vsip, resultsIn.vsip) case (.cd, .d, .cd): vsip_crvdiv_d(aView.vsip, by.vsip, resultsIn.vsip) case (.cf, .f, .cf): vsip_crvdiv_f(aView.vsip, by.vsip, resultsIn.vsip) case (.cd, .cd, .cd): vsip_cvdiv_d(aView.vsip, by.vsip, resultsIn.vsip) case (.cf, .cf, .cf): vsip_cvdiv_f(aView.vsip, by.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for input/resultsIn views of type (\t)") } } public static func div(numerator aView: Matrix, denominator by: Matrix, quotient resultsIn: Matrix){ assert(sizeEqual(aView, against: by),"Views must be the same size") assert(sizeEqual(aView, against: resultsIn),"Views must be the same size") let t = (aView.type, by.type, resultsIn.type) switch t { case (.cd, .cd, .cd): vsip_cmdiv_d(aView.vsip, by.vsip, resultsIn.vsip) case (.cf, .cf, .cf): vsip_cmdiv_f(aView.vsip, by.vsip, resultsIn.vsip) case (.cd, .d, .cd): vsip_crmdiv_d(aView.vsip, by.vsip, resultsIn.vsip) case (.cf, .f, .cf): vsip_crmdiv_f(aView.vsip, by.vsip, resultsIn.vsip) case (.d, .d, .d): vsip_mdiv_d(aView.vsip, by.vsip, resultsIn.vsip) case (.f, .f, .f): vsip_mdiv_f(aView.vsip, by.vsip, resultsIn.vsip) case (.d, .cd, .cd): vsip_rcmdiv_d(aView.vsip, by.vsip, resultsIn.vsip) case (.f, .cf, .cf): vsip_rcmdiv_f(aView.vsip, by.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for input/resultsIn views of type (\t)") } } public static func mul(_ one: Vector, _ to: Vector, resultsIn: Vector) { assert(sizeEqual(one, against: to),"Views must be the same size") switch (one.type, to.type, resultsIn.type) { case (.f,.f,.f): vsip_vmul_f(one.vsip, to.vsip, resultsIn.vsip) case (.f,.cf, .cf): vsip_rcvmul_f(one.vsip, to.vsip, resultsIn.vsip) case (.d, .d,.d): vsip_vmul_d(one.vsip, to.vsip, resultsIn.vsip) case (.d, .cd, .cd): vsip_rcvmul_d(one.vsip, to.vsip, resultsIn.vsip) case (.cf, .cf, .cf): vsip_cvmul_f(one.vsip, to.vsip, resultsIn.vsip) case (.cd, .cd, .cd): vsip_cvmul_d(one.vsip, to.vsip, resultsIn.vsip) case (.i, .i, .i): vsip_vmul_d(one.vsip, to.vsip, resultsIn.vsip) case (.li, .li, .li): vsip_vmul_li(one.vsip, to.vsip, resultsIn.vsip) case (.uc,.uc,.uc): vsip_vmul_uc(one.vsip, to.vsip, resultsIn.vsip) case (.si,.si,.si): vsip_vmul_si(one.vsip, to.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for input/resultsIn views") } } public static func mul(_ one: Matrix, _ to: Matrix, resultsIn: Matrix) { assert(sizeEqual(one, against: to),"Views must be the same size") switch (one.type, to.type, resultsIn.type) { case (.f, .f, .f): vsip_mmul_f(one.vsip, to.vsip, resultsIn.vsip) case (.f, .cf, .cf): vsip_rcmmul_f(one.vsip, to.vsip, resultsIn.vsip) case (.d, .d, .d): vsip_mmul_d(one.vsip, to.vsip, resultsIn.vsip) case (.f, .cd, .cd): vsip_rcmmul_d(one.vsip, to.vsip, resultsIn.vsip) case (.cf, .cf, .cf): vsip_cmmul_f(one.vsip, to.vsip, resultsIn.vsip) case (.cd, .cd, .cd): vsip_cmmul_d(one.vsip, to.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for input/resultsIn views") } } public static func mul(_ scalar: Double, _ vector: Vector, resultsIn: Vector){ Vsip.mul(Scalar(scalar), vector, resultsIn: resultsIn) } public static func mul(_ scalar: Float, _ vector: Vector, resultsIn: Vector){ Vsip.mul(Scalar(scalar), vector, resultsIn: resultsIn) } public static func mul(_ scalar: Int, _ vector: Vector, resultsIn: Vector){ Vsip.mul(Scalar(scalar), vector, resultsIn: resultsIn) } public static func mul(_ scalar: Scalar,_ vector: Vector, resultsIn: Vector){ assert(sizeEqual(vector, against: resultsIn), "View sizes must be the same") let t = (scalar.type, vector.type, resultsIn.type) switch t { case (.f, .f, .f): vsip_svmul_f(scalar.vsip_f, vector.vsip, resultsIn.vsip) case (.d, .d, .d): vsip_svmul_d(scalar.vsip_d, vector.vsip, resultsIn.vsip) case (.f, .cf, .cf): vsip_rscvmul_f(scalar.vsip_f, vector.vsip, resultsIn.vsip) case (.d, .cd, .cd): vsip_rscvmul_d(scalar.vsip_d, vector.vsip, resultsIn.vsip) case (.cf, .cf, .cf): vsip_csvmul_f(scalar.vsip_cf, vector.vsip, resultsIn.vsip) case (.cd, .cd, .cd): vsip_csvmul_d(scalar.vsip_cd, vector.vsip, resultsIn.vsip) case (.i, .i, .i): vsip_svmul_i(scalar.vsip_i, vector.vsip, resultsIn.vsip) case (.li, .li, .li): vsip_svmul_li(scalar.vsip_li, vector.vsip, resultsIn.vsip) case (.si, .si, .si): vsip_svmul_si(scalar.vsip_si, vector.vsip, resultsIn.vsip) case (.uc, .uc, .uc): vsip_svmul_uc(scalar.vsip_uc, vector.vsip, resultsIn.vsip) default: preconditionFailure("Argument string not supported for svmul") } } public static func mul(_ scalar: Double, _ matrix: Matrix, resultsIn: Matrix){ Vsip.mul(Scalar(scalar), matrix, resultsIn: resultsIn) } public static func mul(_ scalar: Float, _ matrix: Matrix, resultsIn: Matrix){ Vsip.mul(Scalar(scalar), matrix, resultsIn: resultsIn) } public static func mul(_ scalar: Scalar,_ matrix: Matrix, resultsIn: Matrix){ assert(sizeEqual(matrix, against: resultsIn),"Views must be the same size") let t = (scalar.type, matrix.type, resultsIn.type) switch t { case (.f, .f, .f): vsip_smmul_f(scalar.vsip_f, matrix.vsip, resultsIn.vsip) case (.d, .d, .d): vsip_smmul_d(scalar.vsip_d, matrix.vsip, resultsIn.vsip) case (.f,.cf, .cf): vsip_rscmmul_f(scalar.vsip_f, matrix.vsip, resultsIn.vsip) case (.d, .cd, .cd): vsip_rscmmul_d(scalar.vsip_d, matrix.vsip, resultsIn.vsip) case (.cd, .cd, .cd): vsip_csmmul_d(scalar.vsip_cd, matrix.vsip, resultsIn.vsip) case (.cf, .cf, .cf): vsip_csmmul_f(scalar.vsip_cf, matrix.vsip, resultsIn.vsip) default: preconditionFailure("Argument string not supported for mul") } } public static func vmmul(vector: Vector, matrix: Matrix, major: vsip_major, resultsIn: Matrix){ let vsipVec = vector.vsip let vsipMat = matrix.vsip let vsipOut = resultsIn.vsip let t = (vector.type, matrix.type, resultsIn.type) switch t { case(.cd, .cd, .cd): vsip_cvmmul_d ( vsipVec, vsipMat, major, vsipOut) case(.cf, .cf, .cf): vsip_cvmmul_f ( vsipVec, vsipMat, major, vsipOut) case(.d, .cd, .cd): vsip_rvcmmul_d ( vsipVec, vsipMat, major, vsipOut) case(.f, .cf, .cf): vsip_rvcmmul_f ( vsipVec, vsipMat, major, vsipOut) case(.d, .d, .d): vsip_vmmul_d ( vsipVec, vsipMat, major, vsipOut) case(.f, .f, .f): vsip_vmmul_f ( vsipVec, vsipMat, major, vsipOut) default: preconditionFailure("Argument list not supported for vmmul") } } public static func sub(_ aView: Vector, subtract: Vector, resultsIn: Vector){ assert(sizeEqual(aView, against: subtract),"Views must be the same size") assert(sizeEqual(aView, against: resultsIn), "Views must be the same size") let t = (aView.type, subtract.type, resultsIn.type) switch t{ case (.cd, .d, .cd): vsip_crvsub_d (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.cf, .f, .cf): vsip_crvsub_f (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.cd, .cd, .cd): vsip_cvsub_d (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.cf, .cf, .cf): vsip_cvsub_f (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.d, .cd, .cd): vsip_rcvsub_d (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.f, .cf, .cf): vsip_rcvsub_f (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.d, .d, .d): vsip_vsub_d (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.f, .f, .f): vsip_vsub_f (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.i, .i, .i): vsip_vsub_i (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.li, .li, .li): vsip_vsub_li (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.si, .si, .si): vsip_vsub_si (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.uc, .uc, .uc): vsip_vsub_uc (aView.vsip,subtract.vsip,resultsIn.vsip ) default: preconditionFailure("function not supported for input/resultsIn views") } } public static func sub(_ aView: Matrix, subtract: Matrix, resultsIn: Matrix){ assert(sizeEqual(aView, against: subtract),"Views must be the same size") assert(sizeEqual(aView, against: resultsIn), "Views must be the same size") let t = (aView.type, subtract.type, resultsIn.type) switch t{ case (.cd, .cd, .cd): vsip_cmsub_d (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.cf, .cf, .cf): vsip_cmsub_f (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.cd, .d, .cd): vsip_crmsub_d (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.cf, .f, .cf): vsip_crmsub_f (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.si, .si, .si): vsip_msub_si (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.d, .cd, .cd): vsip_rcmsub_d (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.d, .d, .d): vsip_msub_d (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.f, .f, .f): vsip_msub_f (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.i, .i, .i): vsip_msub_i (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.li, .li, .li): vsip_msub_li (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.f, .cf, .cf): vsip_rcmsub_f (aView.vsip,subtract.vsip,resultsIn.vsip ) default: preconditionFailure("function not supported for input/resultsIn views \(t)") } } // Mark: - Random public class Rand { fileprivate var tryVsip : OpaquePointer? var vsip: OpaquePointer { get { return tryVsip! } } let jInit : JVSIP var myId : NSNumber? public init(seed: vsip_index, numberOfSubSequences: vsip_index, mySequence: vsip_index, portable: Bool){ let rng = portable ? VSIP_PRNG : VSIP_NPRNG let id = mySequence let numprocs = numberOfSubSequences if let randObj = vsip_randcreate(seed, numprocs, id, rng){ tryVsip = randObj } else { preconditionFailure("Failed to create vsip rand object") } jInit = JVSIP() myId = jInit.myId } public convenience init(seed: vsip_index, portable: Bool){ self.init(seed: seed, numberOfSubSequences: 1, mySequence: 1, portable: portable) } public func randu(_ view: Vector){ let t = view.type switch t{ case .f: vsip_vrandu_f(self.vsip,view.vsip) case .d: vsip_vrandu_d(self.vsip,view.vsip) case .cf: vsip_cvrandu_f(self.vsip,view.vsip) case .cd: vsip_cvrandu_d(self.vsip,view.vsip) default: preconditionFailure("Type \(t) not defined for randu") } } public func randu(_ view: Matrix){ let t = view.type switch t { case .f: vsip_mrandu_f(self.vsip,view.vsip) case .d: vsip_mrandu_d(self.vsip,view.vsip) case .cf: vsip_cmrandu_f(self.vsip,view.vsip) case .cd: vsip_cmrandu_d(self.vsip,view.vsip) default: preconditionFailure("Type \(t) not defined for randu") } } public func randn(_ view: Vector) { let t = view.type switch t{ case .f: vsip_vrandn_f(self.vsip,view.vsip) case .d: vsip_vrandn_d(self.vsip,view.vsip) case .cf: vsip_cvrandn_f(self.vsip,view.vsip) case .cd: vsip_cvrandn_d(self.vsip,view.vsip) default: preconditionFailure("Type \(t) not defined for randn") } } public func randn(_ view: Matrix) { let t = view.type switch t{ case .f: vsip_mrandn_f(self.vsip,view.vsip) case .d: vsip_mrandn_d(self.vsip,view.vsip) case .cf: vsip_cmrandn_f(self.vsip,view.vsip) case .cd: vsip_cmrandn_d(self.vsip,view.vsip) default: preconditionFailure("Type \(t) not defined for randn") } } deinit{ let id = self.myId?.int32Value vsip_randdestroy(self.vsip) if _isDebugAssertConfiguration(){ print("randdestroy id \(id!)") } } } // MARK: - Element Generation and Copy public static func copy(from: Matrix, to: Matrix) { let t = (from.type, to.type) switch t{ case (.f, .f): vsip_mcopy_f_f(from.vsip, to.vsip) case (.f, .d): vsip_mcopy_f_d(from.vsip, to.vsip) case (.d, .f): vsip_mcopy_d_f(from.vsip, to.vsip) case(.d, .d): vsip_mcopy_d_d(from.vsip, to.vsip) case (.cf, .cf): vsip_cmcopy_f_f(from.vsip, to.vsip) case (.cf, .cd): vsip_cmcopy_f_d(from.vsip, to.vsip) case (.cd, .cf): vsip_cmcopy_d_f(from.vsip, to.vsip) case(.cd, .cd): vsip_cmcopy_d_d(from.vsip, to.vsip) case(.i, .i): vsip_mcopy_i_i(from.vsip, to.vsip) case(.f, .i): vsip_mcopy_f_i(from.vsip, to.vsip) case(.i, .f): vsip_mcopy_f_i(from.vsip, to.vsip) case(.d, .i): vsip_mcopy_f_i(from.vsip, to.vsip) case(.i, .d): vsip_mcopy_f_i(from.vsip, to.vsip) default: preconditionFailure("Copy not supported for type \(t)") } } public static func copy(from: Vector, to: Vector) { let t = (from.type, to.type) switch t { case (.f, .f): vsip_vcopy_f_f(from.vsip, to.vsip) case (.f, .d): vsip_vcopy_f_d(from.vsip, to.vsip) case (.d, .f): vsip_vcopy_d_f(from.vsip, to.vsip) case(.d, .d): vsip_vcopy_d_d(from.vsip, to.vsip) case (.cf, .cf): vsip_cvcopy_f_f(from.vsip, to.vsip) case (.cf, .cd): vsip_cvcopy_f_d(from.vsip, to.vsip) case (.cd, .cf): vsip_cvcopy_d_f(from.vsip, to.vsip) case(.cd, .cd): vsip_cvcopy_d_d(from.vsip, to.vsip) case(.i, .i): vsip_vcopy_i_i(from.vsip, to.vsip) case(.f, .i): vsip_vcopy_f_i(from.vsip, to.vsip) case(.i, .f): vsip_vcopy_f_i(from.vsip, to.vsip) case(.d, .i): vsip_vcopy_f_i(from.vsip, to.vsip) case(.i, .d): vsip_vcopy_f_i(from.vsip, to.vsip) default: preconditionFailure("Copy not supported for type \(t)") } } // MARK: - Linear Algebra Matrix and Vector Operations public static func herm(_ complexInputMatrix: Matrix, output: Matrix){ let vsipA = complexInputMatrix.vsip let vsipB = output.vsip let t = (complexInputMatrix.type, output.type) switch t { case (.cf, .cf): vsip_cmherm_f(vsipA, vsipB) case (.cd, .cd): vsip_cmherm_d(vsipA, vsipB) default: preconditionFailure("Type not supported for herm") } } public static func jdot(_ complexInputVector: Vector,dot complexOuputVector: Vector) -> Scalar { let vsipA = complexInputVector.vsip let vsipB = complexOuputVector.vsip let t = (complexInputVector.type, complexInputVector.type) switch t { case (.cf, .cf): return Scalar(vsip_cvjdot_f(vsipA, vsipB)) case (.cd, .cd): return Scalar(vsip_cvjdot_d(vsipA, vsipB)) default: preconditionFailure("Type not supported for jdot") } } public static func gemp(alpha: Scalar, matA: Matrix, opA: vsip_mat_op, matB: Matrix, opB: vsip_mat_op, beta: Scalar, matC: Matrix) { let t = (matA.type, matB.type, matC.type) let vsipA = matA.vsip let vsipB = matB.vsip let vsipC = matC.vsip switch(t){ case (.d, .d, .d): vsip_gemp_d(alpha.reald, vsipA, opA, vsipB, opB, beta.reald, vsipC) case (.f, .f, .f): vsip_gemp_f(alpha.realf, vsipA, opA, vsipB, opB, beta.realf, vsipC) case (.cd, .cd, .cd): vsip_cgemp_d(alpha.vsip_cd, vsipA, opA, vsipB, opB, beta.vsip_cd, vsipC) case (.cf, .cf, .cf): vsip_cgemp_f(alpha.vsip_cf, vsipA, opA, vsipB, opB, beta.vsip_cf, vsipC) default: preconditionFailure("Type not supported for gemp") } } public static func gems(alpha: Scalar, matA: Matrix, opA: vsip_mat_op, beta: Scalar, matC: Matrix){ let t = (matA.type, matC.type) let vsipA = matA.vsip let vsipC = matC.vsip switch(t){ case (.d, .d): vsip_gems_d(alpha.reald, vsipA, opA, beta.reald, vsipC) case (.f, .f): vsip_gems_f(alpha.realf, vsipA, opA, beta.realf, vsipC) case (.cd, .cd): vsip_cgems_d(alpha.vsip_cd, vsipA, opA, beta.vsip_cd, vsipC) case (.cf, .cf): vsip_cgems_f(alpha.vsip_cf, vsipA, opA, beta.vsip_cf, vsipC) default: preconditionFailure("Type not supported for gemp") } } public static func kron(alpha: Scalar, vecX: Vector, vecY: Vector, resutltsIn matC: Matrix){ let t = (vecX.type, vecY.type, matC.type) let vsipX = vecX.vsip let vsipY = vecY.vsip let vsipC = matC.vsip switch(t){ case (.f, .f, .f): vsip_vkron_f(alpha.realf, vsipX, vsipY, vsipC) case (.d, .d, .d): vsip_vkron_d(alpha.reald, vsipX, vsipY, vsipC) case (.cf, .cf, .cf): vsip_cvkron_f(alpha.vsip_cf, vsipX, vsipY, vsipC) case (.cd, .cd, .cd): vsip_cvkron_d(alpha.vsip_cd, vsipX, vsipY, vsipC) default: preconditionFailure("Kron not supported for argument list") } } public static func kron(alpha: Scalar, matA: Matrix, matB: Matrix, resutltsIn matC: Matrix){ let t = (matA.type, matB.type, matC.type) let vsipA = matA.vsip let vsipB = matB.vsip let vsipC = matC.vsip switch(t){ case (.f, .f, .f): vsip_mkron_f(alpha.realf, vsipA, vsipB, vsipC) case (.d, .d, .d): vsip_mkron_d(alpha.reald, vsipA, vsipB, vsipC) case (.cf, .cf, .cf): vsip_cmkron_f(alpha.vsip_cf, vsipA, vsipB, vsipC) case (.cd, .cd, .cd): vsip_cmkron_d(alpha.vsip_cd, vsipA, vsipB, vsipC) default: preconditionFailure("Kron not supported for argument list") } } public static func prod3(_ matA: Matrix,prod matB: Matrix, resutltsIn matC: Matrix){ let t = (matA.type, matB.type, matC.type) let vsipA = matA.vsip let vsipB = matB.vsip let vsipC = matC.vsip switch(t){ case (.f, .f, .f): vsip_mprod3_f(vsipA, vsipB, vsipC) case (.d, .d, .d): vsip_mprod3_d(vsipA, vsipB, vsipC) case (.cf, .cf, .cf): vsip_cmprod3_f(vsipA, vsipB, vsipC) case (.cd, .cd, .cd): vsip_cmprod3_d(vsipA, vsipB, vsipC) default: preconditionFailure("VSIP function prod3 not supported for argument list") } } public static func prod3(_ matA: Matrix,times vecB: Vector, resutltsIn vecC: Vector){ let t = (matA.type, vecB.type, vecC.type) let vsipA = matA.vsip let vsipB = vecB.vsip let vsipC = vecC.vsip switch(t){ case (.f, .f, .f): vsip_mvprod3_f(vsipA, vsipB, vsipC) case (.d, .d, .d): vsip_mvprod3_d(vsipA, vsipB, vsipC) case (.cf, .cf, .cf): vsip_cmvprod3_f(vsipA, vsipB, vsipC) case (.cd, .cd, .cd): vsip_cmvprod3_d(vsipA, vsipB, vsipC) default: preconditionFailure("VSIP function prod4 not supported for argument list") } } public static func prod4(_ matA: Matrix, times matB: Matrix, resutltsIn matC: Matrix){ let t = (matA.type, matB.type, matC.type) let vsipA = matA.vsip let vsipB = matB.vsip let vsipC = matC.vsip switch(t){ case (.f, .f, .f): vsip_mprod4_f(vsipA, vsipB, vsipC) case (.d, .d, .d): vsip_mprod4_d(vsipA, vsipB, vsipC) case (.cf, .cf, .cf): vsip_cmprod4_f(vsipA, vsipB, vsipC) case (.cd, .cd, .cd): vsip_cmprod4_d(vsipA, vsipB, vsipC) default: preconditionFailure("VSIP function prod4 not supported for argument list") } } public static func prod4(_ matA: Matrix, prod vecB: Vector, resutltsIn vecC: Vector){ let t = (matA.type, vecB.type, vecC.type) let vsipA = matA.vsip let vsipB = vecB.vsip let vsipC = vecC.vsip switch(t){ case (.f, .f, .f): vsip_mvprod4_f(vsipA, vsipB, vsipC) case (.d, .d, .d): vsip_mvprod4_d(vsipA, vsipB, vsipC) case (.cf, .cf, .cf): vsip_cmvprod4_f(vsipA, vsipB, vsipC) case (.cd, .cd, .cd): vsip_cmvprod4_d(vsipA, vsipB, vsipC) default: preconditionFailure("VSIP function prod4 not supported for argument list") } } public static func prod(_ matA: Matrix,prod matB: Matrix,resultsIn matC: Matrix){ let t = (matA.type, matB.type, matC.type) let vsipA = matA.vsip let vsipB = matB.vsip let vsipC = matC.vsip switch(t){ case (.cd, .cd, .cd): vsip_cmprod_d ( vsipA, vsipB, vsipC ) case (.cf, .cf, .cf): vsip_cmprod_f ( vsipA, vsipB, vsipC ) case (.d, .d, .d): vsip_mprod_d ( vsipA, vsipB, vsipC ) case (.f, .f, .f): vsip_mprod_f ( vsipA, vsipB, vsipC ) default: preconditionFailure("VSIP function prod not supported for argument list") } } public static func prod(_ matA: Matrix, times vecB: Vector,resultsIn vecC: Vector){ let t = (matA.type, vecB.type, vecC.type) let vsipA = matA.vsip let vsipB = vecB.vsip let vsipC = vecC.vsip switch(t){ case (.cd, .cd, .cd): vsip_cmvprod_d ( vsipA, vsipB, vsipC ) case (.cf, .cf, .cf): vsip_cmvprod_f ( vsipA, vsipB, vsipC ) case (.d, .d, .d): vsip_mvprod_d ( vsipA, vsipB, vsipC ) case (.f, .f, .f): vsip_mvprod_f ( vsipA, vsipB, vsipC ) default: preconditionFailure("VSIP function prod not supported for argument list") } } public static func prod(_ vecA: Vector, times matB: Matrix, resultsIn vecC: Vector){ let t = (vecA.type, matB.type, vecC.type) let vsipA = vecA.vsip let vsipB = matB.vsip let vsipC = vecC.vsip switch(t){ case (.cd, .cd, .cd): vsip_cvmprod_d ( vsipA, vsipB, vsipC ) case (.cf, .cf, .cf): vsip_cvmprod_f ( vsipA, vsipB, vsipC ) case (.d, .d, .d): vsip_vmprod_d ( vsipA, vsipB, vsipC ) case (.f, .f, .f): vsip_vmprod_f ( vsipA, vsipB, vsipC ) default: preconditionFailure("VSIP function prod not supported for argument list") } } public static func prodh(_ matA: Matrix,timesHermitian matB: Matrix, resultsIn matC: Matrix){ let t = (matA.type, matB.type, matC.type) let vsipA = matA.vsip let vsipB = matB.vsip let vsipC = matC.vsip switch(t){ case (.cd, .cd, .cd): vsip_cmprodh_d ( vsipA, vsipB, vsipC ) case (.cf, .cf, .cf): vsip_cmprodh_f ( vsipA, vsipB, vsipC ) default: preconditionFailure("VSIP function prodh not supported for argument list") } } public static func prodj(_ matA: Matrix, timesConjugate matB: Matrix, resultsIn matC: Matrix){ let t = (matA.type, matB.type, matC.type) let vsipA = matA.vsip let vsipB = matB.vsip let vsipC = matC.vsip switch(t){ case (.cd, .cd, .cd): vsip_cmprodj_d ( vsipA, vsipB, vsipC ) case (.cf, .cf, .cf): vsip_cmprodj_f ( vsipA, vsipB, vsipC ) default: preconditionFailure("VSIP function prodj not supported for argument list") } } public static func prodt(_ matA: Matrix,timesTranspose matB: Matrix, resultsIn matC: Matrix){ let t = (matA.type, matB.type, matC.type) let vsipA = matA.vsip let vsipB = matB.vsip let vsipC = matC.vsip switch(t){ case (.cd, .cd, .cd): vsip_cmprodt_d ( vsipA, vsipB, vsipC ) case (.cf, .cf, .cf): vsip_cmprodt_f ( vsipA, vsipB, vsipC ) case (.d, .d, .d): vsip_mprodt_d ( vsipA, vsipB, vsipC ) case (.f, .f, .f): vsip_mprodt_f ( vsipA, vsipB, vsipC ) default: preconditionFailure("VSIP function prodt not supported for argument list") } } public static func trans(_ matA: Matrix, transposeIn matC: Matrix){ let t = (matA.type, matC.type) let vsipA = matA.vsip let vsipC = matC.vsip switch(t) { case (.cd, .cd): vsip_cmtrans_d(vsipA, vsipC) case(.cf, .cf): vsip_cmtrans_f(vsipA, vsipC) case(.d, .d): vsip_mtrans_d(vsipA, vsipC) case(.f, .f): vsip_mtrans_f(vsipA, vsipC) default: preconditionFailure("VSIP function trans not supported for argument list") } } public static func dot(product vecX: Vector, with vecY: Vector) -> Scalar { let t = (vecX.type, vecY.type) let vsipX = vecX.vsip let vsipY = vecY.vsip switch(t){ case (.f, .f): return Scalar(Float(vsip_vdot_f(vsipX, vsipY))) case (.d, .d): return Scalar(Double(vsip_vdot_d(vsipX, vsipY))) case (.cf, .cf): return Scalar(vsip_cvdot_f(vsipX, vsipY)) case (.cd, .cd): return Scalar(vsip_cvdot_d(vsipX, vsipY)) default: preconditionFailure("Kron not supported for argument list") } } public static func outer(alpha: Scalar, vecX: Vector, vecY: Vector, matC: Matrix){ let vsipX = vecX.vsip let vsipY = vecY.vsip let vsipC = matC.vsip let t = (vecX.type, vecY.type, matC.type) switch(t){ case (.f, .f, .f): vsip_vouter_f(alpha.realf, vsipX, vsipY, vsipC) case (.d, .d, .d): vsip_vouter_d(alpha.reald, vsipX, vsipY, vsipC) case (.cf, .cf, .cf): vsip_cvouter_f(alpha.vsip_cf, vsipX, vsipY, vsipC) case (.cd, .cd, .cd): vsip_cvouter_d(alpha.vsip_cd, vsipX, vsipY, vsipC) default: preconditionFailure("Function outer not supported for argument list") } } // Mark: - Simple Solvers public static func covsol(_ A: Matrix, inputOutput: Matrix) -> Int { let t = (A.type, inputOutput.type) switch t { case (.f, .f): return Int(vsip_covsol_f(A.vsip, inputOutput.vsip)) case (.d, .d): return Int(vsip_covsol_d(A.vsip, inputOutput.vsip)) case (.cf, .cf): return Int(vsip_ccovsol_f(A.vsip, inputOutput.vsip)) case (.cd, .cd): return Int(vsip_ccovsol_d(A.vsip, inputOutput.vsip)) default: preconditionFailure("Type \(t) not supported by covsol") } } // MARK: - Chold public class Chold { var size: Int var type: Block.Types { return (jVsip?.type)! } fileprivate var vsip: OpaquePointer { get { return (jVsip?.vsip)! } } fileprivate class chol { var tryVsip : OpaquePointer? var vsip: OpaquePointer { get { return tryVsip! } } let jInit : JVSIP var type : Vsip.Block.Types? init(){ jInit = JVSIP() } } fileprivate class chol_d: chol { init(size: Int){ super.init() self.type = .d if let chold = vsip_chold_create_d(VSIP_TR_LOW, vsip_length(size)){ self.tryVsip = chold } else { preconditionFailure("Failed to create vsip cholesky object") } } deinit{ if _isDebugAssertConfiguration(){ print("vsip_chold_destroy_d \(jInit.myId.int32Value)") } vsip_chold_destroy_d(self.vsip) } } fileprivate class chol_f: chol { init(size: Int){ super.init() self.type = .f if let chold = vsip_chold_create_f(VSIP_TR_LOW, vsip_length(size)){ self.tryVsip = chold } else { preconditionFailure("Failed to create vsip cholesky object") } } deinit{ if _isDebugAssertConfiguration(){ print("vsip_chold_destroy_f \(jInit.myId.int32Value)") } vsip_chold_destroy_f(self.vsip) } } fileprivate class chol_cd: chol { init(size: Int){ super.init() self.type = .cd if let chold = vsip_cchold_create_d(VSIP_TR_LOW, vsip_length(size)){ self.tryVsip = chold } else { preconditionFailure("Failed to create vsip cholesky object") } } deinit{ if _isDebugAssertConfiguration(){ print("vsip_cchold_destroy_d \(jInit.myId.int32Value)") } vsip_cchold_destroy_d(self.vsip) } } fileprivate class chol_cf: chol { init(size: Int){ super.init() self.type = .cf if let chold = vsip_cchold_create_f(VSIP_TR_LOW, vsip_length(size)){ self.tryVsip = chold } else { preconditionFailure("Failed to create vsip cholesky object") } } deinit{ if _isDebugAssertConfiguration(){ print("vsip_cchold_destroy_f \(jInit.myId.int32Value)") } vsip_cchold_destroy_f(self.vsip) } } fileprivate let jVsip : chol? init(type: Vsip.Block.Types, size: Int) { self.size = size switch type { case .f: self.jVsip = chol_f(size: size) case .d: self.jVsip = chol_d(size: size) case .cf: self.jVsip = chol_cf(size: size) case .cd: self.jVsip = chol_cd(size: size) default: preconditionFailure ("type \(type) not found for cholesky decomposition") } } public func decompose(_ A: Matrix) -> Int { let t = (self.type, A.type) switch t { case (.f, .f): return Int(vsip_chold_f(self.vsip, A.vsip)) case (.d, .d): return Int(vsip_chold_d(self.vsip, A.vsip)) case (.cf, .cf): return Int(vsip_cchold_f(self.vsip, A.vsip)) case (.cd, .cd): return Int(vsip_cchold_d(self.vsip, A.vsip)) default: preconditionFailure("Type \(t) not supported for cholesky decompostion") } } public func solve(_ XB: Matrix) -> Int { let t = (self.type, XB.type) switch t { case (.f, .f): return Int(vsip_cholsol_f(self.vsip, XB.vsip)) case (.d, .d): return Int(vsip_cholsol_d(self.vsip, XB.vsip)) case (.cf, .cf): return Int(vsip_ccholsol_f(self.vsip, XB.vsip)) case (.cd, .cd): return Int(vsip_ccholsol_d(self.vsip, XB.vsip)) default: preconditionFailure ("type \(type) not found for cholesky decomposition") } } } // MARK: - LU public class LUD { var type: Block.Types { return (jVsip?.type)! } fileprivate class lu { var tryVsip : OpaquePointer? var vsip: OpaquePointer { get { return tryVsip! } } let jInit : JVSIP var type : Block.Types? init(){ jInit = JVSIP() } } fileprivate class lu_f: lu{ init(_ size: Int){ super.init() type = .f if let lud = vsip_lud_create_f(vsip_length(size)){ self.tryVsip = lud } else { preconditionFailure("Failed to create vsip svd object") } } deinit{ if _isDebugAssertConfiguration(){ print("vsip_lud_destroy_f \(jInit.myId.int32Value)") } vsip_lud_destroy_f(self.vsip) } } fileprivate class lu_d: lu{ init(_ size: Int){ super.init() type = .d if let lud = vsip_lud_create_d(vsip_length(size)){ self.tryVsip = lud } else { preconditionFailure("Failed to create vsip svd object") } } deinit{ if _isDebugAssertConfiguration(){ print("vsip_lud_destroy_d \(jInit.myId.int32Value)") } vsip_lud_destroy_d(self.vsip) } } fileprivate class clu_f: lu{ init(_ size: Int){ super.init() type = .cf if let lud = vsip_clud_create_f(vsip_length(size)){ self.tryVsip = lud } else { preconditionFailure("Failed to create vsip svd object") } } deinit{ if _isDebugAssertConfiguration(){ print("vsip_clud_destroy_f \(jInit.myId.int32Value)") } vsip_clud_destroy_f(self.vsip) } } fileprivate class clu_d: lu{ init(_ size: Int){ super.init() type = .cd if let lud = vsip_clud_create_d(vsip_length(size)){ self.tryVsip = lud } else { preconditionFailure("Failed to create vsip svd object") } } deinit{ if _isDebugAssertConfiguration(){ print("vsip_clud_destroy_d \(jInit.myId.int32Value)") } vsip_clud_destroy_d(self.vsip) } } fileprivate let jVsip : lu? fileprivate var vsip: OpaquePointer { get { return (jVsip?.vsip)! } } init(type: Vsip.Block.Types, size: Int) { switch type { case .f: jVsip = lu_f(size) case .d: jVsip = lu_d(size) case .cf: jVsip = clu_f(size) case .cd: jVsip = clu_d(size) default: preconditionFailure("Type \(type) not supported") } } public func decompose(_ A: Matrix) -> Int{ let t = (self.type, A.type) switch t{ case (.f, .f): return Int(vsip_lud_f(self.vsip, A.vsip)) case (.d, .d): return Int(vsip_lud_d(self.vsip, A.vsip)) case (.cf, .cf): return Int(vsip_clud_f(self.vsip, A.vsip)) case (.cd, .cd): return Int(vsip_clud_d(self.vsip, A.vsip)) default: preconditionFailure("Type \(t) not found for lud decompose") } } public func solve(matOp: vsip_mat_op, _ XB: Matrix) -> Int{ let t = (matOp, self.type, XB.type) switch t { case (VSIP_MAT_NTRANS,.f,.f): return Int(vsip_lusol_f(self.vsip, VSIP_MAT_NTRANS, XB.vsip)) case (VSIP_MAT_NTRANS,.d,.d): return Int(vsip_lusol_d(self.vsip, VSIP_MAT_NTRANS, XB.vsip)) case (VSIP_MAT_NTRANS,.cf,.cf): return Int(vsip_clusol_f(self.vsip, VSIP_MAT_NTRANS, XB.vsip)) case (VSIP_MAT_NTRANS,.cd,.cd): return Int(vsip_clusol_d(self.vsip, VSIP_MAT_NTRANS, XB.vsip)) case (VSIP_MAT_TRANS,.f,.f): return Int(vsip_lusol_f(self.vsip, VSIP_MAT_TRANS, XB.vsip)) case (VSIP_MAT_TRANS,.d,.d): return Int(vsip_lusol_d(self.vsip, VSIP_MAT_TRANS, XB.vsip)) case (VSIP_MAT_HERM,.cf,.cf): return Int(vsip_clusol_f(self.vsip, VSIP_MAT_HERM, XB.vsip)) case (VSIP_MAT_HERM,.cd,.cd): return Int(vsip_clusol_d(self.vsip, VSIP_MAT_HERM, XB.vsip)) default: preconditionFailure("Type \(t) not found for lud solve") } } } // MARK: - QRD public class QRD{ fileprivate struct Attrib { let m: Int let n: Int let op: vsip_qrd_qopt } var type: Block.Types { return (jVsip?.type)! } fileprivate(set) var amSet = false fileprivate let attrib: Attrib var columnLength: Int { get{ return attrib.m } } var rowLength: Int { get { return attrib.n } } var qrdNoSaveQ: Bool{ get { return attrib.op == VSIP_QRD_NOSAVEQ } } var qrdSaveQ: Bool{ get { return attrib.op == VSIP_QRD_SAVEQ } } var qrdSaveQ1: Bool{ get { return attrib.op == VSIP_QRD_SAVEQ1 } } fileprivate class qr { var tryVsip : OpaquePointer? var vsip: OpaquePointer { get { return tryVsip! } } let jInit : JVSIP var type : Block.Types? init(){ jInit = JVSIP() } } fileprivate class qr_f: qr { init(m: Int, n: Int, qopt: vsip_qrd_qopt){ super.init() type = .f if let qrd = vsip_qrd_create_f(vsip_length(m),vsip_length(n),qopt){ self.tryVsip = qrd } else { preconditionFailure("Failed to create vsip qrd object") } } deinit{ if _isDebugAssertConfiguration(){ print("vsip_qrd_destroy_f \(jInit.myId.int32Value)") } vsip_qrd_destroy_f(self.vsip) } } fileprivate class qr_d: qr { init(m: Int, n: Int, qopt: vsip_qrd_qopt){ super.init() type = .d if let qrd = vsip_qrd_create_d(vsip_length(m),vsip_length(n),qopt){ self.tryVsip = qrd } else { preconditionFailure("Failed to create vsip qrd object") } } deinit{ if _isDebugAssertConfiguration(){ print("vsip_qrd_destroy_d \(jInit.myId.int32Value)") } vsip_qrd_destroy_d(self.vsip) } } fileprivate class cqr_f: qr { init(m: Int, n: Int, qopt: vsip_qrd_qopt){ super.init() type = .cf if let qrd = vsip_cqrd_create_f(vsip_length(m),vsip_length(n),qopt){ self.tryVsip = qrd } else { preconditionFailure("Failed to create vsip qrd object") } } deinit{ if _isDebugAssertConfiguration(){ print("vsip_cqrd_destroy_f \(jInit.myId.int32Value)") } vsip_cqrd_destroy_f(self.vsip) } } fileprivate class cqr_d: qr { init(m: Int, n: Int, qopt: vsip_qrd_qopt){ super.init() type = .cd if let qrd = vsip_cqrd_create_d(vsip_length(m),vsip_length(n),qopt){ self.tryVsip = qrd } else { preconditionFailure("Failed to create vsip qrd object") } } deinit{ if _isDebugAssertConfiguration(){ print("vsip_cqrd_destroy_d \(jInit.myId.int32Value)") } vsip_cqrd_destroy_d(self.vsip) } } fileprivate let jVsip : qr? fileprivate var vsip: OpaquePointer { get { return (jVsip?.vsip)! } } init(type: Block.Types, columnLength: Int, rowLength: Int, qopt: vsip_qrd_qopt) { attrib = Attrib(m: columnLength, n: rowLength, op: qopt) self.amSet = false switch type { case .f: jVsip = qr_f(m: columnLength, n: rowLength, qopt: qopt) case .d: jVsip = qr_d(m: columnLength, n: rowLength, qopt: qopt) case .cf: jVsip = cqr_f(m: columnLength, n: rowLength, qopt: qopt) case .cd: jVsip = cqr_d(m: columnLength, n: rowLength, qopt: qopt) default: self.jVsip = nil assert(false, "QRD not supported for this type") } } public func decompose(_ aMatrix: Matrix) -> Scalar { let t = (aMatrix.type, self.type) switch t { case(.f,.f): return Scalar(vsip_qrd_f(self.vsip, aMatrix.vsip)) case(.d,.d): return Scalar(vsip_qrd_d(self.vsip, aMatrix.vsip)) case(.cf,.cf): return Scalar(vsip_cqrd_f(self.vsip, aMatrix.vsip)) case(.cd,.cd): return Scalar(vsip_cqrd_d(self.vsip, aMatrix.vsip)) default: preconditionFailure("Types \(t) not supported for qrd decompostion") } } public func prodq(matrixOperator op: vsip_mat_op, matrixSide side: vsip_mat_side, matrix: Matrix) { let t = (self.type, op, side, matrix.type) switch t{ case (.f, VSIP_MAT_NTRANS, VSIP_MAT_LSIDE, .f): vsip_qrdprodq_f(self.vsip, op, side, matrix.vsip) case (.d, VSIP_MAT_NTRANS, VSIP_MAT_LSIDE, .d): vsip_qrdprodq_d(self.vsip, op, side, matrix.vsip) case (.cf, VSIP_MAT_NTRANS, VSIP_MAT_LSIDE, .cf): vsip_cqrdprodq_f(self.vsip, op, side, matrix.vsip) case (.cd, VSIP_MAT_NTRANS, VSIP_MAT_LSIDE, .cd): vsip_cqrdprodq_d(self.vsip, op, side, matrix.vsip) case (.f, VSIP_MAT_TRANS, VSIP_MAT_LSIDE, .f): vsip_qrdprodq_f(self.vsip, op, side, matrix.vsip) case (.d, VSIP_MAT_TRANS, VSIP_MAT_LSIDE, .d): vsip_qrdprodq_d(self.vsip, op, side, matrix.vsip) case (.cf, VSIP_MAT_HERM, VSIP_MAT_LSIDE, .cf): vsip_cqrdprodq_f(self.vsip, op, side, matrix.vsip) case (.cd, VSIP_MAT_HERM, VSIP_MAT_LSIDE, .cd): vsip_cqrdprodq_d(self.vsip, op, side, matrix.vsip) case (.f, VSIP_MAT_NTRANS, VSIP_MAT_RSIDE, .f): vsip_qrdprodq_f(self.vsip, op, side, matrix.vsip) case (.d, VSIP_MAT_NTRANS, VSIP_MAT_RSIDE, .d): vsip_qrdprodq_d(self.vsip, op, side, matrix.vsip) case (.cf, VSIP_MAT_NTRANS, VSIP_MAT_RSIDE, .cf): vsip_cqrdprodq_f(self.vsip, op, side, matrix.vsip) case (.cd, VSIP_MAT_NTRANS, VSIP_MAT_RSIDE, .cd): vsip_cqrdprodq_d(self.vsip, op, side, matrix.vsip) case (.f, VSIP_MAT_TRANS, VSIP_MAT_RSIDE, .f): vsip_qrdprodq_f(self.vsip, op, side, matrix.vsip) case (.d, VSIP_MAT_TRANS, VSIP_MAT_RSIDE, .d): vsip_qrdprodq_d(self.vsip, op, side, matrix.vsip) case (.cf, VSIP_MAT_HERM, VSIP_MAT_RSIDE, .cf): vsip_cqrdprodq_f(self.vsip, op, side, matrix.vsip) case (.cd, VSIP_MAT_HERM, VSIP_MAT_RSIDE, .cd): vsip_cqrdprodq_d(self.vsip, op, side, matrix.vsip) default: preconditionFailure("Type \(t) not supported for QRD prodq.") } } public func solveR(matrixOperator opR: vsip_mat_op, alpha: Scalar, XB: Matrix) -> Int { let t = (opR, XB.type) switch t { case (VSIP_MAT_NTRANS, .f): return Int(vsip_qrdsolr_f(self.vsip, VSIP_MAT_NTRANS, alpha.vsip_f, XB.vsip)) case (VSIP_MAT_TRANS, .f): return Int(vsip_qrdsolr_f(self.vsip, VSIP_MAT_TRANS, alpha.vsip_f, XB.vsip)) case (VSIP_MAT_NTRANS, .d): return Int(vsip_qrdsolr_d(self.vsip, VSIP_MAT_NTRANS, alpha.vsip_d, XB.vsip)) case (VSIP_MAT_TRANS, .f): return Int(vsip_qrdsolr_d(self.vsip, VSIP_MAT_TRANS, alpha.vsip_d, XB.vsip)) case (VSIP_MAT_NTRANS, .cf): return Int(vsip_cqrdsolr_f(self.vsip, VSIP_MAT_NTRANS, alpha.vsip_cf, XB.vsip)) case (VSIP_MAT_TRANS, .cf): return Int(vsip_cqrdsolr_f(self.vsip, VSIP_MAT_HERM, alpha.vsip_cf, XB.vsip)) case (VSIP_MAT_NTRANS, .d): return Int(vsip_cqrdsolr_d(self.vsip, VSIP_MAT_NTRANS, alpha.vsip_cd, XB.vsip)) case (VSIP_MAT_TRANS, .f): return Int(vsip_cqrdsolr_d(self.vsip, VSIP_MAT_HERM, alpha.vsip_cd, XB.vsip)) default: preconditionFailure("Case \(t) not found for solveR") } } public func solveCovariance(solveProblem prob: vsip_qrd_prob, XB: Matrix) -> Int { let t = (prob, XB.type) switch t { case (VSIP_COV, .f): return Int(vsip_qrsol_f(self.vsip, VSIP_COV, XB.vsip)) case (VSIP_LLS, .f): return Int(vsip_qrsol_f(self.vsip, VSIP_LLS, XB.vsip)) case (VSIP_COV, .d): return Int(vsip_qrsol_d(self.vsip, VSIP_COV, XB.vsip)) case (VSIP_LLS, .d): return Int(vsip_qrsol_d(self.vsip, VSIP_LLS, XB.vsip)) case (VSIP_COV, .cf): return Int(vsip_cqrsol_f(self.vsip, VSIP_COV, XB.vsip)) case (VSIP_LLS, .cf): return Int(vsip_cqrsol_f(self.vsip, VSIP_LLS, XB.vsip)) case (VSIP_COV, .cd): return Int(vsip_cqrsol_d(self.vsip, VSIP_COV, XB.vsip)) case (VSIP_LLS, .cd): return Int(vsip_cqrsol_d(self.vsip, VSIP_LLS, XB.vsip)) default: preconditionFailure("Case \(t) not found for Covariance/LeastSquare solver") } } } // MARK: - SVD // needs work on error checks /*! For SVD given input matrix A we have A = U S transpose(V) */ public class Svd { let type: Block.Types let n: Int // length of singular value vector var amSet = false fileprivate let jVsip : sv? public struct Attrib { let m: Int let n: Int let saveU: vsip_svd_uv let saveV: vsip_svd_uv init(columnLength: Int, rowLength: Int, saveU: vsip_svd_uv, saveV: vsip_svd_uv){ m=columnLength n=rowLength self.saveU=saveU self.saveV=saveV } var size : (Int, Int) { return (m,n) } } let attr : Attrib fileprivate class sv { var tryVsip : OpaquePointer? var tryS: OpaquePointer? var vsip: OpaquePointer { get { return tryVsip! } } var s: OpaquePointer { get { return tryS! } } let jInit : JVSIP var type : Block.Types? init(){ jInit = JVSIP() } } fileprivate class sv_f : sv { init(m: Int, n: Int, saveU: vsip_svd_uv, saveV: vsip_svd_uv){ super.init() type = .f if let svd = vsip_svd_create_f(vsip_length(m),vsip_length(n),saveU,saveV){ self.tryVsip = svd } else { preconditionFailure("Failed to create vsip svd object") } if let s = vsip_vcreate_f(vsip_length((m<n) ? m:n),VSIP_MEM_NONE){ self.tryS = s } else { preconditionFailure("Failed to create vsip s object") } } deinit{ if _isDebugAssertConfiguration(){ print("vsip_svd_destroy_f \(jInit.myId.int32Value)") print("svd s destroy") } vsip_svd_destroy_f(self.vsip) vsip_valldestroy_f(self.s) } } fileprivate class sv_d : sv { init(m: Int, n: Int, saveU: vsip_svd_uv, saveV: vsip_svd_uv){ super.init() type = .f if let svd = vsip_svd_create_d(vsip_length(m),vsip_length(n),saveU,saveV){ self.tryVsip = svd } else { preconditionFailure("Failed to create vsip svd object") } if let s = vsip_vcreate_d(vsip_length((m<n) ? m:n),VSIP_MEM_NONE){ self.tryS = s } else { preconditionFailure("Failed to create vsip s object") } } deinit{ if _isDebugAssertConfiguration(){ print("vsip_svd_destroy_d \(jInit.myId.int32Value)") print("svd s destroy") } vsip_svd_destroy_d(self.vsip) vsip_valldestroy_d(self.s) } } fileprivate class csv_f : sv { init(m: Int, n: Int, saveU: vsip_svd_uv, saveV: vsip_svd_uv){ super.init() type = .cf if let svd = vsip_csvd_create_f(vsip_length(m),vsip_length(n),saveU,saveV){ self.tryVsip = svd } else { preconditionFailure("Failed to create vsip svd object") } if let s = vsip_vcreate_f(vsip_length((m<n) ? m:n),VSIP_MEM_NONE){ self.tryS = s } else { preconditionFailure("Failed to create vsip s object") } } deinit{ if _isDebugAssertConfiguration(){ print("vsip_svd_destroy_f \(jInit.myId.int32Value)") print("svd s destroy") } vsip_csvd_destroy_f(self.vsip) vsip_valldestroy_f(self.s) } } fileprivate class csv_d : sv { init(m: Int, n: Int, saveU: vsip_svd_uv, saveV: vsip_svd_uv){ super.init() type = .cd if let svd = vsip_csvd_create_d(vsip_length(m),vsip_length(n),saveU,saveV){ self.tryVsip = svd } else { preconditionFailure("Failed to create vsip svd object") } if let s = vsip_vcreate_d(vsip_length((m<n) ? m:n),VSIP_MEM_NONE){ self.tryS = s } else { preconditionFailure("Failed to create vsip s object") } } deinit{ if _isDebugAssertConfiguration(){ print("vsip_csvd_destroy_cd \(jInit.myId.int32Value)") print("svd s destroy") } vsip_csvd_destroy_d(self.vsip) vsip_valldestroy_d(self.s) } } public init(type: Block.Types,columnLength m: Int, rowLength n: Int, saveU: vsip_svd_uv, saveV: vsip_svd_uv){ self.n = (m<n) ? m:n self.type = type self.attr = Attrib(columnLength: m, rowLength: n, saveU: saveU, saveV: saveV) switch type { case .d: self.jVsip = sv_d(m: m,n: n,saveU: saveU, saveV: saveV) case .f: self.jVsip = sv_f(m: m,n: n,saveU: saveU, saveV: saveV) case .cd: self.jVsip = csv_d(m: m,n: n,saveU: saveU, saveV: saveV) case .cf: self.jVsip = csv_f(m: m,n: n,saveU: saveU, saveV: saveV) default: self.jVsip = nil assert(false, "SVD not supported for this type") } } public convenience init(view: Matrix, saveU: vsip_svd_uv, saveV: vsip_svd_uv){ self.init(type: view.type, columnLength: view.columnLength, rowLength: view.rowLength, saveU: saveU, saveV: saveV) } public convenience init(view: Matrix){ self.init(type: view.type, columnLength: view.columnLength, rowLength: view.rowLength, saveU: VSIP_SVD_UVFULL, saveV: VSIP_SVD_UVFULL) } fileprivate var vsip: OpaquePointer? { return self.jVsip!.vsip } fileprivate var s: OpaquePointer? {// singular values return self.jVsip!.s } public func decompose(_ matrix: Matrix, singularValues: Vector){ switch (self.type, matrix.type, singularValues.type){ case (.d, .d, .d): vsip_svd_d(self.vsip, matrix.vsip, self.s!) vsip_vcopy_d_d(self.s!, singularValues.vsip) case (.f, .f, .f): vsip_svd_f(self.vsip, matrix.vsip, self.s!) vsip_vcopy_f_f(self.s!, singularValues.vsip) case (.cd, .cd, .d): vsip_csvd_d(self.vsip, matrix.vsip, self.s!) vsip_vcopy_d_d(self.s!, singularValues.vsip) case (.cf, .cf, .f): vsip_csvd_f(self.vsip, matrix.vsip, self.s!) vsip_vcopy_f_f(self.s!, singularValues.vsip) default: preconditionFailure("function not supported for input/resultsIn views") } self.amSet = true } public func decompose(_ matrix: Matrix) -> Vector { let v: Vsip.Vector switch matrix.type { case .cd, .d: v = Vector(length: self.n, type: .d) case .cf, .f: v = Vector(length: self.n, type: .f) default: preconditionFailure("Case not found for decompose") } self.decompose(matrix, singularValues: v) return v } /*! Function matU returns 0 on success Output data is stored in matrix matU in natural order starting at element index (0,0). Matrix matU must be large enough to hold the resultsIn data */ public func matU(_ lowColumn: Int, highColumn: Int, matU: Matrix) -> Int { let low = vsip_scalar_vi(lowColumn) let high = vsip_scalar_vi(highColumn) assert(low <= high, "Error in column selection") let highMax = vsip_scalar_vi((matU.rowLength)) let vsipSv = self.vsip // VSIPL pointer to singular value object let vsipC = matU.vsip // VSIPL pointer to U Matrix switch (self.attr.saveU, matU.type, self.type){ case (VSIP_SVD_UVFULL, .f, .f): return Int(vsip_svdmatu_f(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVFULL, .cf, .cf): return Int(vsip_csvdmatu_f(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVFULL, .d, .d): return Int(vsip_svdmatu_d(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVFULL, .cd, .cd): return Int(vsip_csvdmatu_d(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVPART, .f, .f): precondition(high <= highMax, "Input matrix row length to small") return Int(vsip_svdmatu_f(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVPART, .cf, .cf): precondition(high <= highMax, "Input matrix row length to small") return Int(vsip_csvdmatu_f(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVPART, .d, .d): precondition(high <= highMax, "Input matrix row length to small") return Int(vsip_svdmatu_d(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVPART, .cd, .cd): precondition(high <= highMax, "Input matrix row length to small") return Int(vsip_csvdmatu_d(vsipSv, low, high, vsipC)) default: if self.attr.saveU == VSIP_SVD_UVNOS{ preconditionFailure("SVD Created without U Matrix") } else { preconditionFailure("SVD Not supported for these types") } } } /*! Function matV returns 0 on success Output data is stored in matrix matV in natural order starting at element index (0,0). Matrix matV must be large enough to hold the resultsIn data */ public func matV(_ lowColumn: Int, highColumn: Int, matV: Matrix) -> Int { let low = vsip_scalar_vi(lowColumn) let high = vsip_scalar_vi(highColumn) assert(low <= high, "Error in column selection") let highMax = vsip_scalar_vi(matV.rowLength) let vsipSv = self.vsip // VSIPL pointer to singular value object let vsipC = matV.vsip // VSIPL pointer to V Matrix switch (self.attr.saveU, matV.type, self.type){ case (VSIP_SVD_UVFULL, .f, .f): return Int(vsip_svdmatv_f(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVFULL, .cf, .cf): return Int(vsip_csvdmatv_f(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVFULL, .d, .d): return Int(vsip_svdmatv_d(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVFULL, .cd, .cd): return Int(vsip_csvdmatv_d(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVPART, .f, .f): precondition(high <= highMax, "Input matrix row length to small") return Int(vsip_svdmatv_f(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVPART, .cf, .cf): precondition(high <= highMax, "Input matrix row length to small") return Int(vsip_csvdmatv_f(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVPART, .d, .d): precondition(high <= highMax, "Input matrix row length to small") return Int(vsip_svdmatv_d(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVPART, .cd, .cd): precondition(high <= highMax, "Input matrix row length to small") return Int(vsip_csvdmatv_d(vsipSv, low, high, vsipC)) default: if self.attr.saveU == VSIP_SVD_UVNOS { preconditionFailure("SVD Created without V Matrix") } else { preconditionFailure("SVD Not supported for these types") } } } public func produ(op: vsip_mat_op, side: vsip_mat_side, matrix: Matrix) -> Int { let vsipSv = self.vsip let vsipC = matrix.vsip switch (self.attr.saveU, matrix.type, self.type){ case (VSIP_SVD_UVFULL, .f, .f): return Int(vsip_svdprodu_f(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVFULL, .cf, .cf): return Int(vsip_csvdprodu_f(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVFULL, .d, .d): return Int(vsip_svdprodu_d(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVFULL, .cd, .cd): return Int(vsip_csvdprodu_d(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVPART, .f, .f): return Int(vsip_svdprodu_f(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVPART, .cf, .cf): return Int(vsip_csvdprodu_f(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVPART, .d, .d): return Int(vsip_svdprodu_d(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVPART, .cd, .cd): return Int(vsip_csvdprodu_d(vsipSv, op, side, vsipC)) default: if self.attr.saveU == VSIP_SVD_UVNOS { preconditionFailure("SVD Created without U Matrix") } else { preconditionFailure("SVD Not supported for these types") } } } public func prodv(op: vsip_mat_op, side: vsip_mat_side, matrix: Matrix) -> Int { let vsipSv = self.vsip let vsipC = matrix.vsip switch (self.attr.saveV, matrix.type, self.type){ case (VSIP_SVD_UVFULL, .f, .f): return Int(vsip_svdprodv_f(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVFULL, .cf, .cf): return Int(vsip_csvdprodv_f(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVFULL, .d, .d): return Int(vsip_svdprodv_d(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVFULL, .cd, .cd): return Int(vsip_csvdprodv_d(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVPART, .f, .f): return Int(vsip_svdprodv_f(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVPART, .cf, .cf): return Int(vsip_csvdprodv_f(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVPART, .d, .d): return Int(vsip_svdprodv_d(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVPART, .cd, .cd): return Int(vsip_csvdprodv_d(vsipSv, op, side, vsipC)) default: if self.attr.saveU == VSIP_SVD_UVNOS { preconditionFailure("SVD Created without V Matrix") } else { preconditionFailure("SVD Not supported for these types") } } } public var sizeU: (Int, Int){ get { var retval = (self.attr.m, self.attr.m) switch self.attr.saveU { case VSIP_SVD_UVFULL: return retval case VSIP_SVD_UVPART: if self.attr.m > self.attr.n { retval.1 = self.attr.n } return retval default: return (0,0) } } } public var sizeV: (Int, Int){ get { var retval = (self.attr.n, self.attr.n) switch self.attr.saveU { case VSIP_SVD_UVFULL: return retval case VSIP_SVD_UVPART: if self.attr.n > self.attr.m { retval.1 = self.attr.m } return retval default: return (0,0) } } } public var matU: Matrix? { get { if !amSet { return nil } if self.attr.saveU == VSIP_SVD_UVNOS { return nil } let (m,n) = self.sizeU let mat = Matrix(columnLength: m, rowLength: n, type: self.type, major: VSIP_ROW) let success = self.matU(0, highColumn: n-1, matU: mat) if success == 0 { return mat } else { return nil } } } public var matV: Matrix? { get { if !amSet { return nil } if self.attr.saveU == VSIP_SVD_UVNOS { return nil } let (m,n) = self.sizeV let mat = Matrix(columnLength: m, rowLength: n, type: self.type, major: VSIP_ROW) let success = self.matV(0, highColumn: n-1, matV: mat) if success == 0 { return mat } else { return nil } } } } // MARK: - JVSIP added functionality public class Jvsip { public static func normFro(view: Vector) -> Vsip.Scalar { switch view.type { case .f: return Vsip.sumsqval(view).sqrt case .d: return Vsip.sumsqval(view).sqrt case.cf: return (Vsip.sumsqval(view.real) + Vsip.sumsqval(view.imag)).sqrt case.cd: return (Vsip.sumsqval(view.real) + Vsip.sumsqval(view.imag)).sqrt default: preconditionFailure("normFro not supported for this view") } } public static func normFro(view: Matrix) -> Vsip.Scalar { switch view.type { case .f: return Vsip.sumsqval(view).sqrt case .d: return Vsip.sumsqval(view).sqrt case.cf: return (Vsip.sumsqval(view.real) + Vsip.sumsqval(view.imag)).sqrt case.cd: return (Vsip.sumsqval(view.real) + Vsip.sumsqval(view.imag)).sqrt default: preconditionFailure("normFro not supported for this view") } } public static func decompose(_ aMatrix: Vsip.Matrix) -> (Q: Vsip.Matrix, R: Vsip.Matrix){ let qrd = Vsip.QRD(type: aMatrix.type, columnLength: aMatrix.columnLength, rowLength: aMatrix.rowLength, qopt: VSIP_QRD_SAVEQ) let Q = Vsip.Matrix(columnLength: qrd.columnLength, rowLength: qrd.columnLength, type: aMatrix.type, major: VSIP_ROW) let R = Vsip.Matrix(columnLength: qrd.columnLength, rowLength: qrd.rowLength, type: aMatrix.type, major: VSIP_ROW) let aCopy = aMatrix.newCopy Q.fill(Scalar(0.0)) R.fill(Scalar(0.0)) print("create/destroy Q.diagview") Q.diagview.fill(Vsip.Scalar(1.0)) print("call qrd.decompose") let _ = qrd.decompose(aMatrix) qrd.prodq(matrixOperator: VSIP_MAT_NTRANS, matrixSide: VSIP_MAT_LSIDE, matrix: Q) print("create Qt") let Qt = Q.transview Vsip.prod(Qt, prod: aCopy, resultsIn: R) return (Q,R) } } } <file_sep>/* Created RJudd September 25, 1997 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cvsqrt_f.c,v 2.0 2003/02/22 15:18:52 judd Exp $ */ /* Modified RJudd June 28, 1998 */ /* to add complex block support */ /* Removed Development Mode RJudd Sept 00 */ #include"vsip.h" #include"vsip_cvviewattributes_f.h" void (vsip_cvsqrt_f)( const vsip_cvview_f *a, const vsip_cvview_f *r) { /* r_j = sqrt(a_j) */ { vsip_length n = r->length; vsip_stride cast = a->block->cstride; vsip_stride crst = r->block->cstride; vsip_scalar_f *apr = (vsip_scalar_f *)((a->block->R->array) + cast * a->offset), *rpr = (vsip_scalar_f *)((r->block->R->array) + crst * r->offset); vsip_scalar_f *api = (vsip_scalar_f *)((a->block->I->array) + cast * a->offset), *rpi = (vsip_scalar_f *)((r->block->I->array) + crst * r->offset); vsip_stride ast = (cast * a->stride), rst = (crst * r->stride); while(n-- > 0) { /* the following is a modified version of vsip_csqrt_f */ if (0.0 == *api) { if(*apr < 0.0) { *rpi = (vsip_scalar_f)sqrt(-*apr); *rpr = 0.0; } else { *rpr = (vsip_scalar_f)sqrt(*apr); *rpi = (vsip_scalar_f)0.0; } } else { if (0.0 == *apr) { if(*api > 0.0) { *rpi = (vsip_scalar_f)sqrt(0.5 * *api); *rpr = *rpi; } else { *rpi = (vsip_scalar_f)sqrt(0.5 * -*api); *rpr = - *rpi; } } else { vsip_scalar_f mag = (vsip_scalar_f)sqrt(0.5 * ((vsip_scalar_f)sqrt(*apr * *apr + *api * *api) + ((*apr > 0) ? *apr : -*apr))); vsip_scalar_f s = *api/(vsip_scalar_f)( 2.0 * mag); if(*apr < 0.0) { if(*api < 0.0) { *rpr = -s; *rpi = - mag; } else { *rpr = s; *rpi = mag; } } else { *rpr = mag; *rpi = s; } } } apr += ast; api += ast; rpr += rst; rpi += rst; } } } <file_sep>/* Created RJudd August 28, 1999 */ /* SPAWARSYSCEN D881 */ /* private attributes for real qrd */ #ifndef _vsip_qrddattributes_d_h #define _vsip_qrdattributes_d_h 1 #include"vsip_mviewattributes_d.h" #include"vsip_vviewattributes_d.h" struct vsip_qrdattributes_d{ vsip_qrd_qopt qopt; vsip_length M; vsip_length N; vsip_mview_d *A; vsip_mview_d AA; vsip_vview_d *v; vsip_vview_d *w; vsip_scalar_d *beta; }; #endif /*_vsip_qrdattributes_d_h */ <file_sep>/* Created RJudd */ /* $Id: vsip_mpermute_once_d.c,v 2.1 2008/09/03 17:54:03 judd Exp $ */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"vsip.h" #include"vsip_mviewattributes_d.h" #include"vsip_vviewattributes_vi.h" void vsip_mpermute_once_d( const vsip_mview_d* in, vsip_major major, const vsip_vview_vi* p, const vsip_mview_d* out){ vsip_length n_dta; /* length of data row/col to copy */ vsip_length n_ind; /* length of matrix col/row to index */ vsip_stride in_dta_strd, out_dta_strd; vsip_stride in_ind_strd, out_ind_strd; vsip_index i,j; if(major == VSIP_ROW){ n_dta = in->row_length; n_ind = in->col_length; in_dta_strd = in->row_stride * in->block->rstride; in_ind_strd = in->col_stride * in->block->rstride; out_dta_strd = out->row_stride * out->block->rstride; out_ind_strd = out->col_stride * out->block->rstride; } else { n_dta = in->col_length; n_ind = in->row_length; in_dta_strd = in->col_stride * in->block->rstride; in_ind_strd = in->row_stride * in->block->rstride; out_dta_strd = out->col_stride * out->block->rstride; out_ind_strd = out->row_stride * out->block->rstride; } if(in == out) { /* in-place */ vsip_scalar_d *ptr = in->block->array + in->offset * in->block->rstride; vsip_scalar_vi *b = p->block->array + p->offset; for(i=0; i<n_ind; i++){ vsip_index r_or_c = b[i * p->stride]; /* row or column to copy to */ register vsip_index from0 = b[i * p->stride] * in_ind_strd; register vsip_index to0 = i * in_ind_strd; if(from0 != to0) { for(j=0; j<n_dta; j++){ vsip_index to = to0 + j * in_dta_strd; vsip_index from = from0 + j * in_dta_strd; vsip_scalar_d t = ptr[to]; ptr[to] = ptr[from]; ptr[from] = t; } j=i; while(i != b[j * p->stride]){ j++; if(j > n_ind) exit(-1); } b[j * p->stride] = r_or_c; } } } else { /* out-of-place */ vsip_scalar_d *in_ptr = in->block->array + in->offset * in->block->rstride; vsip_scalar_d *out_ptr = out->block->array + out->offset * out->block->rstride; vsip_scalar_vi *in = p->block->array + p->offset; for(i=0; i<n_ind; i++){ vsip_scalar_d *pin = in_ptr + in[i * p->stride] * in_ind_strd; vsip_scalar_d *pout = out_ptr + i * out_ind_strd; for(j=0; j < n_dta; j++){ *pout = *pin; pout += out_dta_strd; pin += in_dta_strd; } } } return; } <file_sep>/* Created RJudd October 6, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_mrealview_d.h,v 2.1 2003/03/09 22:41:17 judd Exp $ */ #ifndef _VI_MREALVIEW_D_H #define _VI_MREALVIEW_D_H #include"vsip_cmviewattributes_d.h" #include"vsip_mviewattributes_d.h" static vsip_mview_d* VI_mrealview_d( const vsip_cmview_d* X, vsip_mview_d* Y) { Y->block = X->block->R; Y->offset = X->offset; Y->row_length = X->row_length; Y->col_length = X->col_length; Y->row_stride = X->row_stride; Y->col_stride = X->col_stride; Y->markings = VSIP_VALID_STRUCTURE_OBJECT; return Y; } #endif /* _VI_MREALVIEW_D_H */ <file_sep>from vsip import * def __isSizeCompatible(a,b): if 'mview' in a.type and 'mview' in b.type: if (a.rowlength == b.rowlength) and (a.collength == b.collength): return True elif 'vview' in a.type and 'vview' in b.type: if a.length == b.length: return True else: return False # vsip_cvjdot_p # vsip_dvdot_p # jdot and dot are not supported as functions. Use the view method jdot and dot instead. #vsip_cmherm_p def herm(a,b): """ Returns the N by M matrix C, which is the Hermitian (conjugate transpose) of an M by N matrix. If N==M (the matrix is square) then this may be done in-place. """ f={'cmview_dcmview_d':vsip_cmherm_d, 'cmview_fcmview_f':vsip_cmherm_f} assert 'pyJvsip' in repr(a) and 'pyJvsip' in repr(b),\ 'Arguments one must by pyJvsip views for function herm' assert a.rowlength == b.collength and a.collength == b.rowlength, 'Input sizes not compliant.' t=a.type+b.type assert t in f, 'Type <:'+t+':> not supported for function herm' f[t](a.vsip,b.vsip) return b # vsip_dgemp_p def gemp(alpha,a,op_a,b,op_b,beta,c): """ General Matrix Product C = alpha * op_a(a).prod(op_b(b)) + beta * C See VSIP specification for additional information. This function is always in place into C. Usage: gemp(alpha, a, op_a, b, op_b, beta, c) Where: alpha is a scalar multiplier on view op_a(a) a is a matrix view of type (real or complex) float op_a is a matrix operation on view a b is a matrix view of the same type as a op_b is a matrix operation on view b beta is a scalar multiplier on view c c is a view of the same type as a (input/output) op_a and op_b may be 'NTRANS', 'TRANS', 'HERM', or 'CONJ' if a and b are real then 'HERM' is the same as 'TRANS' and 'CONJ' is the same as 'NTRANS' """ opc={0:VSIP_MAT_NTRANS,1:VSIP_MAT_TRANS,2:VSIP_MAT_HERM,3:VSIP_MAT_CONJ, 'NTRANS':VSIP_MAT_NTRANS,'TRANS':VSIP_MAT_TRANS,'HERM':VSIP_MAT_HERM, 'CONJ':VSIP_MAT_CONJ} opr={0:VSIP_MAT_NTRANS,1:VSIP_MAT_TRANS,2:VSIP_MAT_TRANS,3:VSIP_MAT_NTRANS, 'NTRANS':VSIP_MAT_NTRANS,'TRANS':VSIP_MAT_TRANS,'HERM':VSIP_MAT_TRANS, 'CONJ':VSIP_MAT_NTRANS} f={'cmview_d':vsip_cgemp_d, 'cmview_f':vsip_cgemp_f, 'mview_d':vsip_gemp_d, 'mview_f':vsip_gemp_f} assert 'pyJvsip' in repr(a) and 'pyJvsip' in repr(b)\ and 'pyJvsip' in repr(c),\ 'Arguments 2, 4,and 7 must by pyJvsip views for function gemp' assert b.type == a.type and c.type == a.type,\ 'Arguments 2, 4 and 7 must be the same type' t = a.type assert t in f, 'Type <:'+t+':> not supported by function gemp' assert op_a in opc,'Matrix operation flag not recognized' assert op_b in opc,'Matrix operation flag not recognized' assert isinstance(alpha,float) or isinstance(alpha,int) or isinstance(alpha,complex),\ 'Argument one must be a scalar' assert isinstance(beta,float) or isinstance(beta,int) or isinstance(beta,complex),\ 'Argument six must be a scalar' if t=='cmview_d': f[t](vsip_cmplx_d(alpha.real,alpha.imag),a.vsip,opc[op_a],b.vsip,opc[op_b],\ vsip_cmplx_d(beta.real,beta.imag),c.vsip) return c elif t == 'cmview_f': f[t](vsip_cmplx_f(alpha.real,alpha.imag),a.vsip,opc[op_a],b.vsip,opc[op_b],\ vsip_cmplx_f(beta.real,beta.imag),c.vsip) return c else: assert isinstance(alpha,float) or isinstance(alpha,int), \ 'For type mview_f or mview_d the first argument must be a real scalar' assert isinstance(beta,float) or isinstance(beta,int), \ 'For type mview_f or mview_d the sixth argument must be a real scalar' f[t](float(alpha),a.vsip,opr[op_a],b.vsip,opr[op_b],float(beta),c.vsip) return c # vsip_dgems_p def gems(alpha,a,op_a,beta,c): """ General matrix sum C = alpha * op_a(A) + beta * C This function is always in-place into C Usage: C = gems(alpha,A,op_a,beta,C) Where: alpha is a scalar multiplier A is a matrix op_a is a matrix operator on A beta is a scalar multiplier of view C C is a matrix of the same type as A (input/output) op_a may be 'NTRANS', 'TRANS', 'HERM', or 'CONJ' if a is real then 'HERM' is the same as 'TRANS' and 'CONJ' is the same as 'NTRANS' """ opc={0:VSIP_MAT_NTRANS,1:VSIP_MAT_TRANS,2:VSIP_MAT_HERM,3:VSIP_MAT_CONJ, 'NTRANS':VSIP_MAT_NTRANS,'TRANS':VSIP_MAT_TRANS,'HERM':VSIP_MAT_HERM, 'CONJ':VSIP_MAT_CONJ} opr={0:VSIP_MAT_NTRANS,1:VSIP_MAT_TRANS,2:VSIP_MAT_TRANS,3:VSIP_MAT_NTRANS, 'NTRANS':VSIP_MAT_NTRANS,'TRANS':VSIP_MAT_TRANS,'HERM':VSIP_MAT_TRANS, 'CONJ':VSIP_MAT_NTRANS} f={'cmview_d':vsip_cgems_d,'cmview_f':vsip_cgems_f, 'mview_d':vsip_gems_d,'mview_f':vsip_gems_f} assert 'pyJvsip' in repr(a) and 'pyJvsip' in repr(c),\ 'Arguments 2, 5 must by pyJvsip views for function gems' assert a.type==c.type, 'View arguments must be the same type for functions gems' t=a.type assert t in f, 'Type <:'+t+':> not supported for function gems' assert op_a in opc, 'Matrix operation flag not recognized' assert isinstance(alpha,float) or isinstance(alpha,int) or isinstance(alpha,complex),\ 'Argument one must be a scalar' assert isinstance(beta,float) or isinstance(beta,int) or isinstance(beta,complex),\ 'Argument four must be a scalar' if t == 'cmview_d': f[t](vsip_cmplx_d(alpha.real,alpha.imag),a.vsip,opc[op_a],\ vsip_cmplx_d(beta.real,beta.imag),c.vsip) return c elif t == 'cmview_f': f[t](vsip_cmplx_f(alpha.real,alpha.imag),a.vsip,opc[op_a],\ vsip_cmplx_f(beta.real,beta.imag),c.vsip) return c else: f[t](float(alpha),a.vsip,opc[op_a],float(beta),c.vsip) return c # vsip_dskron_p def kron(alpha,a,b,c): """ See VSIP Spec for additional information """ f={'cmview_dcmview_dcmview_d':vsip_cmkron_d, 'cmview_fcmview_fcmview_f':vsip_cmkron_f, 'cvview_dcvview_dcmview_d':vsip_cvkron_d, 'cvview_fcvview_fcmview_f':vsip_cvkron_f, 'mview_dmview_dmview_d':vsip_mkron_d, 'mview_fmview_fmview_f':vsip_mkron_f, 'vview_dvview_dmview_d':vsip_vkron_d, 'vview_fvview_fmview_f':vsip_vkron_f} assert 'pyJvsip' in repr(a) and 'pyJvsip' in repr(b)\ and 'pyJvsip' in repr(c),\ 'Arguments 2, 3, and 4 must by pyJvsip views for function kron' assert isinstance(alpha,float) or isinstance(alpha,int) or isinstance(alpha,complex),\ 'Argument one must be a scalar' t=a.type+b.type+c.type assert t in f, 'Type <:'+t+':> not recognized for function kron' if 'vview' in a.type: N=a.length; M=b.length else: N = a.rowlength * b.rowlength; M = a.collength * b.collength assert c.rowlength == N and c.collength == M, 'Matrix C is not sized properly' if 'cmview_d' in t: f[t](vsip_cmplx_d(alpha.real,alpha.imag),a.vsip,b.vsip,c.vsip) return c elif 'cmview_f' in t: f[t](vsip_cmplx_f(alpha.real,alpha.imag),a.vsip,b.vsip,c.vsip) return c else: f[t](float(alpha),a.vsip,b.vsip,c.vsip) return c # vsip_dmvprod3_p # vsip_dmprod3_p def prod3(a,b,c): """ Matrix Product Not in-place prod3(a,b,c) Argument a is an input matrix view of size (3,3) Argument b is an input matrix view of size (3,N) or vector view of length 3 Argument c is an output matrix view of size (3,N) or vector view of length 3 """ f={'cmview_dcmview_dcmview_d':vsip_cmprod3_d, 'cmview_fcmview_fcmview_f':vsip_cmprod3_f, 'mview_dmview_dmview_d':vsip_mprod3_d, 'mview_fmview_fmview_f':vsip_mprod3_f, 'cmview_dcvview_dcvview_d':vsip_cmvprod3_d,'cmview_fcvview_fcvview_f':vsip_cmvprod3_f, 'mview_dvview_dvview_d':vsip_mvprod3_d,'mview_fvview_fvview_f':vsip_mvprod3_f} assert 'pyJvsip' in repr(a) and 'pyJvsip' in repr(b)\ and 'pyJvsip' in repr(c),\ 'Arguments by pyJvsip views for function prod3' t=a.type+b.type+c.type assert t in f, 'Type <:'+t+':> not supported by prod3' assert a.rowlength == 3 and a.collength == 3,\ 'The first argument to prod3 must be size (3,3)' if 'vview' in t: assert b.length == 3 and c.length == 3, 'Size error in prod3' else: assert b.collength == 3, 'The second argument to prod3 must have column length of 3' assert c.collength == 3, 'The third argument to prod3 must have column length of 3' assert c.rowlength == b.rowlength, \ 'The size of the second argument and third argument must be the same for function prod3' f[t](a.vsip,b.vsip,c.vsip) return c # vsip_dmvprod4_p # vsip_dmprod4_p def prod4(a,b,c): """ Matrix Product Not in-place prod4(a,b,c) Argument a is an input matrix view of size (4,4) Argument b is an input matrix view of size (4,N) or vector view of length 4 Argument c is an output matrix view of size (4,N) or vector view of length 4 """ f={'cmview_dcmview_dcmview_d':vsip_cmprod4_d, 'cmview_fcmview_fcmview_f':vsip_cmprod4_f, 'mview_dmview_dmview_d':vsip_mprod4_d, 'mview_fmview_fmview_f':vsip_mprod4_f, 'cmview_dcvview_dcvview_d':vsip_cmvprod4_d,'cmview_fcvview_fcvview_f':vsip_cmvprod4_f, 'mview_dvview_dvview_d':vsip_mvprod4_d,'mview_fvview_fvview_f':vsip_mvprod4_f} assert 'pyJvsip' in repr(a) and 'pyJvsip' in repr(b)\ and 'pyJvsip' in repr(c),\ 'Arguments by pyJvsip views for function prod4' t=a.type+b.type+c.type assert t in f, 'Type <:'+t+':> not supported by prod4' assert a.rowlength == 4 and a.collength == 4,\ 'The first argument to prod4 must be size (4,4)' if 'vview' in t: assert b.length == 4 and c.length == 4, 'Size error in prod4' else: assert b.collength == 4, 'The second argument to prod4 must have column length of 4' assert c.collength == 4, 'The third argument to prod4 must have column length of 4' assert c.rowlength == b.rowlength, \ 'The size of the second argument and third argument must be the same for function prod4' f[t](a.vsip,b.vsip,c.vsip) return c # vsip_dmprod_p # vsip_dmvprod_p # vsip_dvmprod_p def prod(a,b,c): """ Standard matrix product. In-Place not supported. prod includes mprod and mvprod and vmprod. See specification pages in VSIP spec for more information. """ f={'cmview_dcmview_dcmview_d':vsip_cmprod_d, 'cmview_fcmview_fcmview_f':vsip_cmprod_f, 'cmview_dcvview_dcvview_d':vsip_cmvprod_d, 'cmview_fcvview_fcvview_f':vsip_cmvprod_f, 'cvview_dcmview_dcvview_d':vsip_cvmprod_d, 'cvview_fcmview_fcvview_f':vsip_cvmprod_f, 'mview_dmview_dmview_d':vsip_mprod_d, 'mview_fmview_fmview_f':vsip_mprod_f, 'vview_dmview_dvview_d':vsip_vmprod_d, 'vview_fmview_fvview_f':vsip_vmprod_f, 'mview_dvview_dvview_d':vsip_mvprod_d, 'mview_fvview_fvview_f':vsip_mvprod_f} assert 'pyJvsip' in repr(a) and 'pyJvsip' in repr(b) \ and 'pyJvsip' in repr(c), 'Arguments to prod must be pyJvsip views' t=a.type+b.type+c.type assert t in f,'Type <:'+t+':> not recognized by function prod' if 'mview' in a.type and 'mview' in b.type: assert b.collength == a.rowlength and c.collength == a.collength \ and b.rowlength == c.rowlength, 'Size error in function prod' f[t](a.vsip,b.vsip,c.vsip) return c elif 'mview' in a.type and 'vview' in b.type: assert a.rowlength == b.length and a.collength == c.length, \ 'Size error in function prod' f[t](a.vsip,b.vsip,c.vsip) return c else: # a.type is vector and b.type is matrix assert a.length == b.collength and b.rowlength == c.length, \ 'Size error in function prod' f[t](a.vsip,b.vsip,c.vsip) return c # vsip_dmtrans_p def trans(a,b): """ Function trans is a corner turn. In-place is not supported. """ f={'cmview_dcmview_d':vsip_cmtrans_d, 'cmview_fcmview_f':vsip_cmtrans_f, 'mview_dmview_d':vsip_mtrans_d, 'mview_fmview_f':vsip_mtrans_f} assert 'pyJvsip' in repr(a) and 'pyJvsip' in repr(b),\ 'Argmuments to function trans must be pyJvsip views' t=a.type+b.type assert t in f, 'Type <:'+t+':> not recognized for function trans' assert a.rowlength == b.collength and a.collength == b.rowlength, \ 'Size error in function trans' f[t](a.vsip,b.vsip) return b # vsip_cmprodh_p def prodh(a,b,c): """ Matrix Hermitian Product; See VSIPL specification for more Info. Not in-place Usage: prodh(a,b,c) Where: a View of input M by P matrix. b View of input M by P matrix. c View of output M by N matrix. Matrices are complex float. """ assert 'pyJvsip' in repr(a) and 'pyJvsip' in repr(b)\ and 'pyJvsip' in repr(c),\ 'Arguments must by pyJvsip views for function prodh' assert a.type == b.type and a.type == c.type,'View types must agree for prodh' f={'cmview_d':vsip_cmprodh_d,'cmview_f':vsip_cmprodh_f} t=a.type assert t in f,'Type <:'+t+':> not recognized for function prodh' assert a.collength == c.collength and a.rowlength == b.rowlength \ and b.collength == c.rowlength, 'Size error in prodh' f[t](a.vsip,b.vsip,c.vsip) return c # vsip_cmprodj_p def prodj(a,b,c): """ Matrix Conjugate Product; See VSIPL specification for more Information. Not in-place Usage: prodh(a,b,c) Where: a View of input M by P matrix. b View of input P by N matrix. c View of output M by N matrix. Matrices are complex float. """ assert 'pyJvsip' in repr(a) and 'pyJvsip' in repr(b)\ and 'pyJvsip' in repr(c),\ 'Arguments must by pyJvsip views for function prodj' assert a.type == b.type and a.type == c.type,'View types must agree for prodj' f={'cmview_d':vsip_cmprodj_d, 'cmview_f':vsip_cmprodj_f} t=a.type assert t in f,'Type <:'+t+':> not recognized for function prodh' assert a.collength == c.collength and a.rowlength == b.collength \ and b.rowlength == c.rowlength, 'Size error in prodj' f[t](a.vsip,b.vsip,c.vsip) return c # vsip_dmprodt_p def prodt(a,b,c): """ Matrix Transpose Product; See VSIPL Specification for more Information. Usage: prodh(a,b,c) Where: a View of input M by P matrix. b View of input M by P matrix. c View of output M by N matrix. Matrices are real or complex float. """ assert 'pyJvsip' in repr(a) and 'pyJvsip' in repr(b)\ and 'pyJvsip' in repr(c),\ 'Arguments must by pyJvsip views for function prodt' assert a.type == b.type and a.type == c.type,'View types must agree for prodt' f={'cmview_d':vsip_cmprodt_d, 'cmview_f':vsip_cmprodt_f, 'mview_d':vsip_mprodt_d, 'mview_f':vsip_mprodt_f} t=a.type assert t in f,'Type <:'+t+':> not recognized for function prodh' assert a.collength == c.collength and a.rowlength == b.rowlength \ and b.collength == c.rowlength, 'Size error in prodt' f[t](a.vsip,b.vsip,c.vsip) return c # vsip_dvouter_p def outer(alpha,a,b,c): """ Outer Product. See VSIPL spec for more Information. Usage: outer(alpha,a,b,c) Where: alpha is a scalar multiplier. If a,b,c are real views then alpha may not be complex. a is a pyJvsip vector view b is a pyJvsip vector view c is a pyJvsip matrix view """ f={'cvview_dcvview_dcmview_d':vsip_cvouter_d,'cvview_fcvview_fcmview_f':vsip_cvouter_f, 'vview_dvview_dmview_d':vsip_vouter_d,'vview_fvview_fmview_f':vsip_vouter_f} assert isinstance(alpha,float) or isinstance(alpha,int) or isinstance(alpha,complex),\ 'Argument one must be a scalar' assert 'pyJvsip' in repr(a) and 'pyJvsip' in repr(b)\ and 'pyJvsip' in repr(c),\ 'Arguments 2,3 & 4 must be pyJvsip views for function outer' t=a.type+b.type+c.type assert t in f assert c.collength == a.length and c.rowlength == b.length, 'Size error in function outer' if 'cvview_d' in t: f[t](vsip_cmplx_d(alpha.real,alpha.imag),a.vsip,b.vsip,c.vsip) elif 'cvview_f' in t: f[t](vsip_cmplx_f(alpha.real,alpha.imag),a.vsip,b.vsip,c.vsip) else: assert not isinstance(alpha,complex), \ 'For real views the scalar multiplier must be real for function outer' f[t](float(alpha),a.vsip,b.vsip,c.vsip) return c # vsip_dcovsol_p def covsol(A,XB): """ See VSIPL spec for more information Usage: x=covsol(A,XB) Where: x = 0 on success A is a matrix view. A is overwritten by the calculation. XB is a the input/output view. """ f={'cmview_d':vsip_ccovsol_d, 'cmview_f':vsip_ccovsol_f, 'mview_d':vsip_covsol_d, 'mview_f':vsip_covsol_f} assert 'pyJvsip' in repr(A) and 'pyJvsip' in repr(XB),\ 'Arguments must by pyJvsip views for function covsol' t=A.type assert t in f, 'Type <:'+t+':> not recognized for function covsol' if 'mview' in XB.type: C = XB else: C=XB.block.bind(inOut.offset,inOut.stride,inOut.length,1,1) assert t == C.type, 'Arguments in function covsol must be the same type' assert A.rowlength == C.collength, 'Size error in function covsol' x=f[t](A.vsip,C.vsip) return x # vsip_dllsqsol_p def llsqsol(A,XB): """ See VSIPL spec for more information Usage: x=llsqsol(A,XB) Where: x = 0 on success A is a matrix view. A is overwritten by the calculation. XB is a the input/output view. """ f={'cmview_d':vsip_cllsqsol_d, 'cmview_f':vsip_cllsqsol_f, 'mview_d':vsip_llsqsol_d, 'mview_f':vsip_llsqsol_f} assert 'pyJvsip' in repr(A) and 'pyJvsip' in repr(XB),\ 'Arguments must by pyJvsip views for function llsqsol' t=A.type assert t in f, 'Type <:'+t+':> not recognized for function llsqsol' if 'mview' in XB.type: C = XB else: C=XB.block.bind(inOut.offset,inOut.stride,inOut.length,1,1) assert t == C.type, 'Arguments in function llsqsol must be the same type' assert A.rowlength == C.collength, 'Size error in function llsqsol' x=f[t](A.vsip,C.vsip) return x # vsip_dtoepsol_p def toepsol(t,b,w,x): """ See VSIPL spec for more information Usage: x=toepsol(t,b,w,x) Where: x == 0 on success t View of input vector, t, of length N, the first row of the Toeplitz matrix. b View of input vector, b, of length N. w View of vector, w, of length N used for temporary workspace. x View of output vector, x, of length N. """ f={'cvview_d':vsip_ctoepsol_d,'cvview_f':vsip_ctoepsol_f, 'vview_d':vsip_toepsol_d,'vview_f':vsip_toepsol_f} assert 'pyJvsip' in repr(t) and 'pyJvsip' in repr(b) \ and'pyJvsip' in repr(w) and 'pyJvsip' in repr(x),\ 'Arguments must be pyJvsip views' tp=t.type assert tp in f, 'Type <:'+tp+':> not recognized by toepsol' assert tp == b.type and tp == w.type and tp == x.type,\ 'Arguments to toepsol must all be vector views of the same type' assert t.length == b.length and t.length == w.length and t.length == x.length, \ 'View lengths must all be the same size for function topsol' x=f[tp](t.vsip,b.vsip,w.vsip,x.vsip) return x <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmcopyto_user_f.h,v 1.1 2007/04/18 03:59:06 judd Exp $ */ #include"VU_cmprintm_f.include" static void cmcopyto_user_f(void){ vsip_index i,j; printf("********\nTEST cmcopyto_user_f\n"); { /* check row copy interleaved */ vsip_cblock_f *block = vsip_cblockcreate_f(200,VSIP_MEM_NONE); vsip_scalar_f output[40]; vsip_scalar_f ans[40]={0,0,0,1,0,2,0,3,1,0,1,1,1,2,1,3,2,0,2,1,2,2,2,3,3,0,3,1,3,2,3,3,4,0,4,1,4,2,4,3}; vsip_cmview_f *view = vsip_cmbind_f(block,100,2,5,12,4); vsip_cvview_f *all = vsip_cvbind_f(block,0,1,200); vsip_scalar_f check = 0; vsip_cvfill_f(vsip_cmplx_f(-1,-1),all); for(i=0; i<5; i++){ for(j=0; j < 4; j++){ vsip_cscalar_f t = vsip_cmplx_f((vsip_scalar_f)i,(vsip_scalar_f)j); vsip_cmput_f(view,i,j,t); } } vsip_cmcopyto_user_f(view,VSIP_ROW,output,(vsip_scalar_f*)NULL); printf("check row copy interleaved\n"); VU_cmprintm_f("3.2",view); for(i=0; i<40; i++) { check += fabs(output[i] - ans[i]); printf("%f\n",output[i]); } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_cvdestroy_f(all); vsip_cmdestroy_f(view); vsip_cblockdestroy_f(block); } { /* check col copy interleaved*/ vsip_cblock_f *block = vsip_cblockcreate_f(200,VSIP_MEM_NONE); vsip_scalar_f output[40]; vsip_scalar_f ans[40]={0,0,1,0,2,0,3,0,4,0,0,1,1,1,2,1,3,1,4,1,0,2,1,2,2,2,3,2,4,2,0,3,1,3,2,3,3,3,4,3}; vsip_cmview_f *view = vsip_cmbind_f(block,100,2,5,12,4); vsip_cvview_f *all = vsip_cvbind_f(block,0,1,200); vsip_scalar_f check = 0; vsip_cvfill_f(vsip_cmplx_f(-1,-1),all); for(i=0; i<5; i++){ for(j=0; j < 4; j++){ vsip_cscalar_f t = vsip_cmplx_f((vsip_scalar_f)i,(vsip_scalar_f)j); vsip_cmput_f(view,i,j,t); } } vsip_cmcopyto_user_f(view,VSIP_COL,output,(vsip_scalar_f*)NULL); printf("check col copy interleaved\n"); VU_cmprintm_f("3.2",view); for(i=0; i<40; i++) { check += fabs(output[i] - ans[i]); printf("%f\n",output[i]); } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_cvdestroy_f(all); vsip_cmdestroy_f(view); vsip_cblockdestroy_f(block); } { /* check row copy split */ vsip_cblock_f *block = vsip_cblockcreate_f(200,VSIP_MEM_NONE); vsip_scalar_f output_r[20]; vsip_scalar_f output_i[20]; vsip_scalar_f ans_r[20]={0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4}; vsip_scalar_f ans_i[20]={0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3}; vsip_cmview_f *view = vsip_cmbind_f(block,100,2,5,12,4); vsip_cvview_f *all = vsip_cvbind_f(block,0,1,200); vsip_scalar_f check = 0; vsip_cvfill_f(vsip_cmplx_f(-1,-1),all); for(i=0; i<5; i++){ for(j=0; j < 4; j++){ vsip_cscalar_f t = vsip_cmplx_f((vsip_scalar_f)i,(vsip_scalar_f)j); vsip_cmput_f(view,i,j,t); } } vsip_cmcopyto_user_f(view,VSIP_ROW,output_r,output_i); printf("check row copy split\n"); VU_cmprintm_f("3.2",view); for(i=0; i<20; i++) { check += fabs(output_r[i] - ans_r[i]); check += fabs(output_i[i] - ans_i[i]); printf("%f %f\n",output_r[i],output_i[i]); } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_cvdestroy_f(all); vsip_cmdestroy_f(view); vsip_cblockdestroy_f(block); } { /* check col copy split*/ vsip_cblock_f *block = vsip_cblockcreate_f(200,VSIP_MEM_NONE); vsip_scalar_f output_r[20]; vsip_scalar_f output_i[20]; vsip_scalar_f ans_r[20]={0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4}; vsip_scalar_f ans_i[20]={0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3}; vsip_cmview_f *view = vsip_cmbind_f(block,100,2,5,12,4); vsip_cvview_f *all = vsip_cvbind_f(block,0,1,200); vsip_scalar_f check = 0; vsip_cvfill_f(vsip_cmplx_f(-1,-1),all); for(i=0; i<5; i++){ for(j=0; j < 4; j++){ vsip_cscalar_f t = vsip_cmplx_f((vsip_scalar_f)i,(vsip_scalar_f)j); vsip_cmput_f(view,i,j,t); } } vsip_cmcopyto_user_f(view,VSIP_COL,output_r,output_i); printf("check col copy split\n"); VU_cmprintm_f("3.2",view); for(i=0; i<20; i++) { check += fabs(output_r[i] - ans_r[i]); check += fabs(output_i[i] - ans_i[i]); printf("%f %f\n",output_r[i],output_i[i]); } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_cvdestroy_f(all); vsip_cmdestroy_f(view); vsip_cblockdestroy_f(block); } return; } <file_sep>/* RJudd 22 February, 98 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vcreate_cheby_d.c,v 2.5 2007/04/21 19:39:33 judd Exp $ */ /* Converted matlab code to VSIP */ /* Modifed March 8, 98 */ /* DAVID'S Matlab Code for cheby */ /* // function window = chebyw(nf, ripple) // % nf - window length // % ripple - stopband attenuation in dB // dp = 10.^(-ripple/20); // odd = rem(nf,2); // n2 = fix(nf/2); // df = acos(1/cosh(acosh((1+dp)/dp)/(nf-1)))/pi; // x0 = (3-cos(2*pi*df))/(1.+cos(2*pi*df)); // alpha = (x0 + 1)/2; // beta = (x0 - 1)/2; // k = (0:nf-1); // f = k/nf; // x = alpha*cos(2*pi*f) + beta; // tmp = (abs(x) > 1); // j = sqrt(-1); // wf = dp*(tmp.*(cosh(((nf-1)/2).*acosh(x)))+(1-tmp).*cos(((nf-1)/2).*acos(x))); // if (~odd) // wf = real(wf).*exp(-j*pi*f); // wf(n2+1:nf) = -wf(n2+1:nf); // else // wf = wf +j*zeros(1,nf); // end // wt = fft(wf); // wt = wt(1:nf)/wt(1); // window = real([wt(n2+2:nf) wt(1:n2+1)]'); // %size(window) // %plot(window,1,4*nf) // %plot(window) */ #include<math.h> #include"vsip.h" #include"vsip_vviewattributes_d.h" #include"vsip_cvviewattributes_d.h" #include"vsip_scalars.h" #include"VI_vcreate_d.h" #include"VI_valldestroy_d.h" #include"VI_cvcreate_d.h" #include"VI_cvalldestroy_d.h" #include"VI_vcopy_d_d.h" #include"VI_cvfill_d.h" #include"VI_cvsqrt_d.h" #include"VI_rcvadd_d.h" #include"VI_cvadd_d.h" #include"VI_vramp_d.h" #include"VI_vrealview_d.h" #include"VI_svsub_d.h" #include"VI_vclip_d.h" #include"VI_vacos_d.h" #include"VI_vcos_d.h" #include"VI_svmul_d.h" #include"VI_csvmul_d.h" #include"VI_vmul_d.h" #include"VI_rcvmul_d.h" #include"VI_rscvmul_d.h" #include"VI_veuler_d.h" #include"VI_cvget_d.h" #define cheby_PI ((vsip_scalar_d)3.1415926535897932384626433832795) #define TWOPI ((vsip_scalar_d)6.283185307179586) /* VSIP internal functions below */ /*******************************************************************/ static vsip_scalar_d VI_acosh_d(vsip_scalar_d x){ /*scalar acosh*/ vsip_scalar_d a = x * x; vsip_scalar_d z; vsip_scalar_d C1 = .25; vsip_scalar_d C2 = 3.0/32.0; vsip_scalar_d C3 = 15.0/288.0; vsip_scalar_d C4 = 105.0/3072.0; if(x <= 1.0) return 0.0; if(x < 10) return (vsip_scalar_d) log(x + sqrt(a - 1.0)); z = 1.0/a; return (vsip_scalar_d)(log(2.0 * x) - z * (C1 + z * (C2 + z * (C3 + z * C4)))); } /*******************************************************************/ static void VI_cvlog_d(vsip_cvview_d *a,vsip_cvview_d *r) { /* register */ vsip_length n = r->length; vsip_stride cast = a->block->cstride; vsip_stride crst = r->block->cstride; vsip_scalar_d *apr = (vsip_scalar_d *)((a->block->R->array) + cast * a->offset), *rpr = (vsip_scalar_d *)((r->block->R->array) + crst * r->offset); vsip_scalar_d *api = (vsip_scalar_d *)((a->block->I->array) + cast * a->offset), *rpi = (vsip_scalar_d *)((r->block->I->array) + crst * r->offset); /* register */ vsip_stride ast = (cast * a->stride), rst = (crst * r->stride); vsip_scalar_d arg = 0; while(n-- > 0){ arg = (vsip_scalar_d)atan2(*api , *apr); *rpr = (vsip_scalar_d)log(sqrt(*apr * *apr + *api * *api)); *rpi = arg; apr += ast; api += ast; rpr += rst; rpi += rst; } } /*******************************************************************/ static void VI_rcvacosh_d(vsip_vview_d *x, vsip_cvview_d *r){ void VI_cvlog_d(vsip_cvview_d*,vsip_cvview_d*); { vsip_length n = r->length; vsip_stride r_str = r->stride * r->block->cstride; vsip_stride x_str = x->stride * x->block->rstride; vsip_stride r_off = r_str * r->offset; vsip_stride x_off = x_str * x->offset; vsip_scalar_d *x_p = x->block->array + x_off, *rp_r = (vsip_scalar_d*)(r->block->R->array + r_off), *rp_i = (vsip_scalar_d*)(r->block->I->array + r_off); while(n-- > 0){ *rp_r = *x_p * *x_p - (vsip_scalar_d)1.0; *rp_i = (vsip_scalar_d)0; rp_r += r_str; rp_i += r_str; x_p += x_str; } } VI_cvsqrt_d(r,r); VI_rcvadd_d(x,r,r); VI_cvlog_d(r,r); return; } /*******************************************************************/ static void VI_cvcosh_d(vsip_cvview_d *x, vsip_cvview_d *r){ vsip_length n = r->length; vsip_stride stx = x->block->cstride * x->stride, str = r->block->cstride * r->stride; vsip_scalar_d *x_pr = (vsip_scalar_d*)(x->block->R->array + stx * x->offset), *x_pi = (vsip_scalar_d*)(x->block->I->array + stx * x->offset), *r_pr = (vsip_scalar_d*)(r->block->R->array + str * r->offset), *r_pi = (vsip_scalar_d*)(r->block->I->array + str * r->offset), tmp, mag, maginv; while(n-- > 0){ mag = (vsip_scalar_d)0.50 * VSIP_EXP_D(*x_pr); maginv = (vsip_scalar_d)0.25 / mag; tmp = (mag + maginv) * VSIP_COS_D(*x_pi); *r_pi = (mag - maginv) * VSIP_SIN_D(*x_pi); *r_pr = tmp; x_pr += stx; r_pr += str; x_pi += stx; r_pi += str; } } /*******************************************************************/ static void VI_vfreqswap_d(vsip_vview_d *a) { vsip_length n; vsip_length n2 = (a->length / 2); vsip_scalar_d *a_p = a->block->array + a->offset * a->block->rstride, *t_p, tmp; vsip_stride ast = a->stride * a->block->rstride; if(a->length % 2){ t_p = a_p + n2 + 1; tmp = *(t_p - 1); *(t_p - 1) = *a_p; n = n2 - 1; while(n-- > 0){ *a_p = *t_p; a_p += a->stride; *t_p = *a_p; t_p += a->stride; } *a_p = *t_p; *t_p = tmp; } else { n = n2; t_p = a_p + n2 ; while(n-- > 0){ tmp = *t_p; *t_p = *a_p; *a_p = tmp; a_p += ast; t_p += ast; } } } vsip_vview_d* (vsip_vcreate_cheby_d)( vsip_length nf, vsip_scalar_d ripple, vsip_memory_hint hint) { vsip_vview_d *window = VI_vcreate_d(nf,hint); int odd = 0; vsip_length n2 = 0; vsip_scalar_d dp = 0.0, df = 0.0, x0 = 0.0, alpha = 0.0, beta = 0.0; vsip_cvview_d *wf = VI_cvcreate_d(nf,hint), *Cfoo = VI_cvcreate_d(nf,hint); vsip_vview_d *f = VI_vcreate_d(nf,hint), *x = VI_vcreate_d(nf,hint), *tmp = VI_vcreate_d(nf,hint), *nottmp = VI_vcreate_d(nf,hint); vsip_vview_d wwfR; vsip_vview_d *wfR = VI_vrealview_d(wf,&wwfR); vsip_vview_d RRefoo; vsip_vview_d *Refoo = VI_vrealview_d(Cfoo,&RRefoo); /* check for malloc errors, destroy everything and return null on failure */ if((wf == NULL) | (Cfoo == NULL) | (f == NULL) | (x == NULL) | (tmp == NULL) | (wfR == NULL) | (Refoo == NULL) | (window == NULL) | (nottmp == NULL)){ VI_valldestroy_d(x); VI_valldestroy_d(f); VI_valldestroy_d(tmp); VI_cvalldestroy_d(wf); VI_cvalldestroy_d(Cfoo); VI_valldestroy_d(nottmp); VI_valldestroy_d(window); return (vsip_vview_d*)NULL; } VI_cvfill_d(wf->block->a_zero,wf); /* zero fill */ dp = VSIP_EXP10_D(-ripple/20.0);/*dp = 10.^(-ripple/20);*/ odd = ((int)nf) % 2; /*odd = rem(nf,2);*/ n2 = (vsip_length) VSIP_FLOOR_D((vsip_scalar_d)nf/2.0); /*n2 = fix(nf/2);*/ /*df = acos(1/cosh(acosh((1+dp)/dp)/(nf-1)))/pi;*/ df = (vsip_scalar_d)VSIP_ACOS_D(1.0/VSIP_COSH_D(VI_acosh_d(((vsip_scalar_d)1.0 + dp)/dp) / ((vsip_scalar_d)nf - 1.0)))/cheby_PI; /*x0 = (3-cos(2*pi*df))/(1.+cos(2*pi*df));*/ x0 = (vsip_scalar_d)((3. - VSIP_COS_D(TWOPI * df))/(1. + VSIP_COS_D(TWOPI * df))); alpha = (x0 + (vsip_scalar_d)1.0) / (vsip_scalar_d)2.; /*alpha = (x0 + 1)/2;*/ beta = (x0 - (vsip_scalar_d)1.0) / (vsip_scalar_d)2.; /*beta = (x0 - 1)/2;*/ VI_vramp_d(((vsip_scalar_d)0.0),((vsip_scalar_d)1.0/((vsip_scalar_d)nf)),f); /*k = (0:nf-1);f = k/nf;*/ /* x = alpha*cos(2*pi*f) + beta; */ { vsip_length n = nf; vsip_scalar_d *f_p = f->block->array + f->offset, *x_p = x->block->array + x->offset; while(n-- > 0){ *x_p = alpha * (vsip_scalar_d)VSIP_COS_D(TWOPI * *f_p) + beta; x_p += x->stride; f_p += f->stride; } } /* END x = alpha*cos(2*pi*f) + beta; */ /*tmp = (mag(x) > 1); */ { vsip_length n = nf; vsip_scalar_d *x_p = x->block->array + x->offset, *tmp_p = tmp->block->array + tmp->offset; while(n-- > 0){ *tmp_p = (vsip_scalar_d)((((*x_p >= 0) ? *x_p : - *x_p) > 1) ? 1.0 : 0.0); x_p += x->stride; tmp_p += tmp->stride; } } /* END tmp = (mag(x) > 1); */ /* wf = dp*(tmp.*(cosh((((vsip_scalar_d)nf-1.0)/2).*acosh(x)))+ (1-tmp).*cos((((vsip_scalar_d)nf-1.0)/2).*acos(x)));*/ { VI_svsub_d(1.0,tmp,nottmp); VI_vclip_d(x,-1.0,1.0,-1.0,1.0,wfR); /* modified to handle x out side of range of acos*/ /* ensures that for x > 1 default return value of acos is zero */ VI_vacos_d(wfR,Refoo); VI_svmul_d(((vsip_scalar_d)nf-(vsip_scalar_d)1.0)/(vsip_scalar_d)2.0,Refoo,Refoo); VI_vcos_d(Refoo,Refoo); VI_vmul_d(nottmp,Refoo,wfR); VI_rcvacosh_d(x,Cfoo); VI_rscvmul_d(((vsip_scalar_d)nf - (vsip_scalar_d)1.0)/(vsip_scalar_d)2.0,Cfoo,Cfoo); VI_cvcosh_d(Cfoo,Cfoo); VI_rcvmul_d(tmp,Cfoo,Cfoo); VI_cvadd_d(Cfoo,wf,wf); VI_rscvmul_d(dp,wf,wf); } /* END wf = dp*(tmp.*(cosh(((nf-1)/2).*acosh(x)))+ (1-tmp).*cos(((nf-1)/2).*acos(x)));*/ if(!odd ){ /* if (~odd) */ /*wf = real(wf).*exp(-j*pi*f);*/ { VI_svmul_d((vsip_scalar_d)(-cheby_PI),f,f); VI_veuler_d(f,Cfoo); VI_rcvmul_d(wfR,Cfoo,wf); } /*END wf = real(wf).*exp(-j*pi*f);*/ /* wf(n2+1:nf) = -wf(n2+1:nf); */ { vsip_stride str = wf->block->cstride; vsip_length n = n2; vsip_scalar_d *wf_rp = (vsip_scalar_d*)(wf->block->R->array + str * n); vsip_scalar_d *wf_ip = (vsip_scalar_d*)(wf->block->I->array + str * n); while(n-- > 0){ *wf_rp = - *wf_rp; wf_rp += str; *wf_ip = - *wf_ip; wf_ip += str;} } /*END wf(n2+1:nf) = -wf(n2+1:nf);*/ }/* END if (~odd) */ {/* wt = fft(wf); */ vsip_fft_d* fftplan = vsip_ccfftip_create_d(nf,(vsip_scalar_d)(1.0/(vsip_scalar_d)nf),VSIP_FFT_FWD,0,VSIP_ALG_NOISE); vsip_ccfftip_d(fftplan,wf); {/* wt = wt(1:nf)/wt(1) */ vsip_cscalar_d scale; vsip_scalar_d magsq; VI_CVGETP_D(wf,0); scale = VI_CVGET_D(wf); scale.i = -scale.i; magsq = scale.i * scale.i + scale.r * scale.r; scale.i /= magsq; scale.r /= magsq; VI_csvmul_d(scale,wf,wf); } vsip_fft_destroy_d(fftplan); }/*END wt = fft(wf); */ VI_vcopy_d_d(wfR, window); VI_vfreqswap_d(window); VI_valldestroy_d(x); VI_valldestroy_d(f); VI_valldestroy_d(tmp); VI_valldestroy_d(nottmp); VI_cvalldestroy_d(wf); VI_cvalldestroy_d(Cfoo); return window; } <file_sep>/* Created RJudd September 4, 2006 */ /* VSIPL Consultant */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cvcopyfrom_user_f.c,v 2.1 2006/10/20 16:26:36 judd Exp $ */ #include"vsip.h" #include"vsip_cvviewattributes_f.h" void (vsip_cvcopyfrom_user_f)( vsip_scalar_f* const r, vsip_scalar_f* const i, const vsip_cvview_f* a) { vsip_length n = a->length; vsip_stride ast = a->stride * a->block->cstride; vsip_scalar_f *ap_r = (a->block->R->array) + a->offset * a->block->cstride; vsip_scalar_f *ap_i = (a->block->I->array) + a->offset * a->block->cstride; if(i == NULL){ /* user storage must be interleaved */ vsip_scalar_f *rp = r; while(n-- > 0){ *ap_r = *rp; rp++; ap_r += ast; *ap_i = *rp; ap_i+= ast; rp++; } } else { /* user storage must be split */ vsip_scalar_f *rp = r; vsip_scalar_f *ip = i; while(n-- > 0){ *ap_r = *rp; rp++; ap_r += ast; *ap_i = *ip; ap_i+= ast; ip++; } } return; } <file_sep>/* Created RJudd March 17, 1999 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_correlate1d_f.c,v 2.1 2007/04/16 16:50:41 judd Exp $ */ #include"vsip.h" #include"vsip_corr1dattributes_f.h" #include"vsip_cvviewattributes_f.h" #include"vsip_vviewattributes_f.h" #include"VI_vcopy_f_f.h" #include"VI_vfill_f.h" #include"VI_vrealview_f.h" #include"VI_vimagview_f.h" static void VI_vunbiasfull_f( const vsip_corr1d_f *cor, const vsip_vview_f *x, const vsip_vview_f *y) { /* register */ vsip_length n = y->length; /* register */ vsip_length s1 = n - cor->m; /* register */ vsip_length s2 = cor->m; /* register */ vsip_stride xst = x->stride * x->block->rstride, yst = y->stride * y->block->rstride; vsip_scalar_f *xp = (x->block->array) + x->offset * x->block->rstride, *yp = (y->block->array) + y->offset * y->block->rstride; vsip_scalar_f scale2 = (vsip_scalar_f)1.0/(vsip_scalar_f)cor->m, scale1 = (vsip_scalar_f)1.0; while(n-- > s1){ *yp = *xp / scale1; scale1 += 1.0; yp+=yst; xp+=xst; } n++; while(n-- > s2){ *yp = *xp * scale2; yp+=yst; xp+=xst; } n++; n++; while(n-- > 1){ *yp = *xp / (vsip_scalar_f)n; yp+=yst; xp+=xst; } return; } static void VI_vunbiassame_f( const vsip_corr1d_f *cor, const vsip_vview_f *x, const vsip_vview_f *y) { vsip_index i; register vsip_scalar_f mscale = (vsip_scalar_f)cor->m; vsip_length adj = (vsip_length)(cor->m & 1); vsip_length n0 = cor->m/2; vsip_length n1 = cor->n - n0; vsip_length n2 = cor->n; register vsip_scalar_f mceil = (vsip_scalar_f)(n0 + adj); register vsip_scalar_f N = (vsip_scalar_d)(n2 + n0); vsip_stride xst = x->stride * x->block->rstride, yst = y->stride * y->block->rstride; vsip_scalar_f *xp = (x->block->array) + x->offset * x->block->rstride, *yp = (y->block->array) + y->offset * y->block->rstride; for(i=0; i < n0; i++) yp[i * yst] = xp[i * xst] / ((vsip_scalar_f)(i) + mceil); for(i=n0; i < n1; i++) yp[i * yst] = xp[i * xst] / mscale ; for(i=n1; i < n2; i++) yp[i * yst] = xp[i * xst] / (N - (vsip_scalar_f)i); return; } void vsip_correlate1d_f( const vsip_corr1d_f *cor, vsip_bias bias, const vsip_vview_f *h, const vsip_vview_f *x, const vsip_vview_f *y) { vsip_vview_f xxr,xxi,hhr,hhi, *xr = VI_vrealview_f(cor->x,&xxr), *xi = VI_vimagview_f(cor->x,&xxi), *hr = VI_vrealview_f(cor->h,&hhr), *hi = VI_vimagview_f(cor->h,&hhi); xr->length = cor->x->length - x->length; VI_vfill_f(0,xr); xr->offset = xr->length; xr->length = x->length; VI_vcopy_f_f(x,xr); xr->offset = 0; xr->length = cor->x->length; hr->length = h->length; VI_vcopy_f_f(h,hr); hr->offset = hr->length; hr->length = cor->h->length - h->length; VI_vfill_f(0,hr); hr->offset = 0; hr->length = cor->h->length; VI_vfill_f(0,hi); VI_vfill_f(0,xi); vsip_ccfftip_f(cor->fft,cor->h); vsip_ccfftip_f(cor->fft,cor->x); vsip_cvjmul_f(cor->x,cor->h,cor->x); vsip_cvconj_f(cor->x,cor->x); vsip_rscvmul_f(1/(vsip_scalar_f)cor->N,cor->x,cor->x); vsip_ccfftip_f(cor->fft,cor->x); switch(cor->support){ case VSIP_SUPPORT_FULL: xr->offset = xr->length - cor->mn; xr->length = y->length; if(bias == VSIP_UNBIASED){ VI_vunbiasfull_f(cor,xr,y); } else { VI_vcopy_f_f(xr,y); } break; case VSIP_SUPPORT_SAME: xr->offset = xr->length - cor->mn + (cor->m -1 )/2; xr->length = y->length; if(bias == VSIP_UNBIASED){ VI_vunbiassame_f(cor,xr,y); } else { VI_vcopy_f_f(xr,y); } break; case VSIP_SUPPORT_MIN: xr->offset = xr->length - cor->mn + cor->m - 1; xr->length = y->length; if(bias == VSIP_UNBIASED){ vsip_svmul_f((vsip_scalar_f)1.0/(vsip_scalar_f)cor->m,xr,y); } else { VI_vcopy_f_f(xr,y); } break; } return; } <file_sep>/* Created RJudd September 25, 1997 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_cvsqrt_d.h,v 2.0 2003/02/22 15:18:31 judd Exp $ */ #include"vsip.h" #include"vsip_cvviewattributes_d.h" #ifndef VI_CVSQRT_D_H #define VI_CVSQRT_D_H static void VI_cvsqrt_d( const vsip_cvview_d *a, const vsip_cvview_d *r) { /* r_j = sqrt(a_j) */ { vsip_length n = r->length; vsip_stride cast = a->block->cstride; vsip_stride crst = r->block->cstride; vsip_scalar_d *apr = (vsip_scalar_d *)((a->block->R->array) + cast * a->offset), *rpr = (vsip_scalar_d *)((r->block->R->array) + crst * r->offset); vsip_scalar_d *api = (vsip_scalar_d *)((a->block->I->array) + cast * a->offset), *rpi = (vsip_scalar_d *)((r->block->I->array) + crst * r->offset); vsip_stride ast = (cast * a->stride), rst = (crst * r->stride); while(n-- > 0) { /* the following is a modified version of vsip_csqrt_d */ if (0.0 == *api) { if(*apr < 0.0) { *rpi = (vsip_scalar_d)sqrt(-*apr); *rpr = 0.0; } else { *rpr = (vsip_scalar_d)sqrt(*apr); *rpi = (vsip_scalar_d)0.0; } } else { if (0.0 == *apr) { if(*api > 0.0) { *rpi = (vsip_scalar_d)sqrt(0.5 * *api); *rpr = *rpi; } else { *rpi = (vsip_scalar_d)sqrt(0.5 * -*api); *rpr = - *rpi; } } else { vsip_scalar_d mag = (vsip_scalar_d)sqrt(0.5 * ((vsip_scalar_d)sqrt(*apr * *apr + *api * *api) + ((*apr > 0) ? *apr : -*apr))); vsip_scalar_d s = *api/(vsip_scalar_d)( 2.0 * mag); if(*apr < 0.0) { if(*api < 0.0) { *rpr = -s; *rpi = - mag; } else { *rpr = s; *rpi = mag; } } else { *rpr = mag; *rpi = s; } } } apr += ast; api += ast; rpr += rst; rpi += rst; } } } #endif <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cvlog_f.h,v 2.0 2003/02/22 15:23:23 judd Exp $ */ #include"VU_cvprintm_f.include" static void cvlog_f(void){ printf("\n********\nTEST cvlog_f\n\n"); { /* create some space */ vsip_cscalar_f a0,a1,a2,a3,a4,a5; vsip_cvview_f *a = vsip_cvcreate_f(12,VSIP_MEM_NONE); vsip_cvview_f *ab = vsip_cvsubview_f(a,0,6); vsip_cvview_f *ac = vsip_cvsubview_f(a,1,6); vsip_cvview_f *ans = vsip_cvcreate_f(6,VSIP_MEM_NONE); vsip_cvview_f *chk = vsip_cvcreate_f(6,VSIP_MEM_NONE); vsip_vview_f *chk_r = vsip_vimagview_f(chk); vsip_scalar_f data1[12]; vsip_scalar_f data2[6]; vsip_scalar_f data3[6]; vsip_cvview_f *ua = vsip_cvbind_f( vsip_cblockbind_f(data1,(vsip_scalar_f*)NULL,6,VSIP_MEM_NONE), 0,1,6); /* interleaved */ vsip_cvview_f *ub = vsip_cvbind_f( vsip_cblockbind_f(data2,data3,6,VSIP_MEM_NONE), 0,1,6); /* split */ vsip_cblockadmit_f(vsip_cvgetblock_f(ua),VSIP_FALSE); vsip_cblockadmit_f(vsip_cvgetblock_f(ub),VSIP_FALSE); vsip_cvputstride_f(ab,2); vsip_cvputstride_f(ac,2); /* put some data in a */ a0 = vsip_cmplx_f(0,1); a1 = vsip_cmplx_f(1, 0); a2 = vsip_cmplx_f(-1,VSIP_MEM_NONE); a3 = vsip_cmplx_f(1,1); a4 = vsip_cmplx_f(1,-1); a5 = vsip_cmplx_f(0,1); vsip_cvput_f(ab,0,a0); vsip_cvput_f(ab,1,a1); vsip_cvput_f(ab,2,a2); vsip_cvput_f(ab,3,a3); vsip_cvput_f(ab,4,a4); vsip_cvput_f(ab,5,a5); a0 = vsip_cmplx_f(0,1.5708); a1 = vsip_cmplx_f(0, 0); a2 = vsip_cmplx_f(0,3.1416); a3 = vsip_cmplx_f(.3466,.7854); a4 = vsip_cmplx_f(.3466,-.7854); a5 = vsip_cmplx_f(0.0,1.5708); vsip_cvput_f(ans,0,a0); vsip_cvput_f(ans,1,a1); vsip_cvput_f(ans,2,a2); vsip_cvput_f(ans,3,a3); vsip_cvput_f(ans,4,a4); vsip_cvput_f(ans,5,a5); printf("input vector ab\n"); printf("ab from \"a\" stride 2 offset 0\n");VU_cvprintm_f("8.6",ab); vsip_cvlog_f(ab,ac); printf("ac from \"a\" stride 2 offset 1\n"); printf("output of cvlog_f(ab,ac)\n"); VU_cvprintm_f("8.6",ac); printf("expected output to four decimal\n"); VU_cvprintm_f("8.4",ans); vsip_cvsub_f(ac,ans,chk); vsip_cvmag_f(chk,chk_r); vsip_vclip_f(chk_r,.0002,.0002,0,1,chk_r); if(vsip_vsumval_f(chk_r) > .5) printf(" cvlog_f in error\n"); else { printf("cvlog_f correct to 4 decimal digits for\n"); printf("input vsipl vector of stride 2, output vsipl vector of stride 2\n"); } printf("\ntest cvlog for \"user data case\"\n"); printf("with user interleaved data on input\n"); printf("and user split data on output\n"); vsip_cvcopy_f_f(ab,ua); vsip_cvlog_f(ua,ub); vsip_cvsub_f(ub,ans,chk); vsip_cvmag_f(chk,chk_r); vsip_vclip_f(chk_r,.0002,.0002,0,1,chk_r); if(vsip_vsumval_f(chk_r) > .5) printf("cvlog_f in error for user data case \n"); else { printf("cvlog_f correct to 4 decimal digits for "); printf("user data case\n"); vsip_cvdestroy_f(ab); vsip_cvdestroy_f(ac);vsip_cvalldestroy_f(a); vsip_cvalldestroy_f(ans); vsip_vdestroy_f(chk_r); vsip_cvalldestroy_f(chk); } } return; } <file_sep>/* Created RJudd November 22, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cvkron_f.c,v 2.0 2003/02/22 15:18:50 judd Exp $ */ #include"vsip.h" #include"vsip_cvviewattributes_f.h" #include"vsip_cmviewattributes_f.h" void vsip_cvkron_f( vsip_cscalar_f alpha, const vsip_cvview_f *x, const vsip_cvview_f *y, const vsip_cmview_f *C) { vsip_cscalar_f tmp; vsip_length n = x->length, m = y->length; vsip_scalar_f *x_p_r = x->block->R->array + x->offset * x->block->cstride; vsip_scalar_f *x_p_i = x->block->I->array + x->offset * x->block->cstride; vsip_scalar_f *y_p_r = y->block->R->array + y->offset * y->block->cstride; vsip_scalar_f *y_p_i = y->block->I->array + y->offset * y->block->cstride; vsip_scalar_f *yp0_r = y_p_r; vsip_scalar_f *yp0_i = y_p_i; vsip_scalar_f *Cp0_r = C->block->R->array + C->offset * C->block->cstride; vsip_scalar_f *Cp0_i = C->block->I->array + C->offset * C->block->cstride; vsip_scalar_f *C_p_r = Cp0_r; vsip_scalar_f *C_p_i = Cp0_i; vsip_stride Crst = C->row_stride * C->block->cstride, Ccst = C->col_stride * C->block->cstride, xst = x->stride * x->block->cstride, yst = y->stride * y->block->cstride; while(n-- > 0){ tmp.r = *x_p_r * alpha.r - *x_p_i * alpha.i; tmp.i = *x_p_i * alpha.r + *x_p_r * alpha.i; x_p_r += xst; x_p_i += xst; while(m-- > 0){ *C_p_r = tmp.r * *y_p_r - tmp.i * *y_p_i; *C_p_i = tmp.i * *y_p_r + tmp.r * *y_p_i; C_p_r += Ccst; y_p_r+= yst; C_p_i += Ccst; y_p_i+= yst; } Cp0_r += Crst; Cp0_i += Crst; C_p_r = Cp0_r; C_p_i = Cp0_i; y_p_r = yp0_r; y_p_i = yp0_i; m = y->length; } return; } <file_sep>#ifndef __VI_FFTTYPE_H_ #define __VI_FFTTYPE_H_ typedef enum { VSIP_CCFFTOP, VSIP_CCFFTIP, VSIP_RCFFTOP, VSIP_CRFFTOP } vsip_ffttype; #endif <file_sep>#include<vsip.h> #include"svd.h" static void mprint_f(vsip_mview_f *A){ vsip_length n=vsip_mgetrowlength_f(A); vsip_length m=vsip_mgetcollength_f(A); vsip_index i,j; printf("["); for(i=0; i<m; i++){ for(j=0; j<n; j++){ printf("%+.5f ",vsip_mget_f(A,i,j)); } printf(";\n") ; } printf("]\n"); } static void vprint_f(vsip_vview_f *v){ vsip_index i; printf("["); for(i=0; i<vsip_vgetlength_f(v); i++) printf("%+.5f ",vsip_vget_f(v,i)); printf("]\n"); } static vsip_scalar_f mnormFro_f(vsip_mview_f *A){ return vsip_sqrt_f(vsip_msumsqval_f(A)); } static vsip_scalar_f checkBack_f(vsip_mview_f* A,vsip_mview_f* L, vsip_vview_f* d, vsip_mview_f* R){ vsip_scalar_f c; vsip_mview_f *VH=vsip_mcreate_f(vsip_mgetcollength_f(R),vsip_mgetrowlength_f(R),VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *Ac=vsip_mcreate_f(vsip_mgetcollength_f(A),vsip_mgetrowlength_f(A),VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *L0=vsip_msubview_f(L,0,0,vsip_mgetcollength_f(L),vsip_vgetlength_f(d)); vsip_mcopy_f_f(R,VH); vsip_vmmul_f(d,VH,VSIP_COL,VH); vsip_mprod_f(L0,VH,Ac); vsip_msub_f(A,Ac,Ac); c = mnormFro_f(Ac); vsip_malldestroy_f(VH);vsip_malldestroy_f(Ac);vsip_mdestroy_f(L0); return c; } int main(int argc, char* argv[]){ int init=vsip_init((void*)0); if(init) exit(0); svdObj_f s; vsip_mview_f *A = vsip_mcreate_f(8,6,VSIP_ROW,VSIP_MEM_NONE); vsip_vview_f *a = vsip_vbind_f(vsip_mgetblock_f(A),0,1,48); vsip_randstate *rnd=vsip_randcreate(5,1,1,VSIP_PRNG); vsip_vrandn_f(rnd,a); mprint_f(A); printf("\n"); s=svd_f(A); mprint_f(s.L); printf("\n"); vprint_f(s.d); printf("\n"); mprint_f(s.R); printf("Check value %f\n",checkBack_f(A,s.L,s.d,s.R)); vsip_malldestroy_f(s.L); vsip_malldestroy_f(s.R); vsip_valldestroy_f(s.d); vsip_vdestroy_f(a); vsip_malldestroy_f(A); vsip_randdestroy(rnd); vsip_finalize((void*)0); return 1; } <file_sep>/* Created RJudd October 6, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_mtransview_f.h,v 2.1 2003/03/08 14:43:33 judd Exp $ */ #ifndef _VI_MTRANSVIEW_F_H #define _VI_MTRANSVIEW_F_H #include"vsip.h" #include"vsip_mviewattributes_f.h" static vsip_mview_f *VI_mtransview_f( const vsip_mview_f* v, vsip_mview_f * a) { *a = *v; a->row_stride = v->col_stride; a->col_stride = v->row_stride; a->row_length = v->col_length; a->col_length = v->row_length; return a; } #endif /* _VI_MTRANSVIEW_F_H */ <file_sep>/* Created RJudd September 16, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cblockrelease_d.c,v 2.1 2006/06/08 22:19:26 judd Exp $ */ #include"vsip.h" #include"vsip_cblockattributes_d.h" void (vsip_cblockrelease_d)( vsip_cblock_d* b, vsip_scalar_bl update, vsip_scalar_d* *Rp, vsip_scalar_d* *Ip) { if(b != (vsip_cblock_d*)NULL) b->update = update; #if defined(VSIP_DEFAULT_SPLIT) #include"VI_cblockrelease_d_ds.h" #elif defined(VSIP_ALWAYS_SPLIT) #include"VI_cblockrelease_d_as.h" #elif defined(VSIP_ALWAYS_INTERLEAVED) #include"VI_cblockrelease_d_ai.h" #else #include"VI_cblockrelease_d_di.h" #endif return; } <file_sep>// // elementary.h // // // Created by <NAME> on 1/28/15. // // #ifndef _elementary_h #define _elementary_h #include "support.h" namespace vsip{ //add vsip_vview_f * add(vsip_vview_f* a,vsip_vview_f* b,vsip_vview_f* c){ vsip_vadd_f(a,b,c); return c; } vsip_vview_f * add(vsip_vview_f* a,vsip_vview_f* b){ vsip_vview_f *c;create(&c,vlength(a)); vsip_vadd_f(a,b,c); return c; } vsip_cvview_f * add(vsip_cvview_f* a,vsip_cvview_f* b,vsip_cvview_f* c){ vsip_cvadd_f(a,b,c); return c; } vsip_cvview_f * add(vsip_cvview_f* a,vsip_cvview_f* b){ vsip_cvview_f *c;create(&c,vlength(a)); vsip_cvadd_f(a,b,c); return c; } vsip_vview_f * add(vsip_scalar_f alpha, vsip_vview_f* b, vsip_vview_f* c){ vsip_svadd_f(alpha,b,c); return c; } vsip_vview_f * add(vsip_scalar_f alpha, vsip_vview_f* b){ vsip_vview_f *c;create(&c,vlength(b)); vsip_svadd_f(alpha,b,c); return c; } vsip_vview_d * add(vsip_vview_d* a,vsip_vview_d* b,vsip_vview_d* c){ vsip_vadd_d(a,b,c); return c; } vsip_vview_d * add(vsip_vview_d* a,vsip_vview_d* b){ vsip_vview_d *c;create(&c,vlength(a)); vsip_vadd_d(a,b,c); return c; } vsip_cvview_d * add(vsip_cvview_d* a,vsip_cvview_d* b,vsip_cvview_d* c){ vsip_cvadd_d(a,b,c); return c; } vsip_cvview_d * add(vsip_cvview_d* a,vsip_cvview_d* b){ vsip_cvview_d *c;create(&c,vlength(a)); vsip_cvadd_d(a,b,c); return c; } vsip_vview_d * add(vsip_scalar_d alpha, vsip_vview_d* b, vsip_vview_d* c){ vsip_svadd_d(alpha,b,c); return c; } vsip_vview_d * add(vsip_scalar_d alpha, vsip_vview_d* b){ vsip_vview_d *c;create(&c,vlength(b)); vsip_svadd_d(alpha,b,c); return c; } //Mull vsip_vview_f * mull(vsip_vview_f* a,vsip_vview_f* b,vsip_vview_f* c){ vsip_vmul_f(a,b,c); return c; } vsip_vview_f * mul(vsip_vview_f* a,vsip_vview_f* b){ vsip_vview_f *c;create(&c,vlength(a)); vsip_vmul_f(a,b,c); return c; } vsip_cvview_f * mul(vsip_cvview_f* a,vsip_cvview_f* b,vsip_cvview_f* c){ vsip_cvmul_f(a,b,c); return c; } vsip_cvview_f * mul(vsip_cvview_f* a,vsip_cvview_f* b){ vsip_cvview_f *c;create(&c,vlength(a)); vsip_cvmul_f(a,b,c); return c; } vsip_vview_f * mul(vsip_scalar_f alpha, vsip_vview_f* b, vsip_vview_f* c){ vsip_svmul_f(alpha,b,c); return c; } vsip_vview_f * mul(vsip_scalar_f alpha, vsip_vview_f* b){ vsip_vview_f *c;create(&c,vlength(b)); vsip_svmul_f(alpha,b,c); return c; } vsip_vview_d * mul(vsip_vview_d* a,vsip_vview_d* b,vsip_vview_d* c){ vsip_vmul_d(a,b,c); return c; } vsip_vview_d * mul(vsip_vview_d* a,vsip_vview_d* b){ vsip_vview_d *c;create(&c,vlength(a)); vsip_vmul_d(a,b,c); return c; } vsip_cvview_d * mul(vsip_cvview_d* a,vsip_cvview_d* b,vsip_cvview_d* c){ vsip_cvmul_d(a,b,c); return c; } vsip_cvview_d * mul(vsip_cvview_d* a,vsip_cvview_d* b){ vsip_cvview_d *c;create(&c,vlength(a)); vsip_cvmul_d(a,b,c); return c; } vsip_vview_d * mul(vsip_scalar_d alpha, vsip_vview_d* b, vsip_vview_d* c){ vsip_svmul_d(alpha,b,c); return c; } vsip_vview_d * mul(vsip_scalar_d alpha, vsip_vview_d* b){ vsip_vview_d *c;create(&c,vlength(b)); vsip_svmul_d(alpha,b,c); return c; } //acos vsip_vview_f *acos(vsip_vview_f *a, vsip_vview_f *c) { vsip_vacos_f(a, c); return c; } vsip_mview_f *acos(vsip_mview_f *a, vsip_mview_f *c){ vsip_macos_f(a, c); return c; } vsip_vview_d *acos(vsip_vview_d *a, vsip_vview_d *c) { vsip_vacos_d(a, c); return c; } vsip_mview_d *acos(vsip_mview_d *a, vsip_mview_d *c){ vsip_macos_d(a,c); return c; } //asin vsip_vview_f *asin(vsip_vview_f *a, vsip_vview_f *c) { vsip_vacos_f(a, c); return c; } vsip_mview_f *asin(vsip_mview_f *a, vsip_mview_f *c){ vsip_masin_f(a, c); return c; } vsip_vview_d *asin(vsip_vview_d *a, vsip_vview_d *c) { vsip_vasin_d(a, c); return c; } vsip_mview_d *asin(vsip_mview_d *a, vsip_mview_d *c){ vsip_masin_d(a,c); return c; } //cos vsip_vview_f *cos(vsip_vview_f *a, vsip_vview_f *c) { vsip_vacos_f(a, c); return c; } vsip_mview_f *cos(vsip_mview_f *a, vsip_mview_f *c){ vsip_mcos_f(a, c); return c; } vsip_vview_d *cos(vsip_vview_d *a, vsip_vview_d *c) { vsip_vcos_d(a, c); return c; } vsip_mview_d *cos(vsip_mview_d *a, vsip_mview_d *c){ vsip_mcos_d(a,c); return c; } //sin vsip_vview_f *sin(vsip_vview_f *a, vsip_vview_f *c) { vsip_vacos_f(a, c); return c; } vsip_mview_f *sin(vsip_mview_f *a, vsip_mview_f *c){ vsip_msin_f(a, c); return c; } vsip_vview_d *sin(vsip_vview_d *a, vsip_vview_d *c) { vsip_vsin_d(a, c); return c; } vsip_mview_d *sin(vsip_mview_d *a, vsip_mview_d *c){ vsip_msin_d(a,c); return c; } //exp vsip_vview_f *exp(vsip_vview_f *a, vsip_vview_f *c) { vsip_vexp_f(a, c); return c; } vsip_mview_f *exp(vsip_mview_f *a, vsip_mview_f *c){ vsip_mexp_f(a, c); return c; } vsip_vview_d *exp(vsip_vview_d *a, vsip_vview_d *c) { vsip_vexp_d(a, c); return c; } vsip_mview_d *exp(vsip_mview_d *a, vsip_mview_d *c){ vsip_mexp_d(a,c); return c; } vsip_cvview_f *exp(vsip_cvview_f *a, vsip_cvview_f *c) { vsip_cvexp_f(a, c); return c; } vsip_cmview_f *exp(vsip_cmview_f *a, vsip_cmview_f *c){ vsip_cmexp_f(a, c); return c; } vsip_cvview_d *exp(vsip_cvview_d *a, vsip_cvview_d *c) { vsip_cvexp_d(a, c); return c; } vsip_cmview_d *exp(vsip_cmview_d *a, vsip_cmview_d *c){ vsip_cmexp_d(a,c); return c; } } #endif <file_sep>/* RJudd 22 February, 98 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vcreate_cheby_f.c,v 2.5 2007/04/21 19:39:33 judd Exp $ */ /* Converted matlab code to VSIP */ /* Modifed March 8, 98 */ /* DAVID'S Matlab Code for cheby */ /* // function window = chebyw(nf, ripple) // % nf - window length // % ripple - stopband attenuation in dB // dp = 10.^(-ripple/20); // odd = rem(nf,2); // n2 = fix(nf/2); // df = acos(1/cosh(acosh((1+dp)/dp)/(nf-1)))/pi; // x0 = (3-cos(2*pi*df))/(1.+cos(2*pi*df)); // alpha = (x0 + 1)/2; // beta = (x0 - 1)/2; // k = (0:nf-1); // f = k/nf; // x = alpha*cos(2*pi*f) + beta; // tmp = (abs(x) > 1); // j = sqrt(-1); // wf = dp*(tmp.*(cosh(((nf-1)/2).*acosh(x)))+(1-tmp).*cos(((nf-1)/2).*acos(x))); // if (~odd) // wf = real(wf).*exp(-j*pi*f); // wf(n2+1:nf) = -wf(n2+1:nf); // else // wf = wf +j*zeros(1,nf); // end // wt = fft(wf); // wt = wt(1:nf)/wt(1); // window = real([wt(n2+2:nf) wt(1:n2+1)]'); // %size(window) // %plot(window,1,4*nf) // %plot(window) */ #include<math.h> #include"vsip.h" #include"vsip_vviewattributes_f.h" #include"vsip_cvviewattributes_f.h" #include"vsip_scalars.h" #include"VI_vcreate_f.h" #include"VI_valldestroy_f.h" #include"VI_cvcreate_f.h" #include"VI_cvalldestroy_f.h" #include"VI_vcopy_f_f.h" #include"VI_cvfill_f.h" #include"VI_cvsqrt_f.h" #include"VI_rcvadd_f.h" #include"VI_cvadd_f.h" #include"VI_vramp_f.h" #include"VI_vrealview_f.h" #include"VI_svsub_f.h" #include"VI_vclip_f.h" #include"VI_vacos_f.h" #include"VI_vcos_f.h" #include"VI_svmul_f.h" #include"VI_csvmul_f.h" #include"VI_vmul_f.h" #include"VI_rcvmul_f.h" #include"VI_rscvmul_f.h" #include"VI_veuler_f.h" #include"VI_cvget_f.h" #define cheby_PI ((vsip_scalar_f)3.1415926535897932384626433832795) #define TWOPI ((vsip_scalar_f)6.283185307179586) /* VSIP internal functions below */ /*******************************************************************/ static vsip_scalar_f VI_acosh_f(vsip_scalar_f x){ /*scalar acosh*/ vsip_scalar_f a = x * x; vsip_scalar_f z; vsip_scalar_f C1 = .25; vsip_scalar_f C2 = 3.0/32.0; vsip_scalar_f C3 = 15.0/288.0; vsip_scalar_f C4 = 105.0/3072.0; if(x <= 1.0) return 0.0; if(x < 10) return (vsip_scalar_f) log(x + sqrt(a - 1.0)); z = 1.0/a; return (vsip_scalar_f)(log(2.0 * x) - z * (C1 + z * (C2 + z * (C3 + z * C4)))); } /*******************************************************************/ static void VI_cvlog_f(vsip_cvview_f *a,vsip_cvview_f *r) { /* register */ vsip_length n = r->length; vsip_stride cast = a->block->cstride; vsip_stride crst = r->block->cstride; vsip_scalar_f *apr = (vsip_scalar_f *)((a->block->R->array) + cast * a->offset), *rpr = (vsip_scalar_f *)((r->block->R->array) + crst * r->offset); vsip_scalar_f *api = (vsip_scalar_f *)((a->block->I->array) + cast * a->offset), *rpi = (vsip_scalar_f *)((r->block->I->array) + crst * r->offset); /* register */ vsip_stride ast = (cast * a->stride), rst = (crst * r->stride); vsip_scalar_f arg = 0; while(n-- > 0){ arg = (vsip_scalar_f)atan2(*api , *apr); *rpr = (vsip_scalar_f)log(sqrt(*apr * *apr + *api * *api)); *rpi = arg; apr += ast; api += ast; rpr += rst; rpi += rst; } } /*******************************************************************/ static void VI_rcvacosh_f(vsip_vview_f *x, vsip_cvview_f *r){ void VI_cvlog_f(vsip_cvview_f*,vsip_cvview_f*); { vsip_length n = r->length; vsip_stride r_str = r->stride * r->block->cstride; vsip_stride x_str = x->stride * x->block->rstride; vsip_stride r_off = r_str * r->offset; vsip_stride x_off = x_str * x->offset; vsip_scalar_f *x_p = x->block->array + x_off, *rp_r = (vsip_scalar_f*)(r->block->R->array + r_off), *rp_i = (vsip_scalar_f*)(r->block->I->array + r_off); while(n-- > 0){ *rp_r = *x_p * *x_p - (vsip_scalar_f)1.0; *rp_i = (vsip_scalar_f)0; rp_r += r_str; rp_i += r_str; x_p += x_str; } } VI_cvsqrt_f(r,r); VI_rcvadd_f(x,r,r); VI_cvlog_f(r,r); return; } /*******************************************************************/ static void VI_cvcosh_f(vsip_cvview_f *x, vsip_cvview_f *r){ vsip_length n = r->length; vsip_stride stx = x->block->cstride * x->stride, str = r->block->cstride * r->stride; vsip_scalar_f *x_pr = (vsip_scalar_f*)(x->block->R->array + stx * x->offset), *x_pi = (vsip_scalar_f*)(x->block->I->array + stx * x->offset), *r_pr = (vsip_scalar_f*)(r->block->R->array + str * r->offset), *r_pi = (vsip_scalar_f*)(r->block->I->array + str * r->offset), tmp, mag, maginv; while(n-- > 0){ mag = (vsip_scalar_f)0.50 * VSIP_EXP_F(*x_pr); maginv = (vsip_scalar_f)0.25 / mag; tmp = (mag + maginv) * VSIP_COS_F(*x_pi); *r_pi = (mag - maginv) * VSIP_SIN_F(*x_pi); *r_pr = tmp; x_pr += stx; r_pr += str; x_pi += stx; r_pi += str; } } /*******************************************************************/ static void VI_vfreqswap_f(vsip_vview_f *a) { vsip_length n; vsip_length n2 = (a->length / 2); vsip_scalar_f *a_p = a->block->array + a->offset * a->block->rstride, *t_p, tmp; vsip_stride ast = a->stride * a->block->rstride; if(a->length % 2){ t_p = a_p + n2 + 1; tmp = *(t_p - 1); *(t_p - 1) = *a_p; n = n2 - 1; while(n-- > 0){ *a_p = *t_p; a_p += a->stride; *t_p = *a_p; t_p += a->stride; } *a_p = *t_p; *t_p = tmp; } else { n = n2; t_p = a_p + n2 ; while(n-- > 0){ tmp = *t_p; *t_p = *a_p; *a_p = tmp; a_p += ast; t_p += ast; } } } vsip_vview_f* (vsip_vcreate_cheby_f)( vsip_length nf, vsip_scalar_f ripple, vsip_memory_hint hint) { vsip_vview_f *window = VI_vcreate_f(nf,hint); int odd = 0; vsip_length n2 = 0; vsip_scalar_f dp = 0.0, df = 0.0, x0 = 0.0, alpha = 0.0, beta = 0.0; vsip_cvview_f *wf = VI_cvcreate_f(nf,hint), *Cfoo = VI_cvcreate_f(nf,hint); vsip_vview_f *f = VI_vcreate_f(nf,hint), *x = VI_vcreate_f(nf,hint), *tmp = VI_vcreate_f(nf,hint), *nottmp = VI_vcreate_f(nf,hint); vsip_vview_f wwfR; vsip_vview_f *wfR = VI_vrealview_f(wf,&wwfR); vsip_vview_f RRefoo; vsip_vview_f *Refoo = VI_vrealview_f(Cfoo,&RRefoo); /* check for malloc errors, destroy everything and return null on failure */ if((wf == NULL) | (Cfoo == NULL) | (f == NULL) | (x == NULL) | (tmp == NULL) | (wfR == NULL) | (Refoo == NULL) | (window == NULL) | (nottmp == NULL)){ VI_valldestroy_f(x); VI_valldestroy_f(f); VI_valldestroy_f(tmp); VI_cvalldestroy_f(wf); VI_cvalldestroy_f(Cfoo); VI_valldestroy_f(nottmp); VI_valldestroy_f(window); return (vsip_vview_f*)NULL; } VI_cvfill_f(wf->block->a_zero,wf); /* zero fill */ dp = VSIP_EXP10_F(-ripple/20.0); /*dp = 10.^(-ripple/20);*/ odd = ((int)nf) % 2; /*odd = rem(nf,2);*/ n2 = VSIP_FLOOR_F((vsip_scalar_f)nf/2.0); /*n2 = fix(nf/2);*/ /*df = acos(1/cosh(acosh((1+dp)/dp)/(nf-1)))/pi;*/ df = (vsip_scalar_f)VSIP_ACOS_F(1.0/VSIP_COSH_F(VI_acosh_f(((vsip_scalar_f)1.0 + dp)/dp) / ((vsip_scalar_f)nf - 1.0)))/cheby_PI; /*x0 = (3-cos(2*pi*df))/(1.+cos(2*pi*df));*/ x0 = (vsip_scalar_f)((3. - VSIP_COS_F(TWOPI * df))/(1. + VSIP_COS_F(TWOPI * df))); alpha = (x0 + (vsip_scalar_f)1.0) / (vsip_scalar_f)2.; /*alpha = (x0 + 1)/2;*/ beta = (x0 - (vsip_scalar_f)1.0) / (vsip_scalar_f)2.; /*beta = (x0 - 1)/2;*/ VI_vramp_f(((vsip_scalar_f)0.0),((vsip_scalar_f)1.0/((vsip_scalar_f)nf)),f); /*k = (0:nf-1);f = k/nf;*/ /* x = alpha*cos(2*pi*f) + beta; */ { vsip_length n = nf; vsip_scalar_f *f_p = f->block->array + f->offset, *x_p = x->block->array + x->offset; while(n-- > 0){ *x_p = alpha * (vsip_scalar_f)VSIP_COS_F(TWOPI * *f_p) + beta; x_p += x->stride; f_p += f->stride; } } /* END x = alpha*cos(2*pi*f) + beta; */ /*tmp = (mag(x) > 1); */ { vsip_length n = nf; vsip_scalar_f *x_p = x->block->array + x->offset, *tmp_p = tmp->block->array + tmp->offset; while(n-- > 0){ *tmp_p = (vsip_scalar_f)((((*x_p >= 0) ? *x_p : - *x_p) > 1) ? 1.0 : 0.0); x_p += x->stride; tmp_p += tmp->stride; } } /* END tmp = (mag(x) > 1); */ /* wf = dp*(tmp.*(cosh((((vsip_scalar_f)nf-1.0)/2).*acosh(x)))+ (1-tmp).*cos((((vsip_scalar_f)nf-1.0)/2).*acos(x)));*/ { VI_svsub_f(1.0,tmp,nottmp); VI_vclip_f(x,-1.0,1.0,-1.0,1.0,wfR); /* modified to handle x out side of range of acos*/ /* ensures that for x > 1 default return value of acos is zero */ VI_vacos_f(wfR,Refoo); VI_svmul_f(((vsip_scalar_f)nf-(vsip_scalar_f)1.0)/(vsip_scalar_f)2.0,Refoo,Refoo); VI_vcos_f(Refoo,Refoo); VI_vmul_f(nottmp,Refoo,wfR); VI_rcvacosh_f(x,Cfoo); VI_rscvmul_f(((vsip_scalar_f)nf - (vsip_scalar_f)1.0)/(vsip_scalar_f)2.0,Cfoo,Cfoo); VI_cvcosh_f(Cfoo,Cfoo); VI_rcvmul_f(tmp,Cfoo,Cfoo); VI_cvadd_f(Cfoo,wf,wf); VI_rscvmul_f(dp,wf,wf); } /* END wf = dp*(tmp.*(cosh(((nf-1)/2).*acosh(x)))+ (1-tmp).*cos(((nf-1)/2).*acos(x)));*/ if(!odd ){ /* if (~odd) */ /*wf = real(wf).*exp(-j*pi*f);*/ { VI_svmul_f((vsip_scalar_f)(-cheby_PI),f,f); VI_veuler_f(f,Cfoo); VI_rcvmul_f(wfR,Cfoo,wf); } /*END wf = real(wf).*exp(-j*pi*f);*/ /* wf(n2+1:nf) = -wf(n2+1:nf); */ { vsip_stride str = wf->block->cstride; vsip_length n = n2; vsip_scalar_f *wf_rp = (vsip_scalar_f*)(wf->block->R->array + str * n); vsip_scalar_f *wf_ip = (vsip_scalar_f*)(wf->block->I->array + str * n); while(n-- > 0){ *wf_rp = - *wf_rp; wf_rp += str; *wf_ip = - *wf_ip; wf_ip += str;} } /*END wf(n2+1:nf) = -wf(n2+1:nf);*/ }/* END if (~odd) */ {/* wt = fft(wf); */ vsip_fft_f* fftplan = vsip_ccfftip_create_f(nf,(vsip_scalar_f)(1.0/(vsip_scalar_f)nf),VSIP_FFT_FWD,0,VSIP_ALG_NOISE); vsip_ccfftip_f(fftplan,wf); {/* wt = wt(1:nf)/wt(1) */ vsip_cscalar_f scale; vsip_scalar_f magsq; VI_CVGETP_F(wf,0); scale = VI_CVGET_F(wf); scale.i = -scale.i; magsq = scale.i * scale.i + scale.r * scale.r; scale.i /= magsq; scale.r /= magsq; VI_csvmul_f(scale,wf,wf); } vsip_fft_destroy_f(fftplan); }/*END wt = fft(wf); */ VI_vcopy_f_f(wfR, window); VI_vfreqswap_f(window); VI_valldestroy_f(x); VI_valldestroy_f(f); VI_valldestroy_f(tmp); VI_valldestroy_f(nottmp); VI_cvalldestroy_f(wf); VI_cvalldestroy_f(Cfoo); return window; } <file_sep>/* Standard Disclaimer & Copyright Status */ /* Author: judd */ #ifndef _PARAM_H #define _PARAM_H 1 #include<strings.h> #include<stdlib.h> #include<stdio.h> typedef struct{ double c; /* propagation speed */ double Fs; /* Sample Rate */ int Nts; /* length of time series */ double Dsens; /* distance between sensors */ int Nsens; /* number of sensors */ int Navg; /* number of instances to average in beamformer*/ int Nsim_freqs; /* number of tones to simulate */ double *sim_freqs; /* (array) frequencies to simulate */ double *sim_bearings; /* (array) bearing of each frequencys */ int Nsim_noise; /* number of noise directions to simualte */ } param_obj; int param_read(char *, param_obj*); /* returns 1 on succsess, 0 on failure */ void param_free(param_obj*); /* free memory associated with sim_freqs and sim_bearings */ void param_log(param_obj*); /* print out parameter list */ #endif /* _PARAM_H */ <file_sep># Created RJudd # Converted from lud tests in c_VSIP_testing Directory # Note that blockbinds are not functional at this time in python so they have been removed # This code includes # no warranty, express or implied, including the warranties # of merchantability and fitness for a particular purpose. # No person or entity # assumes any legal liability or responsibility for the accuracy, # completeness, or usefulness of any information, apparatus, # product, or process disclosed, or represents that its use would # not infringe privately owned rights import vsiputils as vsip import vsipUser as VU from vsip import vsip_init,vsip_finalize from vsip import vsip_cmplx_d, vsip_cmplx_f,vsip_csub_f,vsip_csub_d,vsip_cmag_d,vsip_cmag_f def lud(p): """ Usage is lud(p) where p is a string of either '_d' or '_f' to denote precision. only works for real data. """ print('********\nTEST lud'+p+'\n') block = vsip.create('block'+p,(500,vsip.VSIP_MEM_NONE)) AC = vsip.bind(block,(0,6,6,1,6)) AG = vsip.bind(block,(36,2,6,18,6)) IC = vsip.bind(block,(150,1,6,6,6)) IG = vsip.bind(block,(200,2,6,14,6)) B = vsip.bind(block,(300,6,6,1,6)) A = vsip.bind(block,(350,6,6,1,6)) X = vsip.bind(block,(400,5,6,1,3)) Y = vsip.bind(block,(450,3,6,1,3)) ludC = vsip.create('lu'+p,6) ludG = vsip.create('lu'+p,6) AT = vsip.transview(A) data= [ [0.50, 7.00, 10.00, 12.00, -3.00, 0.00], [2.00, 13.00, 18.00, 6.00, 0.00, 130.00], [3.00, -9.00, 2.00, 3.00, 2.00, -9.00], [4.00, 2.00, 2.00, 4.00, 1.00, 2.00], [0.20, 2.00, 9.00, 4.00, 1.00, 2.00], [0.10, 2.00, 0.30, 4.00, 1.00, 2.00]] ydata= [[ 77.85, 155.70, 311.40], [ 942.00, 1884.00, 3768.00], [ 1.00, 2.00, 4.00], [ 68.00, 136.00, 272.00], [ 85.20, 170.40, 340.80], [ 59.00, 118.00, 236.00]] Ident = [[1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1]] for i in range(6): for j in range(6): vsip.put(A, (i,j),data[i][j]) vsip.put(AC,(i,j),data[i][j]) vsip.put(AG,(i,j),data[i][j]) vsip.put(IC,(i,j),Ident[i][j]) vsip.put(IG,(i,j),Ident[i][j]) for i in range(6): for j in range(3): vsip.put(X,(i,j),ydata[i][j]) print("Matrix A = \n");VU.mprint(A,'%7.2f') vsip.lud(ludC,AC); vsip.lud(ludG,AG) print("vsip_lusol(lud,vsip.VSIP_MAT_NTRANS,X)\n") print("Solve A X = I \n") vsip.lusol(ludC,vsip.VSIP_MAT_NTRANS,IC) vsip.lusol(ludG,vsip.VSIP_MAT_NTRANS,IG) print("for compact case X = \n");VU.mprint(IC,'%8.4f') print("for general case X = \n");VU.mprint(IG,'%8.4f') chk = 0 for i in range(6): for j in range(6): chk += abs(vsip.get(IC,(i,j)) - vsip.get(IG,(i,j))) if chk > .01: print("error\n") else: print("agree\n") vsip.prod(A,IC,B) chk = 0 for i in range(6): for j in range(6): chk += abs(vsip.get(B,(i,j)) - Ident[i][j]) vsip.prod(A,IG,B) for i in range(6): for j in range(6): chk += abs(vsip.get(B,(i,j)) - Ident[i][j]) print("mprod(A,X) = \n"); VU.mprint(B,'%8.3f') if chk > .01: print("error\n") else: print("correct\n") print("Matrix Transpose A = \n");VU.mprint(AT,'%7.2f') for i in range(6): for j in range(6): vsip.put(IC,(i,j),Ident[i][j]) vsip.put(IG,(i,j),Ident[i][j]) print("vsip_lusol(lud,vsip.VSIP_MAT_TRANS,X)\n") print("Solve trans(A) X = I \n") vsip.lusol(ludC,vsip.VSIP_MAT_TRANS,IC) vsip.lusol(ludG,vsip.VSIP_MAT_TRANS,IG) print("for compact case X = \n");VU.mprint(IC,'%8.4f') print("for general case X = \n");VU.mprint(IG,'%8.4f') chk = 0 for i in range(6): for j in range(6): chk += abs(vsip.get(IC,(i,j)) - vsip.get(IG,(i,j))) if chk > .01: print("error\n") else: print("agree\n") vsip.prod(AT,IC,B) chk = 0 for i in range(6): for j in range(6): chk += abs(vsip.get(B,(i,j)) - Ident[i][j]) vsip.prod(AT,IG,B) for i in range(6): for j in range(6): chk += abs(vsip.get(B,(i,j)) - Ident[i][j]) print("mprod(trans(A),X) = \n"); VU.mprint(B,'%8.3f') if chk > .01: print("error\n") else: print("correct\n") print("check A X = Y; vsip.VSIP_MAT_NTRANS\n") print("Y = \n");VU.mprint(X,'%8.4f') vsip.lusol(ludC,vsip.VSIP_MAT_NTRANS,X) print("X = \n"); VU.mprint(X,'%8.4f') vsip.prod(A,X,Y) print(" Y = A X\n");VU.mprint(Y,'%8.4f') chk = 0 for i in range(6): for j in range(3): chk += abs(vsip.get(Y,(i,j)) - ydata[i][j]) if chk > .01: print("error\n") else : print("agree\n") for i in range(6): for j in range(3): vsip.put(X,(i,j),ydata[i][j]) print("Y = \n");VU.mprint(X,'%8.4f') vsip.lusol(ludG,vsip.VSIP_MAT_TRANS,X) vsip.prod(AT,X,Y) print("X = \n");VU.mprint(X,'%8.4f') print("Y = trans(A) X\n");VU.mprint(Y,'%8.4f') chk = 0 for i in range(6): for j in range(3): chk += abs(vsip.get(Y,(i,j)) - ydata[i][j]) if (chk > .01): print("error\n") else: print("agree\n") vsip.destroy(AC) vsip.destroy(AG) vsip.destroy(IC) vsip.destroy(IG) vsip.destroy(B) vsip.destroy(A) vsip.destroy(X) vsip.destroy(Y) vsip.allDestroy(AT) vsip.destroy(ludC) vsip.destroy(ludG) def clud(p): def cmplx(p,re,im): return eval('vsip_cmplx'+p+'(re,im)') def csub(p,a,b): return eval('vsip_csub'+p+'(a,b)') def cmag(p,a): return eval('vsip_cmag'+p+'(a)') """ Usage is clud(p) where p is a string of either '_d' or '_f' to denote precision. only works for complex data. """ print('********\nTEST clud'+p+'\n') block = vsip.create('cblock'+p,(600,vsip.VSIP_MEM_NONE)) AC = vsip.bind(block,(0,7,7,1,7)) AG = vsip.bind(block,(175,-2,7,-18,7)) IC = vsip.bind(block,(176,1,7,7,7)) IG = vsip.bind(block,(226,2,7,15,7)) B = vsip.bind(block,(335,7,7,1,7)) A = vsip.bind(block,(385,7,7,1,7)) X = vsip.bind(block,(434,5,7,1,3)) Y = vsip.bind(block,(475,3,7,1,3)) ludC = vsip.create('clu'+p,7) ludG = vsip.create('clu'+p,7) data_r = [ \ [0.5, 7.0, 10.0, 12.0, -3.0, 0.0, 0.05], \ [2.0, 13.0, 18.0, 6.0, 0.0, 130.0, 8.0], \ [3.0, -9.0, 2.0, 3.0, 2.0, -9.0, 6.0], \ [4.0, 2.0, 2.0, 4.0, 1.0, 2.0, 3.0], \ [0.2, 2.0, 9.0, 4.0, 1.0, 2.0, 3.0], \ [0.1, 2.0, 0.3, 4.0, 1.0, 2.0, 3.0], \ [0.0, 0.2, 3.0, 4.0, 1.0, 2.0, 3.0]]; data_i = [ [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1], \ [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1], \ [0.1, 0.1, 0.1, 0.2, 0.2,-0.2, 0.2], \ [0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2], \ [0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3], \ [0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4], \ [0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4]]; ydata_r = [ \ [77.85, 155.70, 311.40], \ [942.00, 1884.00, 3768.00], \ [1.00, 2.00, 4.00], \ [68.00, 136.00, 272.00], \ [85.20, 170.40, 340.80], \ [59.00, 118.00, 236.00], \ [5.00, 18.00, 6.00]]; ydata_i = [ \ [4.5, 1.70, -3.40], \ [3.7, 184.00, -2.00], \ [1.00, 3.00, 2.00], \ [68.00, 16.00, 272.00], \ [85.20, 1170.40, 340.80], \ [59.00, 18.50, 62.00], \ [59.00, 11.60, 26.00]]; Ident = [ \ [1, 0, 0, 0, 0, 0, 0], \ [0, 1, 0, 0, 0, 0, 0], \ [0, 0, 1, 0, 0, 0, 0], \ [0, 0, 0, 1, 0, 0, 0], \ [0, 0, 0, 0, 1, 0, 0], \ [0, 0, 0, 0, 0, 1, 0], \ [0, 0, 0, 0, 0, 0, 1]]; AH = vsip.create('cmview'+p,(7,7,vsip.VSIP_ROW,vsip.VSIP_MEM_NONE)); for i in range(7): for j in range(7): a=cmplx(p,data_r[i][j],data_i[i][j]) e=cmplx(p,Ident[i][j],0.0) vsip.put(A, (i,j),a) vsip.put(AC,(i,j),a) vsip.put(AG,(i,j),a) vsip.put(IC,(i,j),e) vsip.put(IG,(i,j),e) for i in range(7): for j in range(3): a=cmplx(p,ydata_r[i][j],ydata_i[i][j]) vsip.put(X,(i,j),a) vsip.herm(A,AH) print("Matrix A = \n");VU.mprint(A,'%7.2f') vsip.lud(ludC,AC); vsip.lud(ludG,AG) print("vsip_clusol(lud,vsip.VSIP_MAT_NTRANS,X)\n") print("Solve A X = I \n") vsip.lusol(ludC,vsip.VSIP_MAT_NTRANS,IC) vsip.lusol(ludG,vsip.VSIP_MAT_NTRANS,IG) print("for compact case X = \n");VU.mprint(IC,'%8.4f') print("for general case X = \n");VU.mprint(IG,'%8.4f') chk = 0 for i in range(7): for j in range(7): chk += cmag(p,csub(p,vsip.get(IC,(i,j)),vsip.get(IG,(i,j)))) if chk > .01: print("error\n") else: print("agree\n") vsip.prod(A,IC,B) chk = 0 for i in range(7): for j in range(7): chk += cmag(p,csub(p,vsip.get(B,(i,j)),cmplx(p,Ident[i][j],0.0))) vsip.prod(A,IG,B) for i in range(7): for j in range(7): chk += cmag(p,csub(p,vsip.get(B,(i,j)),cmplx(p,Ident[i][j],0.0))) print("mprod(A,X) = \n"); VU.mprint(B,'%8.3f') if chk > .01: print("error\n") else: print("correct\n") # check case VSIP_MAT_HERM print("Matrix Hermitian A = \n");VU.mprint(AH,'%7.2f') for i in range(7): for j in range(7): vsip.put(IC,(i,j),cmplx(p,Ident[i][j],0.0)) vsip.put(IG,(i,j),cmplx(p,Ident[i][j],0.0)) print("vsip_clusol(lud,vsip.VSIP_MAT_HERM,X)\n") print("Solve herm(A) X = I \n") vsip.lusol(ludC,vsip.VSIP_MAT_HERM,IC) vsip.lusol(ludG,vsip.VSIP_MAT_HERM,IG) print("for compact case X = \n");VU.mprint(IC,'%8.4f') print("for general case X = \n");VU.mprint(IG,'%8.4f') chk = 0 for i in range(7): for j in range(7): chk += cmag(p,csub(p,vsip.get(IC,(i,j)),vsip.get(IG,(i,j)))) chk += cmag(p,csub(p,vsip.get(IC,(i,j)),vsip.get(IG,(i,j)))) if chk > .01: print("error\n") else: print("agree\n") vsip.prod(AH,IC,B) chk = 0 for i in range(7): for j in range(7): chk += cmag(p,csub(p,vsip.get(B,(i,j)),cmplx(p,Ident[i][j],0.0))) vsip.prod(AH,IG,B) for i in range(7): for j in range(7): chk += cmag(p,csub(p,vsip.get(B,(i,j)),cmplx(p,Ident[i][j],0.0))) print("mprod(trans(A),X) = \n"); VU.mprint(B,'%8.3f') if chk > .01: print("error\n") else: print("correct\n") # check case A X = B for VSIP_MAT_NTRANS print("check A X = Y; VSIP_MAT_NTRANS\n") print("Y = \n");VU.mprint(X,"%8.4f") vsip.lusol(ludC,vsip.VSIP_MAT_NTRANS,X) print("X = \n"); VU.mprint(X,"%8.4f") vsip.prod(A,X,Y) print(" Y = A X\n");VU.mprint(Y,"%8.4f") chk = 0; for i in range(7): for j in range(3): chk += cmag(p,csub(p,vsip.get(Y,(i,j)),cmplx(p,ydata_r[i][j],ydata_i[i][j]))) if (chk > .01): print("error\n") else: print("agree\n") for i in range(7): for j in range(3): vsip.put(X,(i,j),cmplx(p,ydata_r[i][j],ydata_i[i][j])) print("Y = \n");VU.mprint(X,'%8.4f') vsip.lusol(ludG,vsip.VSIP_MAT_HERM,X) vsip.prod(AH,X,Y) print("X = \n");VU.mprint(X,'%8.4f') print("Y = trans(A) X\n");VU.mprint(Y,'%8.4f') chk = 0 for i in range(7): for j in range(3): chk += cmag(p,csub(p,vsip.get(Y,(i,j)),cmplx(p,ydata_r[i][j],ydata_i[i][j]))) if (chk > .02): print("error\n") else: print("agree\n") vsip.destroy(AC) vsip.destroy(AG) vsip.destroy(IC) vsip.destroy(IG) vsip.destroy(B) vsip.destroy(A) vsip.destroy(X) vsip.destroy(Y) vsip.allDestroy(AH) vsip.destroy(ludC) vsip.destroy(ludG) vsip_init(None) lud('_f') lud('_d') clud('_f') clud('_d') vsip_finalize(None) <file_sep>/* Created RJudd September 19, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_ctbind_d.c,v 2.0 2003/02/22 15:18:48 judd Exp $ */ #define VI_CTVIEW_D_ #include"VI_support_cpriv_d.h" vsip_ctview_d *vsip_ctbind_d( const vsip_cblock_d *block, vsip_offset offset, vsip_stride z_stride, vsip_length z_length, vsip_stride y_stride, vsip_length y_length, vsip_stride x_stride, vsip_length x_length) { vsip_ctview_d *ctview = VI_ctview_d(); if(ctview != NULL){ ctview->block = (vsip_cblock_d*) block; ctview->offset = offset; ctview->z_length = z_length; ctview->y_length = y_length; ctview->x_length = x_length; ctview->z_stride = z_stride; ctview->y_stride = y_stride; ctview->x_stride = x_stride; ctview->markings = VSIP_VALID_STRUCTURE_OBJECT; } return ctview; } <file_sep>/* Created RJudd March 17, 2012 */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"vsip.h" #include"vsip_cvviewattributes_d.h" #include"vsip_vviewattributes_d.h" #include"vsip_rcfirattributes_d.h" #include"VI_cvfill_d.h" void vsip_rcfir_reset_d( vsip_rcfir_d *fir) { fir->p = 0; fir->s->length = fir->M - 1; VI_cvfill_d(vsip_cmplx_d((vsip_scalar_d)0,(vsip_scalar_d)0),fir->s); return; } <file_sep>/* Created RJudd November 2, 2002 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_cblockrelease_f_as.h,v 2.0 2003/02/22 15:18:29 judd Exp $ */ /* VI_cblockrelease_f always split */ if (b == (vsip_cblock_f*) NULL ) { *Rp = (vsip_scalar_f*)NULL; /* if block null return null */ *Ip = (vsip_scalar_f*)NULL; } else { if (b->kind != VSIP_USER_BLOCK) { *Rp = (vsip_scalar_f*)NULL; /* null if not user block */ *Ip = (vsip_scalar_f*)NULL; } else { if((b->r_data == b->R->array) && (update)){ vsip_length n = b->size; vsip_scalar_f *ptr_R = b->R->array, *ptr_I = b->I->array, *ptr_Rp = b->Rp; while(n-- > 0){ *ptr_Rp = *ptr_R; ptr_Rp++; ptr_R++; *ptr_Rp = *ptr_I; ptr_Rp++; ptr_I++; } } b->admit = VSIP_RELEASED_BLOCK; b->R->admit = VSIP_RELEASED_BLOCK; b->I->admit = VSIP_RELEASED_BLOCK; *Rp = b->Rp; *Ip = b->Ip; } } <file_sep>/* Created RJudd August 28, 1999 */ /* SPAWARSYSCEN D881 */ /* private attributes for real qrd */ #ifndef _vsip_cqrddattributes_f_h #define _vsip_cqrdattributes_f_h 1 #include"vsip_cmviewattributes_f.h" #include"vsip_cvviewattributes_f.h" #include"vsip_mviewattributes_f.h" #include"vsip_vviewattributes_f.h" #include"VI.h" struct vsip_cqrdattributes_f{ vsip_qrd_qopt qopt; vsip_length M; vsip_length N; vsip_cmview_f *A; vsip_cmview_f AA; vsip_cvview_f *v; vsip_cvview_f *w; vsip_cvview_f *cI; vsip_scalar_f *beta; }; #endif /*_vsip_cqrdattributes_f_h */ <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cvcopyfrom_user_f.h,v 1.1 2007/04/18 03:59:06 judd Exp $ */ #include"VU_cvprintm_f.include" static void cvcopyfrom_user_f(void){ int i; printf("********\nTEST cvcopyfrom_user_f\n"); { /* test interleaved */ vsip_cblock_f *block = vsip_cblockcreate_f(200,VSIP_MEM_NONE); vsip_scalar_f input[10]={0,1,2,3,4,5,6,7,8,9}; vsip_cvview_f *view = vsip_cvbind_f(block,100,-2,5); vsip_cvview_f *all = vsip_cvbind_f(block,0,1,200); vsip_scalar_f check = 0; vsip_cvfill_f(vsip_cmplx_f(-1,-1),all); vsip_cvcopyfrom_user_f(input,(vsip_scalar_f*)NULL,view); VU_cvprintm_f("3.2",view); for(i=0; i<5; i++){ vsip_cscalar_f t = vsip_cvget_f(view,(vsip_index)i); check += fabs(input[2*i] - vsip_real_f(t)); check += fabs(input[2*i+1] - vsip_imag_f(t)); } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_cvdestroy_f(all); vsip_cvdestroy_f(view); vsip_cblockdestroy_f(block); } { /* test split */ vsip_cblock_f *block = vsip_cblockcreate_f(200,VSIP_MEM_NONE); vsip_scalar_f input_r[5]={0,2,4,6,8}; vsip_scalar_f input_i[5]={1,3,5,7,9}; vsip_scalar_f check = 0; vsip_cvview_f *view = vsip_cvbind_f(block,100,3,5); vsip_cvview_f *all = vsip_cvbind_f(block,0,1,200); vsip_cvfill_f(vsip_cmplx_f(-1,-1),all); vsip_cvcopyfrom_user_f(input_r,input_i,view); printf("split\n"); VU_cvprintm_f("3.2",view); for(i=0; i<5; i++){ vsip_cscalar_f t = vsip_cvget_f(view,(vsip_index)i); check += fabs(input_r[i] - vsip_real_f(t)); check += fabs(input_i[i] - vsip_imag_f(t)); } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_cvdestroy_f(all); vsip_cvdestroy_f(view); vsip_cblockdestroy_f(block); } return; } <file_sep>/* Created RJudd August 28, 1999 */ /* SPAWARSYSCEN D881 */ /* private attributes for real qrd */ #ifndef _vsip_qrddattributes_f_h #define _vsip_qrdattributes_f_h 1 #include"vsip_mviewattributes_f.h" #include"vsip_vviewattributes_f.h" struct vsip_qrdattributes_f{ vsip_qrd_qopt qopt; vsip_length M; vsip_length N; vsip_mview_f *A; vsip_mview_f AA; vsip_vview_f *v; vsip_vview_f *w; vsip_scalar_f *beta; }; #endif /*_vsip_qrdattributes_f_h */ <file_sep>/* Created RJudd March 14, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vmprod_d.c,v 2.1 2004/04/03 14:04:13 judd Exp $ */ /* April 21, 1998 1,2 to row,col */ /* Removed Tisdale error checking Sept 00 */ #include"vsip.h" #include"vsip_vviewattributes_d.h" #include"vsip_mviewattributes_d.h" void (vsip_vmprod_d)( const vsip_vview_d* a, const vsip_mview_d* B, const vsip_vview_d* r) { { vsip_length nx = 0, mx = 0; vsip_scalar_d *ap = a->block->array + a->offset * a->block->rstride, *ap0 = ap, *rp = r->block->array + r->offset * r->block->rstride, *Byp = B->block->array + B->offset * B->block->rstride, *Bxp = Byp; vsip_stride BCst = B->col_stride * B->block->rstride, BRst = B->row_stride * B->block->rstride, rst = r->stride * r->block->rstride; while(nx++ < B->row_length){ *rp = 0; mx = 0; while(mx++ < B->col_length){ *rp += *ap * *Byp; ap += a->stride; Byp += BCst; } ap = ap0; Byp = (Bxp += BRst); rp += rst; } } } <file_sep>/* Modified RJudd June 27, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_valldestroy_f.h,v 2.0 2003/02/22 15:18:34 judd Exp $ */ #include"vsip.h" #ifndef VI_VALLDESTROY_F_H #define VI_VALLDESTROY_F_H #include"VI_blockdestroy_f.h" #include"VI_vdestroy_f.h" static void VI_valldestroy_f( vsip_vview_f* v) { /* vector view destructor */ VI_blockdestroy_f(VI_vdestroy_f(v)); return; } #endif <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: rscvdiv_f.h,v 2.0 2003/02/22 15:23:27 judd Exp $ */ #include"VU_cvprintm_f.include" static void rscvdiv_f(void){ printf("\n********\nTEST rscvdiv_f\n"); { vsip_scalar_f alpha = 2.5; vsip_cvview_f *b = vsip_cvcreate_f(7,VSIP_MEM_NONE); vsip_cvview_f *c = vsip_cvcreate_f(7,VSIP_MEM_NONE); vsip_vview_f *c_i = vsip_vimagview_f(c); vsip_cvview_f *chk = vsip_cvcreate_f(7,VSIP_MEM_NONE); vsip_vview_f *chk_i = vsip_vimagview_f(chk); vsip_scalar_f data_r[] ={.1, .2, .3, .4, .5, .6, .7}; vsip_scalar_f data_i[] ={7,6,5,4,3,2,1}; vsip_scalar_f data_ans[] ={.0051,-.3571, .0139,-.4162, .0299,-.4982, .0619,-.6188, .1351,-.8108, .3440,-1.1468, 1.1745,-1.6779}; vsip_cblock_f *cblock = vsip_cblockbind_f(data_r,data_i,7,VSIP_MEM_NONE); vsip_cblock_f *cblock_ans = vsip_cblockbind_f(data_ans, (vsip_scalar_f*)NULL,7,VSIP_MEM_NONE); vsip_cvview_f *u_b = vsip_cvbind_f(cblock,0,1,7); vsip_cvview_f *u_ans = vsip_cvbind_f(cblock_ans,0,1,7); vsip_cblockadmit_f(cblock,VSIP_TRUE); vsip_cblockadmit_f(cblock_ans,VSIP_TRUE); vsip_cvcopy_f_f(u_b,b); printf("call vsip_rscvdiv_f(alpha,b,c)\n"); printf("alpha = %f\n",alpha); printf("b =\n");VU_cvprintm_f("8.6",b); printf("test normal out of place\n"); vsip_rscvdiv_f(alpha,b,c); printf("c =\n");VU_cvprintm_f("8.6",c); printf("right answer =\n");VU_cvprintm_f("8.4",u_ans); vsip_cvsub_f(u_ans,c,chk); vsip_cvmag_f(chk,chk_i); vsip_vclip_f(chk_i,.0002,.0002,0,1,chk_i); if(vsip_vsumval_f(chk_i) > .5) printf("error\n"); else printf("correct\n"); printf("test b,c inplace\n"); vsip_rscvdiv_f(alpha,b,b); vsip_cvsub_f(u_ans,b,chk); vsip_cvmag_f(chk,chk_i); vsip_vclip_f(chk_i,.0002,.0002,0,1,chk_i); if(vsip_vsumval_f(chk_i) > .5) printf("error\n"); else printf("correct\n"); vsip_cvalldestroy_f(b); vsip_vdestroy_f(c_i); vsip_cvalldestroy_f(c); vsip_vdestroy_f(chk_i); vsip_cvalldestroy_f(chk); vsip_cvalldestroy_f(u_b); vsip_cvalldestroy_f(u_ans); } return; } <file_sep>#!python # Motivation # Demonstrate submatrix by calculating a determinant. # Check against included det method import pyJvsip as pv import timeit # NOTE myDet is not efficient. Keep N below 7 or 8 N=6 # Function myDet uses definition of Determinant in most # Linear Algebra Texts by expansion of cofactors along a row def myDet(A): m = A.collength det = 0 if m == 1: return A[0,0] for i in range(m): det += A[0,i] * pow(-1,i) * myDet(A.submatrix(0,i)) return det # For example we need some data so we Create a non-singular matrix 'A' A=pv.create('mview_d',N,N).fill(-1.0) A.diagview(0).ramp(1,1.1) A.diagview(1).fill(2) A.diagview(-1).fill(2) # Find the determinant with pyJvsip det method d0=A.copy.det # Find the determinant using myDet funciton d1=myDet(A) #compare print('difference d0 - d1 = %f - %f = %f'%(d0,d1,d0-d1)) # Below we do some timing measureents to show inefficiency of myDet. sMyDet='def myDet(A):\n m = A.collength\n det = 0\n if m == 1:\n' sMyDet+=' return A[0,0]\n for i in range(m):\n' sMyDet+=' det += A[0,i] * pow(-1,i) * myDet(A.submatrix(0,i))\n' sMyDet+=' return det\n' Amake='A=pv.create(\'mview_d\',N,N).fill(-1.0)\n' Amake +='A.diagview(0).ramp(1,1.1);A.diagview(1).fill(2)\n' Amake +='A.diagview(-1).fill(2)\n' s='N=6\n'+sMyDet+Amake+'myDet(A)\n' t=timeit.timeit(s,'import pyJvsip as pv',number=5)/5.0 print('Time for calculating myDet using N=6 is %f seconds'%(t)) s='N=6\n'+Amake+'A.det\n' t=timeit.timeit(s,'import pyJvsip as pv',number=50)/50.0 print('Time for calculating A.det using N=6 is %f seconds'%(t)) <file_sep> # coding: utf-8 # ## SVD Bidiagonalization # In this section we prototype code to bidiagonalize an input matrix as the first part of a singular value decomposition. For this algorithm where $m$ is the column length and $n$ is the row length we assume $ m \ge n $. In the JVSIP C algorithm we remove that restriction with a little additional logic. The reason for calling this * SVD Bidiagonalization * instead of just bidiagonalization is we perform phase rotations on the central matrix to ensure the diagonals are real and positive. This means the * SVD iteration* step is the same for both real and complex except for the updating the left and right update matrices. # # The essential part of this algorithm is $ A_{\mathbb{C}}=L_{\mathbb{C}} B_{\mathbb{R}} R_{\mathbb{C}} $ # # Usage is # > ` L,d,f,R,eps0 = svdBidiag(A,eps) ` # # Where ` eps ` is a small number passed for a clue on what is considered zero, `eps0` is passed back as the number the algorithm is using, and `d` and `f` are vectors corresponding to the values in the the central and first diagonal entry of $B$. These objects are needed for the iteration phase. # In[1]: import pyJvsip as pv from math import sqrt # For the main bidiagonalization I use householder methods. See the Householder notebook for more information on Householder. # In[2]: # H A def houseProd(v,A): beta = 2.0/v.jdot(v) v.conj;w=v.prod(A).conj;v.conj A -= v.outer(beta,w) # In[3]: # A H def prodHouse(A,v): beta = 2.0/v.jdot(v) w=A.prod(v) A-=w.outer(beta,v) # In[4]: def VHmatExtract(B): #B bidiagonalized with householder vectors stored in rows and columns. n = B.rowlength V=pv.create(B.type,n,n).fill(0.0);V.diagview(0).fill(1.0) if(n < 3): return V; for i in range(n-3,0,-1): j=i+1; v=B.rowview(i)[j:] t=v[0] v[0]=1.0 prodHouse(V[j:,j:],v) v[0]=t v=B.rowview(0)[1:] t=v[0];v[0]=1.0 prodHouse(V[1:,1:],v) v[0]=t return V # In[5]: def UmatExtract(B): m = B.collength n = B.rowlength U=pv.create(B.type,m,m).fill(0.0);U.diagview(0).fill(1.0) if (m > n): i=n-1; v=B.colview(i)[i:] t=v[0] v[0]=1.0 houseProd(v,U[i:,i:]) v[0]=t for i in range(n-2,0,-1): v=B.colview(i)[i:] t=v[0];v[0]=1.0 houseProd(v,U[i:,i:]) v[0]=t v=B.colview(0) t=v[0];v[0]=1.0 houseProd(v,U) v[0]=t return U # In[6]: # See miscSVDroutineNB notebook for additional information on sign def sign(a): if a.imag == 0.0: if a.real < 0.0: return -1.0 else: return 1.0 else: re = abs(a.real) im = abs(a.imag) if re < im: t=re/im; t*=t; t +=1; t = im*sqrt(t) else: t=im/re; t*=t; t +=1; t = re*sqrt(t) return a/t # In[7]: def houseVector(x): nrm=x.norm2 t=x[0] x[0]=nrm * sign(t) + t nrm = x.norm2 if nrm == 0.0: x[0]=1.0 else: x /= nrm return x # In[8]: def bidiag(B): x=B.colview(0) m=B.collength;n=B.rowlength assert m >= n,'For bidiag the input matrix must have a collength >= rowlength' v=x.empty.fill(0.0) for i in range(n-1): x=B.colview(i)[i:] v=v.block.bind(0,1,x.length) pv.copy(x,v) houseVector(v) z = v[0]; re = z.real; im = z.imag; z = re*re + im*im if z > 0.0: re /= z; im = -im/z if im == 0.0: z=re else: z=complex(re,im) v *= z; houseProd(v,B[i:,i:]); pv.copy(v[1:],x[1:]) if(i < n-2): j = i+1; v.putlength(n-j) x=B.rowview(i)[j:] pv.copy(x,v) houseVector(v); v.conj z = v[0]; re = z.real; im = z.imag; z = re*re + im*im if z > 0.0: re /= z; im = -im/z if im == 0.0: z=re else: z=complex(re,im) v[:] *= z; prodHouse(B[i:,j:],v); pv.copy(v[1:],x[1:]) if(m > n): i=n-1 x=B.colview(i)[i:] v=v.block.bind(0,1,x.length) pv.copy(x,v) houseVector(v) z = v[0]; re = z.real; im = z.imag; z = re*re + im*im if z > 0.0: re /= z; im = -im/z if im == 0.0: z=re else: z=complex(re,im) v[:] *= z; houseProd(v,B[i:,i:]); pv.copy(v[1:],x[1:]) return B # For additonal information on the phase rotations to make d and f real see the notebook biDiagPhaseToZeroNB. # In[9]: def biDiagPhaseToZero(B,L, d, f, R, eps0): # here d and f may be complex nd=d.length nf=f.length assert nd == nf+1, 'For biDiagPhaseToZero the length of d should be nf+1' lc=L.colview rr=R.rowview for i in range(nd): ps = d[i] if ps == 0.0: ps = 1.0 m = 0.0 else: m=abs(ps) # hypot(ps.real,ps.imag) might have better numerical properties than abs ps /= m if(m < eps0): d[i]=0.0 else: d[i]=m if i < f.length: f[i] *= ps.conjugate() lc(i)[:] *= ps for i in range(nf-1): j=i+1 ps=f[i] if ps == 0.0: ps = 1.0 m=0.0 else: m=abs(ps) # hypot(ps.real,ps.imag) might have better numerical properties than abs ps /= m lc(j)[:] *= ps.conjugate() rr(j)[:] *= ps f[i] = m f[j] *= ps j=nf i=j-1 ps=f[i] if ps == 0.0: ps = 1.0 m = 0.0 else: m=abs(ps) ps /= m f[i]=m lc(j)[:] *= ps.conjugate() rr(j)[:] *= ps if 'cvview' in d.type: #From here d and f are real since imaginary is all zero return (d.realview.copy,f.realview.copy) else: return (d.copy,f.copy) # In[10]: def svdBidiag(A,eps): eps0 = A.normFro/float(A.rowlength) * eps B=A.copy bidiag(B) L=UmatExtract(B) R=VHmatExtract(B) b=B.diagview d,f=biDiagPhaseToZero(B,L, b(0), b(1), R, eps0) return(L,d,f,R,eps0) # #### Example # In[11]: A=pv.create('mview_f',6,5).fill(0.0) A[2,2]=3.0; A[3,4]=5.0 L,d,f,R,eps0=svdBidiag(A,1E-10) # In[12]: #make up some data A=pv.create('cmview_f',6,5).randn(5) A.mprint('%.3f') # In[13]: # bidiagonlize and then check to see if we can get back the origional matrix L,d,f,R,eps0=svdBidiag(A,1E-10) B0=A.empty.fill(0.0) if 'cmview' in B0.type: B0.realview.diagview(0)[:]=d B0.realview.diagview(1)[:]=f else: B0.diagview(0)[:]=d B0.diagview(1)[:]=f L.prod(B0).prod(R).mprint('%.3f') print('check %e.4',(A-L.prod(B0).prod(R)).normFro) # In[14]: d.mprint('%.3f') f.mprint('%.3f') # In[14]: <file_sep>#include<stdio.h> #include<vsip.h> #define N 8 /* the length of the vector */ void VU_vprint_d(vsip_vview_d* a){ vsip_length i; for(i=0; i<vsip_vgetlength_d(a); i++) printf("%4.0f",vsip_vget_d(a,i)); printf("\n"); } int main(){ vsip_init((void*)0); vsip_vview_d *A = vsip_vcreate_d(N,0), *B = vsip_vcreate_d(N,0), *C = vsip_vcreate_d(N,0); vsip_vramp_d(0,1,A); printf("A = \n");VU_vprint_d(A); vsip_vfill_d(5,B); printf("B = \n");VU_vprint_d(B); vsip_vadd_d(A,B,C); printf("C = \n");VU_vprint_d(C); vsip_valldestroy_d(A); vsip_valldestroy_d(B); vsip_valldestroy_d(C); vsip_finalize((void*)0); return 1; } <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vcopyfrom_user_d.h,v 1.1 2007/04/18 03:59:06 judd Exp $ */ #include"VU_vprintm_d.include" static void vcopyfrom_user_d(void){ printf("********\nTEST vcopyfrom_user_d\n"); { int i; vsip_block_d *block = vsip_blockcreate_d(200,VSIP_MEM_NONE); vsip_scalar_d input[5]={0,1,2,3,4}; vsip_vview_d *view = vsip_vbind_d(block,100,3,5); vsip_vview_d *all = vsip_vbind_d(block,0,1,200); vsip_scalar_d check = 0; vsip_vfill_d(-1,all); vsip_vcopyfrom_user_d(input,view); VU_vprintm_d("3.2",view); for(i=0; i<5; i++){ check += fabs(input[i] - vsip_vget_d(view,(vsip_index)i)); } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_vdestroy_d(all); vsip_vdestroy_d(view); vsip_blockdestroy_d(block); } return; } <file_sep>/* Created RJudd */ /* VSIPL Consultant */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mvprod4_d.c,v 2.1 2006/04/27 01:58:00 judd Exp $ */ #include"vsip.h" #include"vsip_vviewattributes_d.h" #include"vsip_mviewattributes_d.h" void (vsip_mvprod4_d)( const vsip_mview_d* A, const vsip_vview_d* b, const vsip_vview_d* r) { vsip_scalar_d *bp0 = b->block->array + b->offset * b->block->rstride, *rp0 = r->block->array + r->offset * r->block->rstride, *Ap00 = A->block->array + A->offset * A->block->rstride; vsip_stride rst = r->stride * r->block->rstride, ARst = A->row_stride * A->block->rstride, ACst = A->col_stride * A->block->rstride, bst = b->stride * b->block->rstride; vsip_scalar_d b0,b1,b2,b3; vsip_scalar_d a00, a01, a02, a03; vsip_scalar_d a10, a11, a12, a13; vsip_scalar_d a20, a21, a22, a23; vsip_scalar_d a30, a31, a32, a33; vsip_scalar_d *Ap10 = Ap00 + ACst, *bp1 = bp0 + bst, *rp1 = rp0 + rst; vsip_scalar_d *Ap20 = Ap10 + ACst, *bp2 = bp1 + bst, *rp2 = rp1 + rst; vsip_scalar_d *Ap30 = Ap20 + ACst, *bp3 = bp2 + bst, *rp3 = rp2 + rst; b0 = *bp0; b1 = *bp1; b2 = *bp2; b3 = *bp3; a00 = *Ap00; a01 = *(Ap00+ARst); a02 = *(Ap00 + 2 * ARst); a03 = *(Ap00 + 3 * ARst); a10 = *Ap10; a11 = *(Ap10+ARst); a12 = *(Ap10 + 2 * ARst); a13 = *(Ap10 + 3 * ARst); a20 = *Ap20; a21 = *(Ap20+ARst); a22 = *(Ap20 + 2 * ARst); a23 = *(Ap20 + 3 * ARst); a30 = *Ap30; a31 = *(Ap30+ARst); a32 = *(Ap30 + 2 * ARst); a33 = *(Ap30 + 3 * ARst); *rp0 = b0 * a00 + b1 * a01 + b2 * a02 + b3 * a03; *rp1 = b0 * a10 + b1 * a11 + b2 * a12 + b3 * a13; *rp2 = b0 * a20 + b1 * a21 + b2 * a22 + b3 * a23; *rp3 = b0 * a30 + b1 * a31 + b2 * a32 + b3 * a33; return; } <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: svd1_d.h,v 1.6 2009/08/09 21:04:55 judd Exp $ */ #include"VU_mprintm_d.include" #include"VU_vprintm_d.include" static void svd1_d(void){ printf("********\nTEST svd1 for double\n"); { vsip_index i; vsip_length M=5, N=6; vsip_scalar_d data[30] = { -1, 2, 0,-3, 6, \ 8, 5, 4,-2, 1, \ 2, 3, 4, 5, 6, \ 7, 8, 9,10,11, \ -1,-2,-3,-4,-5, \ -0,-4,-5,-3,-2}; vsip_vview_d *s = vsip_vcreate_d(((M > N) ? N : M),VSIP_MEM_NONE); vsip_sv_d *svd = vsip_svd_create_d(M,N,VSIP_SVD_UVFULL,VSIP_SVD_UVFULL); vsip_block_d *block = vsip_blockbind_d(data,(M * N),VSIP_MEM_NONE); vsip_mview_d *A0 = vsip_mbind_d(block,0,N,M,1,N); vsip_block_d *vblk = vsip_blockcreate_d(300,VSIP_MEM_NONE); vsip_mview_d *A = vsip_mbind_d(vblk,3,3 * N, M,2 , N); vsip_mview_d *U = vsip_mcreate_d(M,M,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *V = vsip_mcreate_d(N,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *B = vsip_mcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_d(block,VSIP_TRUE); vsip_mcopy_d_d(A0,A); printf("in = ");VU_mprintm_d("6.3",A); /* do the svd calculation; check for error */ /* singular values go into vector s */ if(vsip_svd_d(svd,A,s)){ printf("svd error\n"); return; } /* singular values are in vector s. We want these in a diagonal matrix B */ vsip_mfill_d(0.0,B); for(i=0; i<vsip_vgetlength_d(s); i++) vsip_mput_d(B,i,i,vsip_vget_d(s,i)); /* copy the U and V matrix out of the SVD object */ vsip_svdmatu_d(svd, 0, M-1, U); vsip_svdmatv_d(svd, 0, N-1, V); /* output the three matrices (B is the singular value matrix ) */ /* IF U, B and V are correct then we know "A0 = U B V^t" */ printf("U = ");VU_mprintm_d("12.10",U); printf("B = ");VU_mprintm_d("12.10",B); printf("V = ");VU_mprintm_d("12.10",V); VU_vprintm_d("12.10",s); { /* check that A0 = U * B * V' */ vsip_scalar_d chk = 1.0; vsip_scalar_d lim = 5 * DBL_EPSILON * vsip_sqrt_d(vsip_msumsqval_d(A0)); vsip_mview_d *dif=vsip_mcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *out = vsip_mcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *Vt = vsip_mtransview_d(V); vsip_mprod_d(U,B,dif); vsip_mprod_d(dif,Vt,out); vsip_msub_d(out,A0,dif); vsip_mmag_d(dif, dif); chk = vsip_msumval_d(dif)/(2 * M * N); printf("%20.18e - %20.18e = %e\n",lim,chk, (lim - chk)); if(chk > lim){ printf("error\n"); } else { printf("correct\n"); } vsip_malldestroy_d(dif); vsip_malldestroy_d(out); vsip_mdestroy_d(Vt); } vsip_svd_destroy_d(svd); vsip_malldestroy_d(A0); vsip_malldestroy_d(A); vsip_valldestroy_d(s); vsip_malldestroy_d(U); vsip_malldestroy_d(B); vsip_malldestroy_d(V); } return; } <file_sep>// // extensionVector.swift // SJVsip // // Created by <NAME> on 11/4/17. // Copyright © 2017 JVSIP. All rights reserved. // import Foundation import vsip extension Vector { public static func + (left: Vector, right: Vector) -> Vector { let retval = left.empty add(left, right, resultsIn: retval) return retval } public static func - (left: Vector, right: Vector) -> Vector { let retval = left.empty sub(left, subtract: right, resultsIn: retval) return retval } public func randn(_ seed: vsip_index, portable: Bool) -> Vector { let state = Rand(seed: seed, portable: portable) state.randn(self) return self } public func randn(_ seed: vsip_index) -> Vector { return self.randn(seed, portable: true) } public func randu(_ seed: vsip_index, portable: Bool) -> Vector{ let state = Rand(seed: seed, portable: portable) state.randu(self) return self } public func randu(_ seed: vsip_index) -> Vector { return self.randu(seed, portable: true) } public var normFro: Double { get { return (SJvsip.normFro(view: self).reald) } } } <file_sep>## Created RJudd ## <NAME> ## $Id: Makefile,v 2.0 2003/02/22 15:27:33 judd Exp $ ## Top Level of library distribution ## RDIR=$(HOME)/local RDIR=../.. ## C compiler CC=cc INCLUDEDIR=-I$(RDIR)/include LIBDIR=-L$(RDIR)/lib LIBS=-lvsip -lm OPTIONS=-O2 example: example17.c $(CC) -o example17 example17.c $(OPTIONS) $(INCLUDEDIR) $(LIBDIR) $(LIBS) clean: rm -f example17 example17.exe <file_sep>## Created RJudd ## Top Level of JVSIP distribution RDIR=../.. ## C compiler CC=cc INCLUDEDIR=-I$(RDIR)/include LIBDIR=-L$(RDIR)/lib LIBS= -lvsip -lm OPTIONS=-O2 example:example21.c $(CC) -o example21 example21.c exUtils.c $(OPTIONS) $(INCLUDEDIR) $(LIBDIR) $(LIBS) clean: rm -f example21 example21.exe gram_output <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: msumsqval_d.h,v 2.0 2003/02/22 15:23:26 judd Exp $ */ #include"VU_mprintm_d.include" static void msumsqval_d(void){ printf("\n*******\nTEST msumsqval_d\n"); { vsip_scalar_d data[] = {1.0, 1.1, 1.2, 1.3, 1.4, 1.4, 1.3, 1.2, 1.1, 1.0}; vsip_mview_d *m1 = vsip_mbind_d( vsip_blockbind_d(data,10,VSIP_MEM_NONE),0,5,2,1,5); vsip_block_d *block = vsip_blockcreate_d(1024,VSIP_MEM_NONE); vsip_mview_d *m = vsip_mbind_d(block,4,20,2,2,5); vsip_blockadmit_d(vsip_mgetblock_d(m1),VSIP_TRUE); vsip_mcopy_d_d(m1,m); printf("matrix m1, user matrix, compact, row major\n"); VU_mprintm_d("6.4",m1); printf("matrix m1, VSIPL matrix, irregular, row major\n"); printf("col stride 20, row stride 2\n"); printf("copy m1 to m. Matrix m equals\n"); VU_mprintm_d("6.4",m); printf("msumsqval_d(m1) = %f\n",vsip_msumsqval_d(m1)); printf("msumsqval_d(m) = %f\n",vsip_msumsqval_d(m)); printf("ans should be 14.6 \n"); if(fabs(14.6000-vsip_msumsqval_d(m)) > .0001 || fabs(14.6000-vsip_msumsqval_d(m1)) > .0001) { printf("error\n"); }else{ printf("correct\n"); } vsip_malldestroy_d(m); vsip_malldestroy_d(m1); } return; } <file_sep># Notes # This module not really designed for general purpose use. I wrote this as a study mechanism for # decomposition algorithms. The codes are not well tested and may be naive. # # lapack working notes at http://www.netlib.org/lapack/lawns/ import pyJvsip as pv def eye(t,n): """ Usage: I=eye(t,n) create and return an identity matrix of size n and type t t must be a matrix """ return pv.create(t,n,n).identity def sign(a_in): # see LAPACK Working Notes 148 for definition of sign """ Function sign(alpha) returns the sign of scalar (real or complex) alpha. """ if type(a_in) is int: a=float(a_in) else: a=a_in if type(a) is float or type(a) is complex: t=pv.vsip_hypot_d(a.real,a.imag) if t == 0.0: return 1.0 elif a.imag==0.0: if a.real < 0.0: return -1.0 else: return 1.0 else: return a/t else: print('sign function only works on scalars') return # householder routines def houseVector(x): """ v = houseVector(x) returns a normalized householder vector 'v' such that the householder projection matrix 'H' is: H = I - 2 v v* """ if 'vview' not in x.type: print('Function houseVector only works on vector views') return v=x.copy v[0] += (sign(x[0]) * x.norm2) n = v.norm2 if n == 0.0: v[0] = 1.0 else: v /= n return v def house(v): # create and return househoulder rotation matrix for householder # vector v; works for any valid househoulder vector """ Usage: H=house(v) Create and return a householder projector matrix given input householder vector v. """ t={'vview_f':'mview_f','vview_d':'mview_d','cvview_f':'cmview_f','cvview_d':'cmview_d'} return(eye(t[v.type],v.length) - v.outer(2.0/v.jdot(v),v)) def houseProd(v,A): """ Usage: houseProd(v,A) using a householder vector V with a matrix of the proper size return HA Note A is modified in-place; but there are create/destroy penalties with this function Note a convenience reference to A is returned """ beta = 2.0/v.jdot(v) v.conj;w=v.prod(A).conj;v.conj A -= v.outer(beta,w) return A def prodHouse(A,v): """ Usage: prodHouse(A,v) using a householder vector V with a matrix of the proper size return AH Note A is modified in-place; but there are create/destroy penalties with this function Note a convenience reference to A is returned """ beta = 2.0/v.jdot(v) w=A.prod(v) A-=w.outer(beta,v) return A #Givens def givensCoef(x1_in,x2_in): """ Code adapted from Algorithm 1 of LAPACK working Notes lawn148 """ if type(x1_in) is int: x1=float(x1_in) else: x1 = x1_in if type(x2_in) is int: x2=float(x2_in) else: x2 = x2_in if type(x1) is float and type(x2) is float: t=pv.vsip_hypot_d(x1,x2) if x2 == 0.0: return (1.0,0.0,x1) elif x1 == 0.0: return (0.0,sign(x2),t) else: # return (c,s,r) sn=sign(x1) return(pv.vsip_mag_d(x1)/t,sn*x2/t,sn*t) elif type(x1) is complex or type(x2) is complex: mx1=pv.vsip_hypot_d(x1.real,x1.imag) mx2=pv.vsip_hypot_d(x2.real,x2.imag) if mx2 == 0.0: return(1.0,0.0,x1) elif mx1 == 0.0: return(0,sign(x2.conjugate()),mx2) else: t=pv.vsip_hypot_d(mx1,mx2) c=mx1/t sn=sign(x1) s=(sn * x2.conjugate())/t r=sn * t return(c,s,r) else: print('Type <:'+repr(type(x1)) + ':> or <:'+ \ repr(type(x2))+':> not recognized by givensCoef') return def givens(t,i,j,c,s,size): """ Return an extended givens matrix. An extended givens matrix is an identity matrix of size 'size' with elements at (i,i) and (j,j) replaced with c, the element at (i,j) replaced with s, and the element at (j,i) replaced with -conjugate(s) Usage: G=givens(t,i,j,c,s,size) Where: t = type i,j are index values for placement of c,s which are obtained (probably) from function givensCoef. size is an integer """ G=eye(t,size) G[i,i]=c;G[j,j]=c;G[i,j]=s;G[j,i]=-s.conjugate() return G def gProd(i,j,c,s,A): """ Done in-place (A is modified) Usage: gProd(i,j,c,s,A) where: A is a matrix of size (m,n) i,j,c,s are equivalent to a givens matrix G = givens(A.type,i,j,c,s,m) does: A = G A returns: reference to A as a convenience """ a1=A.rowview(i).copy a2=A.rowview(j).copy A.rowview(i)[:]= c * a1 + s * a2 A.rowview(j)[:]= c * a2 - s.conjugate() * a1 return A def prodG(A,i,j,c,s): """ Done in-place (A is modified) Usage: prodG(A,i,j,c,s) where: A is a matrix of size (m,n) i,j,c,s are equivalent to a givens matrix GH = givens(A.type,i,j,c,s,m).herm does: A = A GH returns: reference to A as a convenience """ a_i=A.colview(i).copy a_j=A.colview(j).copy A.colview(i)[:]= c * a_i + s.conjugate() * a_j A.colview(j)[:]= c * a_j - s * a_i return A def gtProd(i,j,c,s,A): """ Done in-place (A is modified) Usage: gtProd(i,j,c,s,A) where: A is a matrix of size (m,n) i,j,c,s are equivalent to a givens matrix G_TH = givens(A.type,i,j,c,s,m).transview.herm does: A = G_TH A returns: reference to A as a convenience """ a_i=A.rowview(i).copy a_j=A.rowview(j).copy A.rowview(i)[:]= c * a_i + s.conjugate() * a_j A.rowview(j)[:]= c * a_j - s * a_i return A def prodGT(A,i,j,c,s): """ Done in-place (A is modified) Usage: prodG(A,i,j,c,s) where: A is a matrix of size (m,n) i,j,c,s are equivalent to a givens matrix G_T = givens(A.type,i,j,c,s,m).transview does: A = A G_T returns: reference to A as a convenience """ a1 = A.colview(i).copy a2 = A.colview(j).copy A.colview(i)[:] = c * a1 + s * a2 A.colview(j)[:] = c * a2 -s.conjugate() * a1 return A # QR decomposition def QRD_inPlace(A): """ The function QRD_inPlace(A) is done in-place on matrix A. If you want to retain A make a copy first. Usage: QRD_inPlace(A) Note that the decomposition represented is A=QR. Matrix R is stored in the upper triangular portion of A. Householder vectors are stored in the lower sub-triangular portion of A. Householder vectors are normalized so that v[0] is 1.0; """ m=A.collength n=A.rowlength if m < n: print('The input matrix must have collength >= rowlength.') print('For matrices where rowlength > collength work with the transpose.') for i in range(n-1): x=A[i:,i:].colview(0) v=houseVector(x) v /= v[0] A[i:,i:]=house(v).prod(A[i:,i:]) x[1:]=v[1:] if m > n: #do last column if matrix not square i=n-1 x=A[i:,i:].colview(0) v=houseVector(x) v /= v[0] A[i:,i:]=house(v).prod(A[i:,i:]) x[1:]=v[1:] def fullQProd(Q,B): """ Usage: U=fullQProd(Q,B) where Q is a matrix of size M,N where M >= N which was produced by QRD_inPlace(Q) B is a matrix of size M,P U is the matrix produced by the matrix product Q B where Q is the full Q matrix from a QR decomposition. """ m=Q.collength n=B.rowlength U=B.copy if m > n: #extract last column if matrix is not square i=n-1 v=Q[i:,i:].colview(0).copy v[0]=1 houseProd(v,U[i:,i:]) for i in range(n-2,-1,-1): v=Q[i:,i:].colview(0).copy v[0]=1 houseProd(v,U[i:,i:]) return U def QmatExtract(B): """ If B is a matrix which has been operated on by QRD_inPlace then QmatExtract(B) will return the full Q matrix of the QR decomposition. """ m=B.collength n=B.rowlength Q=eye(B.type,m) if m > n: #extract last column if matrix is not square i=n-1 v=B[i:,i:].colview(0).copy v[0]=1 houseProd(v,Q[i:,i:]) for i in range(n-2,-1,-1): v=B[i:,i:].colview(0).copy v[0]=1 houseProd(v,Q[i:,i:]) return Q def RmatExtract(B): """ If B is a matrix which has been operated on by QRD_inPlace then RmatExtract(B) returns a new matrix with the (full) R from the QR decomposition. """ R=B.copy m=B.collength for i in range(1,m): R.diagview(-i).fill(0.0) return R def houseQR(A): """ Done out of place Usage: Q,R=houseQR(A) where: A is of size M, N; M >= N; A = Q R Q is unitary R is upper triangular """ R=A.copy m=A.collength n=A.rowlength if m < n: print('The input matrix must have collength >= rowlength.') print('for matrices where rowlength > collength work with the transpose') for i in range(n-1): x=R[i:,i:].colview(0) v=houseVector(x) v /= v[0] houseProd(v,R[i:,i:]) x[1:]=v[1:] if m > n: #do last column if matrix not square i=n-1 x=R[i:,i:].colview(0) v=houseVector(x) v /= v[0] houseProd(v,R[i:,i:]) x[1:]=v[1:] #accumulate Q Q = QmatExtract(R) #zero entries of R for i in range(1,m): R.diagview(-i).fill(0.0) return (Q,R) def bidiag(A): # m >= n """ B=bidiag(A) returns, out of place, the bidiagonal decomposition of A. The esential househoulder vectors are stored in the zeroed entries of B. """ B=A.copy m=B.collength n=B.rowlength if m < n: print('The input matrix must have collength >= rowlength.') print('for matrices where rowlength > collength work with the transpose') for i in range(n-1): x=B[i:,i:].colview(0) v=houseVector(x) v /= v[0] houseProd(v,B[i:,i:]) x[1:]=v[1:] if i < n-2: j=i+1 x = B[i:,j:].rowview(0) #v=houseVector(x.conj);x.conj v=houseVector(x).conj v /= v[0] prodHouse(B[i:,j:],v)#=B[i:,j:].prod(house(v)) x[1:]=v[1:] if m > n: #do last column if matrix not square i=n-1 x=B[i:,i:].colview(0) v=houseVector(x) v /= v[0] houseProd(v,B[i:,i:]) x[1:]=v[1:] return B def bidiagExtract(B): """ B=bidiagExtract(B0) Returns, out of place, a matrix with the bidiagonal entries. Input matrix is one produced by B0=bidiag(A) """ B0=B.empty.fill(0.0) B0.diagview(0)[:] = B.diagview(0) B0.diagview(1)[:] = B.diagview(1) return B0 def UmatExtract(B): """ U=UmatExtract(B0) returns, out of place, the U matrix of the bidiagonal decomposition A=UBV^H given the result of bidiag routine B0=bidiag(A) """ m=B.collength n=B.rowlength U=eye(B.type,m) if m > n: #extract last column if matrix is not square i=n-1 v=B[i:,i:].colview(0).copy v[0]=1 houseProd(v,U[i:,i:]) for i in range(n-2,-1,-1): v=B[i:,i:].colview(0).copy v[0]=1 houseProd(v,U[i:,i:]) return U def VHmatExtract(B): """ VH=UmatExtract(B0) returns, out of place, the hermtian V matrix of the bidiagonal decomposition A=UBV^H given the result of bidiag routine B0=bidiag(A) """ m=B.collength n=B.rowlength V=eye(B.type,n) for i in range(n-3,-1,-1): j=i+1 v=B[i:,j:].rowview(0).copy v[0]=1 prodHouse(V[j:,j:],v) return V def givensCoef(x1_in,x2_in): """ Code adapted from Algorithm 1 of LAPACK working Notes lawn148 """ if type(x1_in) is int: x1=float(x1_in) else: x1 = x1_in if type(x2_in) is int: x2=float(x2_in) else: x2 = x2_in if type(x1) is float and type(x2) is float: t=pv.vsip_hypot_d(x1,x2) if x2 == 0.0: return (1.0,0.0,x1) elif x1 == 0.0: return (0.0,sign(x2),t) else: # return (c,s,r) sn=sign(x1) return(pv.vsip_mag_d(x1)/t,sn*x2/t,sn*t) elif type(x1) is complex or type(x2) is complex: mx1=pv.vsip_hypot_d(x1.real,x1.imag) mx2=pv.vsip_hypot_d(x2.real,x2.imag) if mx2 == 0.0: return(1.0,0.0,x1) elif mx1 == 0.0: return(0,sign(x2.conjugate()),mx2) else: t=pv.vsip_hypot_d(mx1,mx2) c=mx1/t sn=sign(x1) s=(sn * x2.conjugate())/t r=sn * t return(c,s,r) else: print('Type <:'+repr(type(x1)) + ':> or <:'+ \ repr(type(x2))+':> not recognized by givensCoef') return def givensExtract(t,i,j,c,s,size): """ Usage: G=givensExtract(t,i,j,c,s,size) t = type i,j are index values for placement of c,s which are obtained (probably) from function givensCoef. size is an integer """ G=eye(t,size) G[i,i]=c;G[j,j]=c;G[i,j]=s;G[j,i]=-s.conjugate() return G def gProd(i,j,c,s,A): a1=A.rowview(i).copy a2=A.rowview(j).copy A.rowview(i)[:]= c * a1 + s * a2 A.rowview(j)[:]= c * a2 - s.conjugate() * a1 return A def prodG(A,i,j,c,s): a_i=A.colview(i).copy a_j=A.colview(j).copy A.colview(i)[:]= c * a_i + s.conjugate() * a_j A.colview(j)[:]= c * a_j - s * a_i return A def gtProd(i,j,c,s,A): a_i=A.rowview(i).copy a_j=A.rowview(j).copy A.rowview(i)[:]= c * a_i + s.conjugate() * a_j A.rowview(j)[:]= c * a_j - s * a_i return A def prodGT(A,i,j,c,s): a1 = A.colview(i).copy a2 = A.colview(j).copy A.colview(i)[:] = c * a1 + s * a2 A.colview(j)[:] = c * a2 -s.conjugate() * a1 return A def givensQR(A): M = A.collength N = A.rowlength R = A.copy Q = eye(A.type,M) for i in range(N): B=R[i:,i:] r=B[0,0] for j in range(1,B.collength): c,s,r=givensCoef(r,B[j,0]) prodG(Q,i,j+i,c,s) gProd(0,j,c,s,B) return (Q,R) def givensBidiag(A): M = A.collength N = A.rowlength B = A.copy U = eye(A.type,M) VH = eye(A.type,N) for i in range(N-1): TC=B[i:,i:] if i < N-2: TR=B[i:,i+1:] r=TC[0,0] for j in range(1,TC.collength): c,s,r=givensCoef(r,TC[j,0]) prodG(U,i,j+i,c,s) gProd(0,j,c,s,TC) if i < N-2: r=TR[0,0] k=i+1 for j in range(1,TR.rowlength): c,s,r=givensCoef(r,TR[0,j]) gtProd(k,j+k,c,s,VH) prodGT(TR,0,j,c,s) if M > N: i=N-1 TC=B[i:,i:] r=TC[0,0] for j in range(1,TC.collength): c,s,r=givensCoef(r,TC[j,0]) prodG(U,i,j+i,c,s) gProd(0,j,c,s,TC) return (U,B,VH) def svdZeroCheckAndSet(e,b0,b1): """ Usage: svdZeroCheckAndSet(eps,d,f) Where: eps0 is a small number we consider to be (close to) zero d is a vector view representing the main diagonal of an upper bidiagonal matrix f is a vector view representing the superdiagonal in an upper bidiagonal matrix. In the svd algorithm this checks the superdiagonal for small numbers which may be set to zero. If found, set to zero. """ s=e * (b0[0:b1.length].mag + b0[1:].mag) indx_bool = b1.mag.llt(s) if indx_bool.anytrue: #check super diagonal b1.indxFill(indx_bool.indexbool,0.0) def svdCorners(b1): """ Functionality i,j = svdCorners(v) where v is a real vector of type float or double i,j are indices. i,j; as returned v[i:j-1] will be vector with no zero elements v[j-1:] will be a vector with all zero elements Note v is the first super-diagonal of a bidiagonal matrix. The corresponding main diagonal, d, will be d[i:j] """ v_bool=b1.leq(0.0) j=v_bool.length-1 while j >= 0 and v_bool[j] == 1: j -= 1 if j == -1: return(0,0) #all of b1 is zero i=j #index of non-zero j+=1 #index of zero while i >= 0 and v_bool[i] == 0: i -= 1 return(i+1,j+1) def diagPhaseToZero(L,B): """ To phase shift the main diagonal entries of a matrix B so entries are real (imaginary zero) use this routine. """ d = B.diagview(0) for i in range(d.length): ps=d[i] #phase shift if ps.imag != 0.0: #ignore if already real m = pv.vsip_hypot_d(ps.real,ps.imag) ps /= m L.colview(i)[:] *= ps B.rowview(i)[:] *= ps # if B is strictly diagonal don't need this step d[i] = m def biDiagPhaseToZero(L,d,f,R,eps0): """ For a Bidiagonal matrix B This routine uses subview vectors `d=B.diagview(0)` and `f=B.diagview(1)` and phase shifts vectors d and f so that B has zero complex part. Matrices L and R are update matrices. eps0 is a small real number used to check for zero. If an element meets a zero check then that element is set to zero. """ for i in range(d.length): ps=d[i] if ps.imag == 0.0: m = ps.real if m < 0.0: ps=-1.0 else: ps= 1.0 m = abs(m) else: m=pv.vsip_hypot_d(ps.real,ps.imag) ps /= m if m > eps0: L.colview(i)[:] *= ps d[i] = m if i < f.length: f[i] *= ps.conjugate() else: d[i] = 0.0 svdZeroCheckAndSet(eps0,d,f) for i in range(f.length-1): j=i+1 ps = f[i] if ps.imag == 0.0: m = ps.real if m < 0.0: ps=-1.0 else: ps= 1.0 m = abs(m) else: m=pv.vsip_hypot_d(ps.real,ps.imag) ps /= m L.colview(j)[:] *= ps.conjugate() R.rowview(j)[:] *= ps f[i] = m; f[j] *= ps j=f.length i=j-1 ps=f[i] if ps.imag == 0.0: m = ps.real if m < 0.0: ps=-1.0 else: ps= 1.0 m = abs(m) else: m=pv.vsip_hypot_d(ps.real,ps.imag) ps /= m f[i]=m L.colview(j)[:] *= ps.conjugate() R.rowview(j)[:] *= ps def zeroRow(L,d,f): """ To use this we assume a matrix B that is bi-diagonalized. Note i,j = svdCorners(B) => i, j=n+1 Let d0 be B.diagview(0); f0 be B.diagview(1) d is a subview of the main diagonal f is a subview of the first superdiagonal (diagonal(1)) and has no zeros. if f = f0[i:n] then d = d0[i:n+1] L is a subview of the left update matrix we call L0 here. for the indices shown above L = L0[:,i:n+1] If d contains a zero entry, and the zero entry is not at the end of d, then zeroRow is used to zero out the corresponding superdiagonal entry in the row. Vector d may contain more than one zero. We zero out the zero with the largest index (we designate k). So d[k] = d0[i+k] is the zero of interest. Note if d[k] is the last entry then the corresponding superdiagonal entry in the row is already zero. Use zeroCol to zero out the column. Usage: zeroRow(L[:,k:],d[k+1:],f[k:]) """ if 'cvview' in d.type or 'cvview' in f.type: print('zeroRow only works for real vectors') return if d.length == 1: c,s,r=givensCoef(d[0],f[0]) f[0]=0.0;d[0]=r else: c,s,r=givensCoef(d[0],f[0]) f[0]=0;d[0]=r t= - f[1] * s; f[1] *= c prodG(L,1,0,c,s) for i in range(1,d.length-1): c,s,r=givensCoef(d[i],t) prodG(L,i+1,0,c,s) d[i]=r; t=-f[i+1] * s; f[i+1] *= c c,s,r=givensCoef(d[d.length-1],t) d[d.length-1] = r prodG(L,d.length,0,c,s) def zeroCol(d,f,R): """ To use this we assume a matrix B that is bi-diagonalized. Note i,j = svdCorners(B) => i, j=n+1 Let d0 be B.diagview(0); f0 be B.diagview(1) d is a subview of the main diagonal f is a subview of the first superdiagonal (diagonal(1)) and has no zeros. if f = f0[i:n] then d = d0[i:n+1] R is a subview of the right update matrix we call R0 here. for the indices shown above R = R0[i:n+1,:] We assume matrix B has all zeros on row n. Usage: zeroCol(d,f,R) """ if 'cvview' in d.type or 'cvview' in f.type: print('zeroCol only works for real vectors') return if f.length == 1: c,s,r=givensCoef(d[0],f[0]) d[0]=r; f[0]=0.0 gtProd(0,1,c,s,R) elif f.length == 2: c,s,r=givensCoef(d[1],f[1]) d[1]=r; f[1]=0; t= - f[0] * s; f[0] *= c gtProd(1,2,c,s,R) c,s,r=givensCoef(d[0],t) d[0]=r; gtProd(0,2,c,s,R) else: i=f.length-1; j=i-1; k=i c,s,r=givensCoef(d[i],f[i]) f[i]=0; d[i]=r; t=-f[j]*s; f[j]*=c; gtProd(i,k+1,c,s,R) while i > 1: i = j; j = i-1 c,s,r=givensCoef(d[i],t) d[i]=r; t= - f[j] * s; f[j] *= c gtProd(i,k+1,c,s,R) c,s,r=givensCoef(d[0],t) d[0] = r gtProd(0,k+1,c,s,R) def svdMu(d2,f1,d3,f2): """ Complex is removed from bidiagonal so for this algorithm we expect real numbers. """ td=d2*d2; tf=f1*f1 if td == 0.0: cu = tf elif (td < tf): cu=tf * (1.+td/tf) else: cu=td * (1.+tf/td); td=d3*d3; tf=f2*f2 if td == 0.0: cl = tf elif (td < tf): cl=tf * (1.+td/tf) else: cl=td * (1.+tf/td); cd = d2 * f2 T = (cu + cl) D = (cu * cl - cd * cd)/(T*T) if 4.*D > 1.0: root = 0.0 else: root = T * pv.vsip_sqrt_d(1.0 - 4. * D) lambda1 = (T + root)/(2.); lambda2 = (T - root)/(2.) if abs(lambda1 - cl) < abs(lambda2 - cl): mu = lambda1 else: mu = lambda2 return mu def svdStep(L,d,f,R): if 'cvview' in d.type or 'cvview' in f.type: print('Input vector views must be of type real; Fail for svdStep') return n=d.length #initial step if n >= 3: mu = svdMu(d[n-2],f[n-3],d[n-1],f[n-2]) elif n == 2: mu = svdMu(d[0],0.0,d[1],f[0]) else: mu = svdMu(d[0],0.0,0.0,0.0) x1=d[0]; x1 *= x1; x1 -= mu x2 = d[0] * f[0] c,s,r=givensCoef(x1,x2) t=d[0] * c + s * f[0]; f[0] *= c; f[0] -= s * d[0]; d[0] = t; t=s * d[1]; d[1] *= c; gtProd(0,1,c,s,R) for i in range(n-2): j=i+1; k=i+2 #step c,s,r = givensCoef(d[i],t) d[i]=r; t=c * d[j] - s * f[i]; f[i] *=c ;f[i]+=s*d[j];d[j]=t t=s * f[j]; f[j] *= c; prodG(L,i,j,c,s) #step c,s,r=givensCoef(f[i],t) f[i]=r t=c * d[j] + s * f[j]; f[j] *= c; f[j] -= s * d[j]; d[j] = t t=s * d[k]; d[k] *= c; gtProd(j,k,c,s,R) #final step i=n-2; j=n-1 c,s,r = givensCoef(d[i],t) d[i]=r; t= c * d[j] - s * f[i]; f[i] *= c; f[i] += s * d[j]; d[j]=t prodG(L,i,j,c,s) def zeroFind(d,eps0): j = d.length xd=d[j-1] while(xd > eps0): if (j > 1): j -= 1; xd=d[j-1] elif(j==1): return 0; d[j-1]=0.0 return j def svd(A): """ The bidiag routine is used in the svd and bidiag is defined out of place, so svd is also out of place. The bidiag routine can be done in-place with a simple change, so the svd can also be done in-place. Usage: U,S,VH = svd(A) A is a matrix with column length >= row length where U is a unitary matrix of size A.columnlength S is a real vector of size A.rowlength containing the singular values of A Note: S is considered here to be a diagonal matrix VH is a unitary matrix of size A.rowlength Note: A = U S VH = U.prod(S.mmul(VH.ROW)) """ def svdBidiagonal(A): if 'mview_f' not in A.type and 'mview_d' not in A.type: print('Input must be a matrix of type float for function svd.') return if A.rowlength > A.collength: print('For svd function input matrix A of size (M,N) must have N >= M') return(0,0,0,0,0) if 'mview_d' in A.type: eps0 = A.normFro/A.rowlength * 1.0E16 else: eps0 = A.normFro/A.rowlength * 1.0E8 if eps0 == 0.0: print('Input matrix appears to be zero') return(0,0,0,0,0) else: eps0 = 1.0/eps0 B=bidiag(A) L=UmatExtract(B) R=VHmatExtract(B) biDiagPhaseToZero(L,B.diagview(0),B.diagview(1),R,eps0) if 'cmview' in B.type: d0=B.diagview(0).realview.copy f0=B.diagview(1).realview.copy else: d0=B.diagview(0).copy f0=B.diagview(1).copy return (L,d0,f0,R,eps0) def svdIteration(L0,d0,f0,R0,eps0): cntr=0 maxcntr=5*d0.length while cntr < maxcntr: print('%d %d\n'%(d0.length,f0.length)) biDiagPhaseToZero(L0,d0,f0,R0,eps0) cntr += 1 i,j=svdCorners(f0) if j == 0: break d=d0[i:j] f=f0[i:j-1] L=L0[:,i:j] R=R0[i:j,:] n=f.length k=zeroFind(d,eps0) if k >0: k -= 1; if d[n] == 0.0: zeroCol(d,f,R) else: zeroRow(L[:,k:],d[k+1:],f[k:]) else: svdStep(L,d,f,R) def svdSort(L,d,R): indx=d.sort('BYVALUE','DESCENDING') if 'cmview' in R.type: R.realview.permute(indx,'ROW') R.imagview.permute(indx,'ROW') L[:,0:d.length].realview.permute(indx,'COL') L[:,0:d.length].imagview.permute(indx,'COL') else: R.permute(indx,'ROW') L[:,0:d.length].permute(indx,'COL') U,S,f0,VH,eps0 = svdBidiagonal(A) svdIteration(U,S,f0,VH,eps0) svdSort(U,S,VH) return(U,S,VH) <file_sep>// // SJVsip.Tests.swift // SJVsip.Tests // // Created by <NAME> on 11/4/17. // Copyright © 2017 JVSIP. All rights reserved. // import XCTest import vsip @testable import SJVsip class SJVsipTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // // SwiftVsipTests.swift // SwiftVsipTests // // Created by <NAME> on 10/7/16. // Copyright © 2016 JVSIP. All rights reserved. // func testVector() { // All we do here is make sure some stuff runs without failing var v = SJVsip.Vector(length: 10, type: .cd) let _ = v.randn(8) v.mPrint("4.3") v.real.mPrint("4.3") v.imag.mPrint("4.3") SJVsip.add(v.real, v.imag, resultsIn: v.real) v.mPrint("4.3") v.randn(9).mPrint("4.3") v = SJVsip.Vector(length: 11, type: .cf) v.randu(11).mPrint("5.4") } func testMatrix() { // All we do here is make sure some stuff runs without failing var m = SJVsip.Matrix(columnLength: 4, rowLength: 3, type: .cf, major: VSIP_ROW) let _ = m.randn(8, portable: true) m.mPrint("4.3") m.real.mPrint("4.3") m.imag.mPrint("4.3") SJVsip.add(m.real, m.imag, resultsIn: m.real) m.mPrint("4.3") m.randn(9, portable: true).mPrint("4.3") m = SJVsip.Matrix(columnLength: 5, rowLength: 3, type: .d, major: VSIP_COL) m.randu(11, portable: false).mPrint("5.4") } func testScalarPlus(){ let a = SJVsip.Scalar(15.0) let b = SJVsip.Scalar(4.0) let d = a + b print("a + b = \(d.reald)") } func testDiv(){ let a = SJVsip.Vector(length: 10, type: .f) let b = a.empty let c = a.empty a.fill(SJVsip.Scalar(1.0)) b.fill(SJVsip.Scalar(2.0)) SJVsip.div(numerator: a, denominator: b, quotient: c) c.mPrint("3.2") } func testScalarSqrt(){ let a = SJVsip.Scalar(vsip_cmplx_d(4.0, 5.0)) let b = vsip_csqrt_d(vsip_cmplx_d(4.0, 5.0)) let c = a.sqrt print("( \(b.r), \(b.i))") print("( \(c.reald), \(c.imagd))") XCTAssert((b.r == c.reald) && (b.i == c.imagd)) } func testSvd(){ let n = 5 let A = SJVsip.Matrix(columnLength: n, rowLength: n, type: .d, major: VSIP_ROW) let x = SJVsip.Vector(length: A.rowLength, type: A.type) let b = SJVsip.Vector(length: A.columnLength, type: A.type) let fmt = "6.5" let chk = 1E-14 let _ = A.randn(5, portable: true) let _ = x.randn(9, portable: true) let normA = SJvsip.normFro(view: A) SJVsip.prod(A, times: x, resultsIn: b) print("Matrix A");A.mPrint(fmt) print("Known x vector");x.mPrint(fmt) print("Calculated b=Ax vector"); b.mPrint(fmt) // check that U S V^t gives back A let Ac = A.newCopy // Ac is used for decompostion to keep original A let Ar = A.empty // new data space for result let svd = SJVsip.Svd(view: Ac) let sValues = svd.decompose(Ac) let U = svd.matU! let V = svd.matV! print("U");U.mPrint(fmt) print("Singular Values");sValues.mPrint(fmt) print("V");V.mPrint(fmt) let USr = U.empty // result of matrix product of U and Singular Vaules SJVsip.vmmul(vector: sValues, matrix: U, major: VSIP_ROW, resultsIn: USr) SJVsip.prod(USr, times: V.transview, resultsIn: Ar) print("Result of USV^t"); Ar.mPrint(fmt) SJVsip.sub(A, subtract: Ar, resultsIn: Ar) var normChk = SJvsip.normFro(view:Ar).reald / normA.reald print("normChk: \(normChk)") print("Check USV^t equal input matrprix within reasonable bounds") XCTAssert( normChk < chk, "Check Failed for equality of USV^t with input matrix within reasonable bounds") let xe = x.empty // x estimate for backsolve SJVsip.prod(U.transview, times: b, resultsIn: xe) SJVsip.div(numerator: xe, denominator: sValues, quotient: xe) SJVsip.prod(V, times: xe.newCopy, resultsIn: xe) print("solve for estimate of x from b");xe.mPrint(fmt) SJVsip.sub(x, subtract: xe, resultsIn: xe) normChk = SJvsip.normFro(view: xe).reald/SJvsip.normFro(view: x).reald print("Check estimate of x equal x within reasonable bounds (for Ax=b then x_est = V S^-1 U^T b)") XCTAssert( normChk < chk, "Check Failed for (in Ax=b) estimate of x equal to x within reasonable bounds") } func testHouseReflection(){ // create and check a householder reflection let n = 3 let v = SJVsip.Vector(length: n, type: .d) let A = SJVsip.Matrix(columnLength: n, rowLength: n, type: .d, major: VSIP_ROW) let I = A.empty I.fill(SJVsip.Scalar(0.0)) let Id = I.diagview Id.fill(SJVsip.Scalar(1.0)) v[0] = SJVsip.Scalar(2.0); v[1] = SJVsip.Scalar(3.0); v[2] = SJVsip.Scalar(1.0) SJVsip.outer(alpha: SJVsip.Scalar(1.0), vecX: v, vecY: v, matC: A) let beta = SJVsip.Scalar(2.0 / SJVsip.dot(product: v, with: v).reald) SJVsip.mul(beta.reald, A, resultsIn: A) let P = A.empty P.fill(SJVsip.Scalar(0.0)) P.diagview.fill(SJVsip.Scalar(1.0)) SJVsip.sub(P, subtract: A, resultsIn: P) print(beta.reald) A.mPrint("4.3") P.mPrint("4.3") SJVsip.prod(P, times: P, resultsIn: A) A.mPrint("4.3") let chk = (I-A).normFro //SJvsip.normFro(view: tmp).reald print("chk is \(chk)") XCTAssert(chk < 1E-10) } func testQrd(){ let m = 6 let n = 4 let A = SJVsip.Matrix(columnLength: m, rowLength: n, type: .d, major: VSIP_ROW) // generate some data let _ = A.randn(8, portable: true) // keep a copy of original let Acopy = A.newCopy // make some space for an estimate of A to be calculated with Q and R let Ae = A.empty // get (Q,R) let (Q,R) = Acopy.qr // Calculate Ae SJVsip.prod(Q, times: R, resultsIn: Ae) // print original and estimate A.mPrint("5.3") Ae.mPrint("5.3") let chk = SJvsip.normFro(view: (A - Ae)).reald print("chk is \(chk)") XCTAssert(chk < 1E-10) } func testCgemp(){ print("********\nTEST cgemp_f\n"); let alpha = SJVsip.Scalar(vsip_cmplx_f(1.5,0.25)) let beta = SJVsip.Scalar(vsip_cmplx_f(-0.5,2.0)) var data_ar: [Float] = [1.0, 2.0, -3.0, 4.0, 5.0, 5.0, 0.1, 0.2, 0.3, 0.4, -4.0, 3.0, 2.0, 0.0, -1.0] var data_ai: [Float] = [0.1, 2.1, -2.0, 3.0, 5.0, 3.1, 1.1, 1.2, -5.3, 1.4, -2.0, 2.2, 2.2, 0.5, 1.1] var data_br: [Float] = [0.4, 1.5, -2.7, 3.0, 9.0, -1.1, -0.2, -0.3, -0.2, 1.3, 3.0, 2.0, 1.0, 4.0, -1.0] var data_bi: [Float] = [1.4, 1.2, -1.7, 3.0, 9.0, -1.1, -3.1, -1.3, -0.2, 1.3, 2.2, 2.1, 1.1, 40.0, -1.0] var ans_nh_data_r: [Float] = [ 192.1675, 8.0525, 234.2950, 11.6775, -18.4175, -273.6475, -13.0900, -10.6825, 26.1100 ] var ans_nh_data_i: [Float] = [ 28.9250, 9.0000, -188.0425, -19.1325, 6.0375, -94.8375, 34.2900, 17.5325, 7.5850 ] var ans_hn_data_r: [Float] = [ -35.0800, -25.7575, -18.3475, -103.0250, 37.2750, 24.6250, 19.8000, -7.4075, 141.3150, 51.6400, 10.0750, -1.7650, 22.5000, 104.9800, -67.5450, 20.4150, 42.2025, -11.5300, 64.0300, 80.8050, 10.5100, 16.7750, -35.2700, 116.5100, 139.1600 ] var ans_hn_data_i: [Float] = [ -7.1250, -28.0950, -13.2625, -243.6250, 30.1250, 13.1550, 9.2675, 8.6025, 199.1650, 8.3150, -0.9250, 2.2200, 7.7750, 127.2800, -22.4950, 2.7100, 7.2200, 0.5925, 14.8200, 43.6700, 7.0100, -3.2925, 2.6175, -44.3900, 28.7600 ] var ans_tn_data_r: [Float] = [ 23.0200, 84.6762, 36.7462, 679.7875, -66.4125, -37.8225, -24.4900, -12.2688,-618.3525, -55.2650, 1.4875, -2.4025, -21.7000,-449.6300, 75.4575, -33.8675, -60.8587, -11.9650, -94.8350,-116.5725, -35.2850, -2.6475, 9.8700, -39.6850,-148.9600 ] var ans_tn_data_i: [Float] = [ -102.2225, -76.7225, -54.2013,-317.1125, 102.1125, 66.7325, 59.8587, -25.1238, 375.3125, 148.2625, 28.2675, -2.6900, 63.9775, 235.9000,-197.4375, 57.7100, 92.6550, -46.4638, 152.1200, 227.9700, 27.3650, 53.6788,-107.6362, 234.3250, 402.5000 ] func blockbind_cf(length: Int, real: UnsafeMutablePointer<Float>, imag: UnsafeMutablePointer<Float>) -> SJVsip.Block { let blk = SJVsip.Block(length: length, type: .cf) let v = blk.bind(offset: 0, stride: 1, length: length) vsip_cvcopyfrom_user_f(real, imag, v.vsip) return blk } let block_a = blockbind_cf(length: 15, real: &data_ar, imag: &data_ai) let block_b = blockbind_cf(length: 15, real: &data_br, imag: &data_bi) let block_ans_nh = blockbind_cf(length: 9, real: &ans_nh_data_r, imag: &ans_nh_data_i) let block_ans_hn = blockbind_cf(length: 25, real: &ans_hn_data_r, imag: &ans_hn_data_i) let block_ans_tn = blockbind_cf(length: 25, real: &ans_tn_data_r, imag: &ans_tn_data_i) let block = SJVsip.Block(length: 400, type: .cf) let au = block_a.bind(offset: 0,columnStride: 5,columnLength: 3,rowStride: 1,rowLength: 5); let bu = block_b.bind(offset: 0,columnStride: 5,columnLength: 3,rowStride: 1,rowLength: 5); let ans_nh = block_ans_nh.bind(offset: 0,columnStride: 3,columnLength: 3,rowStride: 1,rowLength: 3); let ans_hn = block_ans_hn.bind(offset: 0,columnStride: 5,columnLength: 5,rowStride: 1,rowLength: 5); let ans_tn = block_ans_tn.bind(offset: 0,columnStride: 5,columnLength: 5,rowStride: 1,rowLength: 5) let a = block.bind(offset: 15,columnStride: -1,columnLength: 3,rowStride: -3,rowLength: 5); let b = block.bind(offset: 100,columnStride: 2,columnLength: 3,rowStride: 10,rowLength: 5); let cnt = block.bind(offset: 200,columnStride: -8,columnLength: 3,rowStride: -2,rowLength: 3); let ctn = block.bind(offset: 300,columnStride: 2,columnLength: 5,rowStride: 15,rowLength: 5); let chk_nt = SJVsip.Matrix(columnLength: 3,rowLength: 3, type: .cf, major: VSIP_COL) let chk_nt_r = chk_nt.real let chk_tn = SJVsip.Matrix(columnLength: 5,rowLength: 5, type: .cf, major: VSIP_ROW) SJVsip.copy(from: au, to: a) SJVsip.copy(from: bu, to: b) cnt.fill(SJVsip.Scalar(vsip_cmplx_f(1.0,0.5))) ctn.fill(SJVsip.Scalar(vsip_cmplx_f(2.0,-1.0))) // test nh n=>NTRANS, h=>Herm print("\nvsip_cgemp_f(alpha,a,VSIP_MAT_NTRANS,b,VSIP_MAT_HERM,beta,c)\n") print("alpha = \(alpha)") print("matrix a = ");a.mPrint("6.4") print("matrix b = ");b.mPrint("6.4") print("beta = \(beta)") print("on input matrix c = "); cnt.mPrint("6.4") // for manual calculation let cexact = cnt.newCopy SJVsip.mul(beta, cexact, resultsIn: cexact) let aexact = a.newCopy SJVsip.mul(alpha, aexact, resultsIn: aexact) let bexact = b.transview.newCopy SJVsip.herm(b, output: bexact) let tmp = cnt.empty SJVsip.prod(aexact, times: bexact, resultsIn: tmp) SJVsip.add(cexact, tmp, resultsIn: cexact) // cexact has result of gemp as manual calculation SJVsip.gemp(alpha: alpha,matA: a,opA: VSIP_MAT_NTRANS,matB: b,opB: VSIP_MAT_HERM,beta: beta,matC: cnt); print("on resultsIn matrix c = "); cnt.mPrint("6.4") print("right answer = "); ans_nh.mPrint("6.4") SJVsip.sub(cnt,subtract: ans_nh, resultsIn: chk_nt) var chk = SJvsip.normFro(view: chk_nt_r).reald print(chk); fflush(stdout) chk > 0.5 ? print("error\n") : print("correct\n") chk = SJvsip.normFro(view: (cnt - cexact)).reald XCTAssert(chk < 1E-4) print("Checking using manual calculation against gemp calculation gives error \(chk)"); fflush(stdout) /* test hn */ print("\nvsip_cgemp_f(alpha,a,VSIP_MAT_HERM,b,VSIP_MAT_NTRANS,beta,c)\n"); print("alpha = " + alpha.string(format: "4.2")) print("matrix a = ");a.mPrint("6.4") print("matrix b = ");b.mPrint("6.4") print("beta = " + beta.string(format: "4.2")) print("on input matrix c = ");ctn.mPrint("6.4") SJVsip.gemp(alpha: alpha,matA: a,opA: VSIP_MAT_HERM,matB: b,opB: VSIP_MAT_NTRANS,beta: beta,matC: ctn); print("on results In matrix c = ");ctn.mPrint("6.4") print("right answer = ");ans_hn.mPrint("6.4") SJVsip.sub(ctn, subtract: ans_hn, resultsIn: chk_tn) chk = SJvsip.normFro(view: chk_tn).reald if chk > 1E-4 { print("error\n"); } else { print("correct\n"); } /* test tn */ print("\nvsip_cgemp_f(alpha,a,VSIP_MAT_TRANS,b,VSIP_MAT_NTRANS,beta,c)\n"); print("alpha = " + alpha.string(format: "6.4")) print("matrix a = ");a.mPrint("6.4") print("matrix b = ");b.mPrint("6.4") print("beta = " + beta.string(format: "6.4")) print("on input matrix c = ");ctn.mPrint("6.4") SJVsip.gemp(alpha: alpha,matA: a,opA: VSIP_MAT_TRANS,matB: b,opB: VSIP_MAT_NTRANS,beta: beta,matC: ctn); print("on results In matrix c = ");ctn.mPrint("6.4") print("right answer = "); ans_tn.mPrint("6.4") SJVsip.sub(ctn, subtract: ans_tn, resultsIn: chk_tn) chk = SJvsip.normFro(view: chk_tn).reald if chk > 1E-4 { print("error\n") } else { print("correct\n") } } func testPut() { print("Testing Put") let v = SJVsip.Vector(length: 10, type: .d) v.fill(SJVsip.Scalar(0.0)) v.put(1.0,1.3,1.4,1.2,0.9,3.9,5.6) v.mPrint("3.2") } func testKvc(){// KVC fails; must be doing something wrong." let v = SJVsip.Vector(length: 35, type: .d) let _ = v.ramp(SJVsip.Scalar(0.1), increment: SJVsip.Scalar(0.2)) v.mPrint("3.2") //v.setValue(10, forKey: "length") //v.setValue(2, forKey: "stride") v.length = 10 v.stride = 2 v.mPrint("3.2") v.offset = 1 v.mPrint("3.2") } } <file_sep>#include"vsip.h" #include"vsip_mviewattributes_i.h" void (vsip_mcopy_i_i)( const vsip_mview_i* a, const vsip_mview_i* r) { vsip_length n_mj, /* major length */ n_mn; /* minor length */ vsip_stride ast_mj, ast_mn; vsip_scalar_i *ap = (a->block->array) + a->offset; vsip_scalar_i *ap0 = ap; vsip_index i=0,j=0; /* pick direction dependent on input */ if(a->row_stride < a->col_stride){ /* Row Major */ n_mj = a->row_length; n_mn = a->col_length; ast_mj = a->row_stride; ast_mn = a->col_stride; while(n_mn-- > 0){ vsip_length n = n_mj; while(n-- >0){ vsip_mput_i(r,i,j,(vsip_scalar_i) *ap); ap += ast_mj; j++; } ap0 += ast_mn; ap = ap0; i++; j=0; } } else { /* must be Col Major */ n_mn = a->row_length; n_mj = a->col_length; ast_mn = a->row_stride; ast_mj = a->col_stride; while(n_mn-- > 0){ vsip_length n = n_mj; while(n-- >0){ vsip_mput_i(r,i,j,(vsip_scalar_i) *ap); ap += ast_mj; i++; } ap0 += ast_mn; ap = ap0; i=0; j++; } } return; } <file_sep>import Foundation public enum Major: String { case row, col } public struct Matrix { public var block: Block public var offset: Int public var colstride: Int public var collength: Int public var rowstride: Int public var rowlength: Int public var type: BlockTypes { get { return self.block.type } } public init(block: Block, offset: Int, colstride: Int, collength: Int, rowstride: Int, rowlength: Int) { self.block = block self.offset = offset self.colstride = colstride self.collength = collength self.rowstride = rowstride self.rowlength = rowlength } public init(collength: Int, rowlength: Int, type: BlockTypes, major: Major = .row) { self.block = Block(length: rowlength * collength, type: type) self.collength = collength self.rowlength = rowlength self.offset = 0 if major == .row { self.rowstride = 1 self.colstride = rowlength } else { self.colstride = 1 self.rowstride = collength } } public subscript(rowIndex: Int, colIndex: Int) -> Scalar { get { return self.block[self.offset + rowIndex * self.colstride + colIndex * self.rowstride] } set(value) { self.block[self.offset + rowIndex * self.colstride + colIndex * self.rowstride] = value } } public func row(_ row: Int) -> Vector { return Vector(block: self.block, offset: self.offset + row * self.colstride, stride: self.rowstride, length: self.rowlength) } public func col(_ col: Int) -> Vector { return Vector(block: self.block, offset: self.offset + col * self.rowstride, stride: self.colstride, length: self.collength) } public func diag(_ diag: Int) -> Vector { let i = (diag < 0) ? -diag : 0 // row index of origin let j = (diag > 0) ? diag : 0 // col index of origin let n_row = self.collength - i // # rows from origin to end let n_col = self.rowlength - j // # cols from origin to end return Vector( block: self.block, offset: self.offset + i * self.colstride + j * self.rowstride, stride: self.rowstride + self.colstride, length: (n_row < n_col) ? n_row : n_col); } public static func prod(_ left: Matrix, times right: Matrix, output: Matrix) { // left M by N, right N by P, output M by P let M = left.collength let N = left.rowlength let P = right.rowlength assert(N == right.collength && M == output.collength && P == output.rowlength, "Matrix size error") } public func string(format: String) -> String { var s = "" for i in 0..<self.collength { for j in 0..<self.rowlength { s.append(self[i,j].string(format: format) + " ") } s.append("\n") } return s } } <file_sep>/* Created by RJudd September 9, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_ccfftop_d_def.h,v 2.1 2009/12/26 19:19:48 judd Exp $ */ #include"vsip_fftattributes_d.h" #include"VI_fft_building_blocks_d.h" #include"VI_ccfftip_d.h" /*========================================================*/ void vsip_ccfftop_d(const vsip_fft_d *Offt, const vsip_cvview_d *x, const vsip_cvview_d *y) { vsip_fft_d Nfft = *Offt; vsip_fft_d *fft = &Nfft; vsip_cvcopy_d_d(x,y); fft->type = VSIP_CCFFTIP; VI_ccfftip_d(fft,y); } <file_sep>// // AppDelegate.swift // VectorInspector // // Created by <NAME> on 1/16/17. // Copyright © 2017 JVSIP. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var vectorExplorerControllerWindow: VectorExplorerControllerWindow? func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application let window = VectorExplorerControllerWindow() window.showWindow(self) self.vectorExplorerControllerWindow = window } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } } <file_sep>/* Created RJudd February 1, 2000*/ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mcminmgsqval_d.c,v 2.0 2003/02/22 15:18:54 judd Exp $ */ #include"vsip.h" #include"vsip_cmviewattributes_d.h" vsip_scalar_d (vsip_mcminmgsqval_d)( const vsip_cmview_d *a, vsip_scalar_mi *index) { { vsip_length n_mj, /* major length */ n_mn; /* minor length */ vsip_stride ast_mj, ast_mn; vsip_scalar_d *ap_r = (a->block->R->array) + a->offset * a->block->cstride; vsip_scalar_d *ap_i = (a->block->I->array) + a->offset * a->block->cstride; vsip_scalar_d *ap0_r = ap_r; vsip_scalar_d *ap0_i = ap_i; vsip_scalar_d mag = 0, retval = 0; vsip_index major_i = 0, minor_i = 0; vsip_length n0_mn, n0_mj; /* pick direction dependent on output */ if(a->row_stride < a->col_stride){ n_mj = a->row_length; n_mn = a->col_length; ast_mj = a->row_stride; ast_mn = a->col_stride; ast_mj *= a->block->cstride; ast_mn *= a->block->cstride; } else { n_mn = a->row_length; n_mj = a->col_length; ast_mn = a->row_stride; ast_mj = a->col_stride; ast_mn *= a->block->cstride; ast_mj *= a->block->cstride; } n0_mn = n_mn - 1; n0_mj = n_mj - 1; retval = *ap_r * *ap_r + *ap_i * *ap_i; /*end define*/ while(n_mn-- > 0){ vsip_length n = n_mj; while(n-- >0){ mag = *ap_r * *ap_r + *ap_i * *ap_i; if(retval > mag){ retval = mag; major_i = n0_mj - n; minor_i = n0_mn - n_mn; } ap_r += ast_mj; ap_i += ast_mj; } ap0_r += ast_mn; ap0_i += ast_mn; ap_r = ap0_r; ap_i = ap0_i; } if(index != NULL){ if(a->row_stride < a->col_stride){ index->r = minor_i; index->c = major_i; } else { index->r = major_i; index->c = minor_i; } } return retval; } } <file_sep>/* Created <NAME> 2, 2013 */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"svd.h" /* these functions return a 'bottom corner' of a matrix or vector */ static vsip_mview_f* msv_f( vsip_mview_f *B, vsip_mview_f *BS, vsip_index i,vsip_index j) { vsip_mattr_f attr; vsip_mgetattrib_f(B,&attr); attr.row_length -= j; attr.col_length -= i; attr.offset += j * attr.row_stride + i * attr.col_stride; vsip_mputattrib_f(BS,&attr); return BS; } static vsip_vview_f *vsv_f( vsip_vview_f *v, vsip_vview_f *vs, vsip_index i) { vsip_vattr_f attr; vsip_vgetattrib_f(v,&attr); attr.offset += i * attr.stride; attr.length -= i; vsip_vputattrib_f(vs,&attr); return vs; } static vsip_cmview_f* cmsv_f( vsip_cmview_f *B, vsip_cmview_f *BS, vsip_index i,vsip_index j) { vsip_cmattr_f attr; vsip_cmgetattrib_f(B,&attr); attr.row_length -= j; attr.col_length -= i; attr.offset += j * attr.row_stride + i * attr.col_stride; vsip_cmputattrib_f(BS,&attr); return BS; } static vsip_cvview_f *cvsv_f( vsip_cvview_f *v, vsip_cvview_f *vs, vsip_index i) { vsip_cvattr_f attr; vsip_cvgetattrib_f(v,&attr); attr.offset += i * attr.stride; attr.length -= i; vsip_cvputattrib_f(vs,&attr); return vs; } static vsip_mview_d* msv_d( vsip_mview_d *B, vsip_mview_d *BS, vsip_index i,vsip_index j) { vsip_mattr_d attr; vsip_mgetattrib_d(B,&attr); attr.row_length -= j; attr.col_length -= i; attr.offset += j * attr.row_stride + i * attr.col_stride; vsip_mputattrib_d(BS,&attr); return BS; } static vsip_vview_d *vsv_d( vsip_vview_d *v, vsip_vview_d *vs, vsip_index i) { vsip_vattr_d attr; vsip_vgetattrib_d(v,&attr); attr.offset += i * attr.stride; attr.length -= i; vsip_vputattrib_d(vs,&attr); return vs; } static vsip_cmview_d* cmsv_d(vsip_cmview_d *B,vsip_cmview_d *BS, vsip_index i,vsip_index j) { vsip_cmattr_d attr; vsip_cmgetattrib_d(B,&attr); attr.row_length -= j; attr.col_length -= i; attr.offset += j * attr.row_stride + i * attr.col_stride; vsip_cmputattrib_d(BS,&attr); return BS; } static vsip_cvview_d *cvsv_d(vsip_cvview_d *v,vsip_cvview_d *vs,vsip_index i) { vsip_cvattr_d attr; vsip_cvgetattrib_d(v,&attr); attr.offset += i * attr.stride; attr.length -= i; vsip_cvputattrib_d(vs,&attr); return vs; } /* these functions return a column or row of a matrix */ static vsip_cvview_f *ccol_sv_f(vsip_cmview_f*Am,vsip_cvview_f* vv,vsip_index col) { vsip_cmattr_f A; vsip_cvattr_f v; vsip_cmgetattrib_f(Am,&A); v.offset = A.offset + col * A.row_stride; v.stride = A.col_stride; v.length = A.col_length; vsip_cvputattrib_f(vv,&v); return vv; } static vsip_cvview_f *crow_sv_f(vsip_cmview_f*Am,vsip_cvview_f* vv,vsip_index row) { vsip_cmattr_f A; vsip_cvattr_f v; vsip_cmgetattrib_f(Am,&A); v.offset = A.offset + row * A.col_stride; v.stride = A.row_stride; v.length = A.row_length; vsip_cvputattrib_f(vv,&v); return vv; } static vsip_vview_f *col_sv_f(vsip_mview_f*Am,vsip_vview_f* vv,vsip_index col) { vsip_mattr_f A; vsip_vattr_f v; vsip_mgetattrib_f(Am,&A); v.offset = A.offset + col * A.row_stride; v.stride = A.col_stride; v.length = A.col_length; vsip_vputattrib_f(vv,&v); return vv; } static vsip_vview_f *row_sv_f(vsip_mview_f*Am,vsip_vview_f* vv,vsip_index row) { vsip_mattr_f A; vsip_vattr_f v; vsip_mgetattrib_f(Am,&A); v.offset = A.offset + row * A.col_stride; v.stride = A.row_stride; v.length = A.row_length; vsip_vputattrib_f(vv,&v); return vv; } static vsip_vview_d *col_sv_d(vsip_mview_d*Am,vsip_vview_d* vv,vsip_index col) { vsip_mattr_d A; vsip_vattr_d v; vsip_mgetattrib_d(Am,&A); v.offset = A.offset + col * A.row_stride; v.stride = A.col_stride; v.length = A.col_length; vsip_vputattrib_d(vv,&v); return vv; } static vsip_vview_d *row_sv_d(vsip_mview_d*Am,vsip_vview_d* vv,vsip_index row) { vsip_mattr_d A; vsip_vattr_d v; vsip_mgetattrib_d(Am,&A); v.offset = A.offset + row * A.col_stride; v.stride = A.row_stride; v.length = A.row_length; vsip_vputattrib_d(vv,&v); return vv; } static vsip_cvview_d *ccol_sv_d(vsip_cmview_d*Am,vsip_cvview_d* vv,vsip_index col) { vsip_cmattr_d A; vsip_cvattr_d v; vsip_cmgetattrib_d(Am,&A); v.offset = A.offset + col * A.row_stride; v.stride = A.col_stride; v.length = A.col_length; vsip_cvputattrib_d(vv,&v); return vv; } static vsip_cvview_d *crow_sv_d(vsip_cmview_d*Am,vsip_cvview_d* vv,vsip_index row) { vsip_cmattr_d A; vsip_cvattr_d v; vsip_cmgetattrib_d(Am,&A); v.offset = A.offset + row * A.col_stride; v.stride = A.row_stride; v.length = A.row_length; vsip_cvputattrib_d(vv,&v); return vv; } /* these functions return an interior subview of a matrix or vector */ /* note the first index is a corner and the second index is a length (the same as a slice) */ /* for example imsv_f(B,BS,i1,j1,i2,j2) returns a view equivalent to B[i1:j1,i2:j2]; */ /* a view equivalent to B[:,i2:j2] is imsv_f(B,BS,0,0,i2,j2) */ /* a view equivalent to B[i1:j1,:] is imsv_f(B,BS,i1,j1,0,0) */ /* a view equivalent to B[i1:j1,i2:] is imsv_f(B,BS,i1,j1,i2,0) */ static vsip_mview_f* imsv_f( vsip_mview_f *B, vsip_mview_f *BS, vsip_index i1,vsip_index j1, vsip_index i2, vsip_index j2) { vsip_mattr_f attr; vsip_mgetattrib_f(B,&attr); if(j1 == 0) j1 =attr.col_length; if(j2 == 0) j2 =attr.row_length; attr.col_length = (j1 - i1); attr.row_length = (j2 - i2); attr.offset += i2 * attr.row_stride + i1 * attr.col_stride; vsip_mputattrib_f(BS,&attr); return BS; } static vsip_vview_f *ivsv_f( vsip_vview_f *v, vsip_vview_f *vs, vsip_index i,vsip_index j) { vsip_vattr_f attr; vsip_vgetattrib_f(v,&attr); if(j==0) j=attr.length; attr.offset += i * attr.stride; attr.length = j-i; vsip_vputattrib_f(vs,&attr); return vs; } static vsip_cmview_f* cimsv_f( vsip_cmview_f *B, vsip_cmview_f *BS, vsip_index i1,vsip_index j1, vsip_index i2, vsip_index j2) { vsip_cmattr_f attr; vsip_cmgetattrib_f(B,&attr); if(j1 == 0) j1 =attr.col_length; if(j2 == 0) j2 =attr.row_length; attr.col_length = (j1 - i1); attr.row_length = (j2 - i2); attr.offset += i2 * attr.row_stride + i1 * attr.col_stride; vsip_cmputattrib_f(BS,&attr); return BS; } static vsip_mview_d* imsv_d( vsip_mview_d *B, vsip_mview_d *BS, vsip_index i1,vsip_index j1, vsip_index i2, vsip_index j2) { vsip_mattr_d attr; vsip_mgetattrib_d(B,&attr); if(j1 == 0) j1 =attr.col_length; if(j2 == 0) j2 =attr.row_length; attr.col_length = (j1 - i1); attr.row_length = (j2 - i2); attr.offset += i2 * attr.row_stride + i1 * attr.col_stride; vsip_mputattrib_d(BS,&attr); return BS; } static vsip_vview_d *ivsv_d( vsip_vview_d *v, vsip_vview_d *vs, vsip_index i, vsip_index j) { vsip_vattr_d attr; vsip_vgetattrib_d(v,&attr); if(j==0) j=attr.length; attr.offset += i * attr.stride; attr.length = j-i; vsip_vputattrib_d(vs,&attr); return vs; } static vsip_cmview_d* cimsv_d( vsip_cmview_d *B, vsip_cmview_d *BS, vsip_index i1,vsip_index j1, vsip_index i2, vsip_index j2) { vsip_cmattr_d attr; vsip_cmgetattrib_d(B,&attr); if(j1 == 0) j1 =attr.col_length; if(j2 == 0) j2 =attr.row_length; attr.col_length = (j1 - i1); attr.row_length = (j2 - i2); attr.offset += i2 * attr.row_stride + i1 * attr.col_stride; vsip_cmputattrib_d(BS,&attr); return BS; } /* these functions create a new data space and copy the input into it */ static vsip_cmview_d* cmclone_d(vsip_cmview_d*A){ vsip_cmview_d *B = vsip_cmcreate_d( vsip_cmgetcollength_d(A), vsip_cmgetrowlength_d(A), VSIP_ROW,VSIP_MEM_NONE); if(B) vsip_cmcopy_d_d(A,B); return B; } static vsip_cvview_d* cvclone_d(vsip_cvview_d*x){ vsip_cvview_d *v = vsip_cvcreate_d( vsip_cvgetlength_d(x), VSIP_MEM_NONE); if(v) vsip_cvcopy_d_d(x,v); return v; } static vsip_mview_d* mclone_d(vsip_mview_d*A){ vsip_mview_d *B = vsip_mcreate_d( vsip_mgetcollength_d(A), vsip_mgetrowlength_d(A), VSIP_ROW,VSIP_MEM_NONE); if(B) vsip_mcopy_d_d(A,B); return B; } static vsip_vview_d* vclone_d(vsip_vview_d*x){ vsip_vview_d *v = vsip_vcreate_d( vsip_vgetlength_d(x), VSIP_MEM_NONE); if(v) vsip_vcopy_d_d(x,v); return v; } static vsip_cmview_f* cmclone_f(vsip_cmview_f*A){ vsip_cmview_f *B = vsip_cmcreate_f( vsip_cmgetcollength_f(A), vsip_cmgetrowlength_f(A), VSIP_ROW,VSIP_MEM_NONE); if(B) vsip_cmcopy_f_f(A,B); return B; } static vsip_cvview_f* cvclone_f(vsip_cvview_f*x){ vsip_cvview_f *v = vsip_cvcreate_f( vsip_cvgetlength_f(x), VSIP_MEM_NONE); if(v) vsip_cvcopy_f_f(x,v); return v; } static vsip_mview_f* mclone_f(vsip_mview_f*A){ vsip_mview_f *B = vsip_mcreate_f( vsip_mgetcollength_f(A), vsip_mgetrowlength_f(A), VSIP_ROW,VSIP_MEM_NONE); if(B) vsip_mcopy_f_f(A,B); return B; } static vsip_vview_f* vclone_f(vsip_vview_f*x){ vsip_vview_f *v = vsip_vcreate_f( vsip_vgetlength_f(x), VSIP_MEM_NONE); if(v) vsip_vcopy_f_f(x,v); return v; } /* convenienc functions for creating identity matrices */ static vsip_mview_f* meye_f(vsip_length n){ vsip_vview_f *d = (vsip_vview_f*) NULL; vsip_mview_f *retval = (vsip_mview_f*)NULL; retval = vsip_mcreate_f(n,n,VSIP_ROW,VSIP_MEM_NONE); if(retval) d = vsip_mdiagview_f(retval,0); if(d){ vsip_mfill_f(0.0,retval); vsip_vfill_f(1.0,d); vsip_vdestroy_f(d); } else { vsip_malldestroy_f(retval); retval = (vsip_mview_f*) NULL; } return retval; } static vsip_cmview_f* cmeye_f(vsip_length n){ vsip_cvview_f *d = (vsip_cvview_f*) NULL; vsip_cmview_f *retval = (vsip_cmview_f*)NULL; retval = vsip_cmcreate_f(n,n,VSIP_ROW,VSIP_MEM_NONE); if(retval) d = vsip_cmdiagview_f(retval,0); if(d){ vsip_cmfill_f(vsip_cmplx_f(0.0,0.0),retval); vsip_cvfill_f(vsip_cmplx_f(1.0,0.0),d); vsip_cvdestroy_f(d); } else { vsip_cmalldestroy_f(retval); retval = (vsip_cmview_f*) NULL; } return retval; } static vsip_mview_d* meye_d(vsip_length n){ vsip_vview_d *d = (vsip_vview_d*) NULL; vsip_mview_d *retval = (vsip_mview_d*)NULL; retval = vsip_mcreate_d(n,n,VSIP_ROW,VSIP_MEM_NONE); if(retval) d = vsip_mdiagview_d(retval,0); if(d){ vsip_mfill_d(0.0,retval); vsip_vfill_d(1.0,d); vsip_vdestroy_d(d); } else { vsip_malldestroy_d(retval); retval = (vsip_mview_d*) NULL; } return retval; } static vsip_cmview_d* cmeye_d(vsip_length n){ vsip_cvview_d *d = (vsip_cvview_d*) NULL; vsip_cmview_d *retval = (vsip_cmview_d*)NULL; retval = vsip_cmcreate_d(n,n,VSIP_ROW,VSIP_MEM_NONE); if(retval) d = vsip_cmdiagview_d(retval,0); if(d){ vsip_cmfill_d(vsip_cmplx_d(0.0,0.0),retval); vsip_cvfill_d(vsip_cmplx_d(1.0,0.0),d); vsip_cvdestroy_d(d); } else { vsip_cmalldestroy_d(retval); retval = (vsip_cmview_d*) NULL; } return retval; } /* sign function as defined in http://www.netlib.org/lapack/lawnspdf/lawn148.pdf */ static vsip_scalar_f sign_f(vsip_scalar_f a_in){ if(a_in < 0.0) return -1.0; else return 1.0; } static vsip_cscalar_f csign_f(vsip_cscalar_f a_in){ vsip_scalar_f re = a_in.r; vsip_scalar_f im = a_in.i; vsip_scalar_f t=vsip_hypot_f(re,im); vsip_cscalar_f retval; retval.r=0.0; retval.i = 0.0; if(t == 0.0){ retval.r = 1.0; return retval; } else if (im==0.0) { retval.r = sign_f(re); return retval; } else { retval.r = re/t; retval.i = im/t; return retval; } } static vsip_scalar_d sign_d(vsip_scalar_d a_in){ if(a_in < 0.0) return -1.0; else return 1.0; } static vsip_cscalar_d csign_d(vsip_cscalar_d a_in){ vsip_scalar_d re = a_in.r; vsip_scalar_d im = a_in.i; vsip_scalar_d t=vsip_hypot_d(re,im); vsip_cscalar_d retval; retval.r=0.0; retval.i = 0.0; if(t == 0.0){ retval.r = 1.0; return retval; } else if (im==0.0){ retval.r = sign_d(re); return retval; } else { retval.r = re/t; retval.i = im/t; return retval; } } static vsip_scalar_f vnormFro_f(vsip_vview_f *v){ return vsip_sqrt_f(vsip_vsumsqval_f(v)); } static vsip_scalar_f vnorm2_f(vsip_vview_f *v){ return vnormFro_f(v); } static vsip_scalar_f cvnorm2_f(vsip_cvview_f *v){ return vsip_sqrt_f(vsip_cvjdot_f(v,v).r); } static vsip_scalar_d vnormFro_d(vsip_vview_d *v){ return vsip_sqrt_d(vsip_vsumsqval_d(v)); } static vsip_scalar_d vnorm2_d(vsip_vview_d *v){ return vnormFro_d(v); } static vsip_scalar_d cvnorm2_d(vsip_cvview_d *v){ return vsip_sqrt_d(vsip_cvjdot_d(v,v).r); } static vsip_scalar_f mnormFro_f(vsip_mview_f *v){ return vsip_sqrt_f(vsip_msumsqval_f(v)); } static vsip_scalar_d mnormFro_d(vsip_mview_d *v){ return vsip_sqrt_d(vsip_msumsqval_d(v)); } static vsip_scalar_f cmnormFro_f(vsip_cmview_f *v){ vsip_mview_f* re=vsip_mrealview_f(v); vsip_mview_f* im=vsip_mimagview_f(v); return vsip_sqrt_f(vsip_msumsqval_f(re)+vsip_msumsqval_f(im)); vsip_mdestroy_f(re);vsip_mdestroy_f(im); } static vsip_scalar_d cmnormFro_d(vsip_cmview_d *v){ vsip_mview_d* re=vsip_mrealview_d(v); vsip_mview_d* im=vsip_mimagview_d(v); return vsip_sqrt_d(vsip_msumsqval_d(re)+vsip_msumsqval_d(im)); vsip_mdestroy_d(re);vsip_mdestroy_d(im); } static void gtProd_f(vsip_index i, vsip_index j, vsip_scalar_f c,vsip_scalar_f s, vsip_mview_f* R) { vsip_vview_f *a1= vsip_mrowview_f(R,i); vsip_vview_f *a2= vsip_mrowview_f(R,j); vsip_vview_f *a1c=vclone_f(a1); vsip_svmul_f(c,a1c,a1); vsip_vsma_f(a2,s,a1,a1); vsip_svmul_f(-s,a1c,a1c); vsip_vsma_f(a2,c,a1c,a2); vsip_vdestroy_f(a1);vsip_vdestroy_f(a2); vsip_valldestroy_f(a1c); } static void gtProd_d(vsip_index i, vsip_index j,vsip_scalar_d c, vsip_scalar_d s,vsip_mview_d*R) { vsip_vview_d *a1= vsip_mrowview_d(R,i); vsip_vview_d *a2= vsip_mrowview_d(R,j); vsip_vview_d *a1c=vclone_d(a1); vsip_vview_d *a2c=vclone_d(a2); vsip_svmul_d(c,a1c,a1); vsip_vsma_d(a2c,s,a1,a1); vsip_svmul_d(c,a2c,a2); vsip_vsma_d(a1c,-s,a2,a2); vsip_vdestroy_d(a1);vsip_vdestroy_d(a2); vsip_valldestroy_d(a1c); vsip_valldestroy_d(a2c); } static void cgtProd_f(vsip_index i, vsip_index j,vsip_scalar_f c, vsip_scalar_f s,vsip_cmview_f*R) { vsip_cvview_f *a1= vsip_cmrowview_f(R,i); vsip_cvview_f *a2= vsip_cmrowview_f(R,j); vsip_cvview_f *a1c=cvclone_f(a1); vsip_cvview_f *a2c=cvclone_f(a2); vsip_rscvmul_f(c,a1c,a1); vsip_rscvmul_f(c,a2c,a2); vsip_rscvmul_f(s,a2c,a2c); vsip_rscvmul_f(-s,a1c,a1c); vsip_cvadd_f(a1,a2c,a1); vsip_cvadd_f(a2,a1c,a2); vsip_cvdestroy_f(a1);vsip_cvdestroy_f(a2); vsip_cvalldestroy_f(a1c); vsip_cvalldestroy_f(a2c); } static void cgtProd_d(vsip_index i, vsip_index j,vsip_scalar_d c, vsip_scalar_d s,vsip_cmview_d*R) { vsip_cvview_d *a1= vsip_cmrowview_d(R,i); vsip_cvview_d *a2= vsip_cmrowview_d(R,j); vsip_cvview_d *a1c=cvclone_d(a1); vsip_cvview_d *a2c=cvclone_d(a2); vsip_rscvmul_d(c,a1c,a1); vsip_rscvmul_d(c,a2c,a2); vsip_rscvmul_d(s,a2c,a2c); vsip_rscvmul_d(-s,a1c,a1c); vsip_cvadd_d(a1,a2c,a1); vsip_cvadd_d(a2,a1c,a2); vsip_cvdestroy_d(a1);vsip_cvdestroy_d(a2); vsip_cvalldestroy_d(a1c); vsip_cvalldestroy_d(a2c); } static void prodG_f(vsip_mview_f* L,vsip_index i, vsip_index j,vsip_scalar_f c, vsip_scalar_f s) { vsip_vview_f *a1= vsip_mcolview_f(L,i); vsip_vview_f *a2= vsip_mcolview_f(L,j); vsip_vview_f *a1c=vclone_f(a1); vsip_svmul_f(c,a1c,a1); vsip_vsma_f(a2,s,a1,a1); vsip_svmul_f(-s,a1c,a1c);vsip_vsma_f(a2,c,a1c,a2); vsip_vdestroy_f(a1);vsip_vdestroy_f(a2); vsip_valldestroy_f(a1c); } static void prodG_d(vsip_mview_d* L,vsip_index i, vsip_index j,vsip_scalar_d c, vsip_scalar_d s) { vsip_vview_d *a1= vsip_mcolview_d(L,i); vsip_vview_d *a2= vsip_mcolview_d(L,j); vsip_vview_d *a1c=vclone_d(a1); vsip_vview_d *a2c=vclone_d(a2); vsip_svmul_d(c,a1c,a1); vsip_vsma_d(a2,s,a1,a1); vsip_svmul_d(c,a2c,a2); vsip_vsma_d(a1c,-s,a2,a2); vsip_vdestroy_d(a1);vsip_vdestroy_d(a2); vsip_valldestroy_d(a1c); vsip_valldestroy_d(a2c); } static void cprodG_f(vsip_cmview_f* L,vsip_index i, vsip_index j,vsip_scalar_f c, vsip_scalar_f s) { vsip_cvview_f *a1= vsip_cmcolview_f(L,i); vsip_cvview_f *a2= vsip_cmcolview_f(L,j); vsip_cvview_f *a1c=cvclone_f(a1); vsip_cvview_f *a2c=cvclone_f(a2); vsip_rscvmul_f(c,a1c,a1); vsip_rscvmul_f(-s,a1c,a1c); vsip_rscvmul_f(c,a2c,a2); vsip_rscvmul_f(s,a2c,a2c); vsip_cvadd_f(a1,a2c,a1); vsip_cvadd_f(a2,a1c,a2); vsip_cvdestroy_f(a1);vsip_cvdestroy_f(a2); vsip_cvalldestroy_f(a1c); vsip_cvalldestroy_f(a2c); } static void cprodG_d(vsip_cmview_d* L,vsip_index i, vsip_index j,vsip_scalar_d c, vsip_scalar_d s) { vsip_cvview_d *a1= vsip_cmcolview_d(L,i); vsip_cvview_d *a2= vsip_cmcolview_d(L,j); vsip_cvview_d *a1c=cvclone_d(a1); vsip_cvview_d *a2c=cvclone_d(a2); vsip_rscvmul_d(c,a1c,a1); vsip_rscvmul_d(-s,a1c,a1c); vsip_rscvmul_d(c,a2c,a2); vsip_rscvmul_d(s,a2c,a2c); vsip_cvadd_d(a1,a2c,a1); vsip_cvadd_d(a2,a1c,a2); vsip_cvdestroy_d(a1);vsip_cvdestroy_d(a2); vsip_cvalldestroy_d(a1c); vsip_cvalldestroy_d(a2c); } static vsip_vview_f *houseVector_f(vsip_vview_f* x){ vsip_scalar_f nrm=vnorm2_f(x); vsip_scalar_f t = vsip_vget_f(x,0); vsip_scalar_f s = t + sign_f(t) * nrm; vsip_vput_f(x,0,s); nrm = vnorm2_f(x); if (nrm == 0.0) vsip_vput_f(x,0,1.0); else vsip_svmul_f(1.0/nrm,x,x); return x; } void prodHouse_f(vsip_mview_f *A, vsip_vview_f *v){ vsip_mattr_f a_atr; vsip_vview_f *w; vsip_mview_f *B; vsip_mgetattrib_f(A,&a_atr); B=vsip_mcreate_f(a_atr.col_length,a_atr.row_length,VSIP_ROW,VSIP_MEM_NONE); w = vsip_vcreate_f(a_atr.col_length,VSIP_MEM_NONE); vsip_scalar_f beta = 2.0/vsip_vdot_f(v,v); vsip_mvprod_f(A,v,w); vsip_vouter_f(beta,w,v,B); vsip_msub_f(A,B,A); vsip_valldestroy_f(w); vsip_malldestroy_f(B); } void houseProd_f(vsip_vview_f *v, vsip_mview_f *A){ vsip_mattr_f a_atr; vsip_vview_f *w; vsip_mview_f *B; vsip_mgetattrib_f(A,&a_atr); B=vsip_mcreate_f(a_atr.col_length,a_atr.row_length,VSIP_ROW,VSIP_MEM_NONE); w = vsip_vcreate_f(a_atr.row_length,VSIP_MEM_NONE); vsip_scalar_f beta = 2.0/vsip_vdot_f(v,v); vsip_vmprod_f(v,A,w); vsip_vouter_f(beta,v,w,B); vsip_msub_f(A,B,A); vsip_valldestroy_f(w); vsip_malldestroy_f(B); } static vsip_cvview_f *chouseVector_f(vsip_cvview_f* x){ vsip_cscalar_f t = vsip_cvget_f(x,0); /*x[0]*/ vsip_scalar_f nrm=cvnorm2_f(x); /* x.norm2 */ vsip_cscalar_f s = vsip_cadd_f(t, vsip_cmul_f(csign_f(t), vsip_cmplx_f(nrm, 0.0))); vsip_cvput_f(x,0,s); nrm = cvnorm2_f(x); if (nrm == 0.0) vsip_cvput_f(x,0,vsip_cmplx_f(1.0,0.0)); else vsip_rscvmul_f(1.0/nrm,x,x); return x; } void chouseProd_f(vsip_cvview_f *v, vsip_cmview_f *A){ vsip_cmattr_f a_atr; vsip_cvview_f *w; vsip_cmview_f *B; vsip_scalar_f beta = 2.0/vsip_cvjdot_f(v,v).r; vsip_cmgetattrib_f(A,&a_atr); B=vsip_cmcreate_f(a_atr.col_length,a_atr.row_length,VSIP_ROW,VSIP_MEM_NONE); w = vsip_cvcreate_f(a_atr.row_length,VSIP_MEM_NONE); vsip_cvconj_f(v,v); vsip_cvmprod_f(v,A,w);vsip_cvconj_f(w,w); vsip_cvconj_f(v,v); vsip_cvouter_f(vsip_cmplx_f(beta,0.0),v,w,B); vsip_cmsub_f(A,B,A); vsip_cvalldestroy_f(w); vsip_cmalldestroy_f(B); } void cprodHouse_f(vsip_cmview_f *A, vsip_cvview_f *v){ vsip_cmattr_f a_atr; vsip_cvview_f *w; vsip_cmview_f *B; vsip_scalar_f beta = 2.0/vsip_cvjdot_f(v,v).r; vsip_cmgetattrib_f(A,&a_atr); B=vsip_cmcreate_f(a_atr.col_length,a_atr.row_length,VSIP_ROW,VSIP_MEM_NONE); w = vsip_cvcreate_f(a_atr.col_length,VSIP_MEM_NONE); vsip_cmvprod_f(A,v,w); vsip_cvouter_f(vsip_cmplx_f(beta,0.0),w,v,B); vsip_cmsub_f(A,B,A); vsip_cvalldestroy_f(w); vsip_cmalldestroy_f(B); } static vsip_vview_d *houseVector_d(vsip_vview_d* x){ vsip_scalar_d nrm=vnorm2_d(x); vsip_scalar_d t = vsip_vget_d(x,0); vsip_scalar_d s = t + sign_d(t) * nrm; vsip_vput_d(x,0,s); nrm = vnorm2_d(x); if (nrm == 0.0) vsip_vput_d(x,0,1.0); else vsip_svmul_d(1.0/nrm,x,x); return x; } void houseProd_d(vsip_vview_d *v, vsip_mview_d *A){ vsip_mattr_d a_atr; vsip_vview_d *w; vsip_mview_d *B; vsip_mgetattrib_d(A,&a_atr); B=vsip_mcreate_d(a_atr.col_length,a_atr.row_length,VSIP_ROW,VSIP_MEM_NONE); w = vsip_vcreate_d(a_atr.row_length,VSIP_MEM_NONE); vsip_scalar_d beta = 2.0/vsip_vdot_d(v,v); vsip_vmprod_d(v,A,w); vsip_vouter_d(beta,v,w,B); vsip_msub_d(A,B,A); vsip_valldestroy_d(w); vsip_malldestroy_d(B); } void prodHouse_d(vsip_mview_d *A, vsip_vview_d *v){ vsip_mattr_d a_atr; vsip_vview_d *w; vsip_mview_d *B; vsip_mgetattrib_d(A,&a_atr); B=vsip_mcreate_d(a_atr.col_length,a_atr.row_length,VSIP_ROW,VSIP_MEM_NONE); w = vsip_vcreate_d(a_atr.col_length,VSIP_MEM_NONE); vsip_scalar_d beta = 2.0/vsip_vdot_d(v,v); vsip_mvprod_d(A,v,w); vsip_vouter_d(beta,w,v,B); vsip_msub_d(A,B,A); vsip_valldestroy_d(w); vsip_malldestroy_d(B); } static vsip_cvview_d* chouseVector_d(vsip_cvview_d* x){ vsip_cscalar_d t = vsip_cvget_d(x,0); /*x[0]*/ vsip_scalar_d nrm=cvnorm2_d(x); /* x.norm2 */ vsip_cscalar_d s = vsip_cadd_d(t, vsip_cmul_d(csign_d(t), vsip_cmplx_d(nrm, 0.0))); vsip_cvput_d(x,0,s); nrm = cvnorm2_d(x); if (nrm == 0.0) vsip_cvput_d(x,0,vsip_cmplx_d(1.0,0.0)); else vsip_rscvmul_d(1.0/nrm,x,x); return x; } void chouseProd_d(vsip_cvview_d *v, vsip_cmview_d *A){ vsip_cmattr_d a_atr; vsip_cvview_d *w; vsip_cmview_d *B; vsip_scalar_d beta = 2.0/vsip_cvjdot_d(v,v).r; vsip_cmgetattrib_d(A,&a_atr); B=vsip_cmcreate_d(a_atr.col_length,a_atr.row_length,VSIP_ROW,VSIP_MEM_NONE); w = vsip_cvcreate_d(a_atr.row_length,VSIP_MEM_NONE); vsip_cvconj_d(v,v); vsip_cvmprod_d(v,A,w);vsip_cvconj_d(w,w); vsip_cvconj_d(v,v); vsip_cvouter_d(vsip_cmplx_d(beta,0.0),v,w,B); vsip_cmsub_d(A,B,A); vsip_cvalldestroy_d(w); vsip_cmalldestroy_d(B); } void cprodHouse_d(vsip_cmview_d *A, vsip_cvview_d *v){ vsip_cmattr_d a_atr; vsip_cvview_d *w; vsip_cmview_d *B; vsip_scalar_d beta = 2.0/vsip_cvjdot_d(v,v).r; vsip_cmgetattrib_d(A,&a_atr); B=vsip_cmcreate_d(a_atr.col_length,a_atr.row_length,VSIP_ROW,VSIP_MEM_NONE); w = vsip_cvcreate_d(a_atr.col_length,VSIP_MEM_NONE); vsip_cmvprod_d(A,v,w); vsip_cvouter_d(vsip_cmplx_d(beta,0.0),w,v,B); vsip_cmsub_d(A,B,A); vsip_cvalldestroy_d(w); vsip_cmalldestroy_d(B); } static vsip_mview_f *bidiag_f( vsip_mview_f *A){ vsip_length m = vsip_mgetcollength_f(A); vsip_length n = vsip_mgetrowlength_f(A); vsip_mview_f *B = mclone_f(A); vsip_mview_f *Bs= vsip_mcloneview_f(B); vsip_vview_f *x=vsip_mcolview_f(B,0); vsip_vview_f *v=vclone_f(x); vsip_vview_f *vs = vsip_vcloneview_f(v); vsip_index i,j; for(i=0; i<n-1; i++){ /* x=B[i:,i:].colview(0); v=houseVector(x); v/=v[0]*/ vsip_vputlength_f(v,m-i); vsip_vcopy_f_f(col_sv_f(msv_f(B,Bs,i,i),x,0),v); houseVector_f(v); vsip_svmul_f(1.0/vsip_vget_f(v,0),v,v); /* houseProd(v,B[i:,i:]) */ houseProd_f(v,Bs); /* x[1:]=v[1:] */ vsip_vcopy_f_f(vsv_f(v,vs,1),vsv_f(x,x,1)); if(i < n-2){ j = i+1; vsip_vputlength_f(v,n-j); vsip_vcopy_f_f(row_sv_f(msv_f(B,Bs,i,j),x,0),v); houseVector_f(v); vsip_svmul_f(1.0/vsip_vget_f(v,0),v,v); prodHouse_f(Bs,v); vsip_vcopy_f_f(vsv_f(v,vs,1),vsv_f(x,x,1)); } } if(m > n){ i=n-1; vsip_vputlength_f(v,m-i); vsip_vcopy_f_f(col_sv_f(msv_f(B,Bs,i,i),x,0),v); houseVector_f(v); vsip_svmul_f(1.0/vsip_vget_f(v,0),v,v); houseProd_f(v,Bs); vsip_vcopy_f_f(vsv_f(v,vs,1),vsv_f(x,x,1)); } vsip_vdestroy_f(vs); vsip_valldestroy_f(v); vsip_vdestroy_f(x); vsip_mdestroy_f(Bs); return B; } static vsip_cmview_f *cbidiag_f( vsip_cmview_f *A){ vsip_length m = vsip_cmgetcollength_f(A); vsip_length n = vsip_cmgetrowlength_f(A); vsip_cmview_f *B = cmclone_f(A); vsip_cmview_f *Bs= vsip_cmcloneview_f(B); vsip_cvview_f *x=vsip_cmcolview_f(B,0); vsip_cvview_f *v=cvclone_f(x); vsip_cvview_f *vs = vsip_cvcloneview_f(v); vsip_index i,j; for(i=0; i<n-1; i++){ vsip_cvputlength_f(v,m-i); vsip_cvcopy_f_f(ccol_sv_f(cmsv_f(B,Bs,i,i),x,0),v); chouseVector_f(v); vsip_csvmul_f(vsip_cdiv_f(vsip_cmplx_f(1.0,0.0),vsip_cvget_f(v,0)),v,v); chouseProd_f(v,Bs); vsip_cvcopy_f_f(cvsv_f(v,vs,1),cvsv_f(x,x,1)); if(i < n-2){ j = i+1; vsip_cvputlength_f(v,n-j); vsip_cvcopy_f_f(crow_sv_f(cmsv_f(B,Bs,i,j),x,0),v); chouseVector_f(v);vsip_cvconj_f(v,v); vsip_csvmul_f(vsip_cdiv_f(vsip_cmplx_f(1.0,0.0),vsip_cvget_f(v,0)),v,v); cprodHouse_f(Bs,v); vsip_cvcopy_f_f(cvsv_f(v,vs,1),cvsv_f(x,x,1)); } } if(m > n){ i=n-1; vsip_cvputlength_f(v,m-i); vsip_cvcopy_f_f(ccol_sv_f(cmsv_f(B,Bs,i,i),x,0),v); chouseVector_f(v); vsip_csvmul_f(vsip_cdiv_f(vsip_cmplx_f(1.0,0.0),vsip_cvget_f(v,0)),v,v); chouseProd_f(v,Bs); vsip_cvcopy_f_f(cvsv_f(v,vs,1),cvsv_f(x,x,1)); } vsip_cvdestroy_f(vs); vsip_cvalldestroy_f(v); vsip_cvdestroy_f(x); vsip_cmdestroy_f(Bs); return B; } static vsip_mview_d *bidiag_d(vsip_mview_d *A){ vsip_length m = vsip_mgetcollength_d(A); vsip_length n = vsip_mgetrowlength_d(A); vsip_mview_d *B = mclone_d(A); vsip_mview_d *Bs= vsip_mcloneview_d(B); vsip_vview_d *x=vsip_mcolview_d(B,0); vsip_vview_d *v=vclone_d(x); vsip_vview_d *vs = vsip_vcloneview_d(v); vsip_index i,j; for(i=0; i<n-1; i++){ vsip_vputlength_d(v,m-i); vsip_vcopy_d_d(col_sv_d(msv_d(B,Bs,i,i),x,0),v); houseVector_d(v); vsip_svmul_d(1.0/vsip_vget_d(v,0),v,v); houseProd_d(v,Bs); vsip_vcopy_d_d(vsv_d(v,vs,1),vsv_d(x,x,1)); if(i < n-2){ j = i+1; vsip_vputlength_d(v,n-j); vsip_vcopy_d_d(row_sv_d(msv_d(B,Bs,i,j),x,0),v); houseVector_d(v); vsip_svmul_d(1.0/vsip_vget_d(v,0),v,v); prodHouse_d(Bs,v); vsip_vcopy_d_d(vsv_d(v,vs,1),vsv_d(x,x,1)); } } if(m > n){ i=n-1; vsip_vputlength_d(v,m-i); vsip_vcopy_d_d(col_sv_d(msv_d(B,Bs,i,i),x,0),v); houseVector_d(v); vsip_svmul_d(1.0/vsip_vget_d(v,0),v,v); houseProd_d(v,Bs); vsip_vcopy_d_d(vsv_d(v,vs,1),vsv_d(x,x,1)); } vsip_vdestroy_d(vs); vsip_valldestroy_d(v); vsip_vdestroy_d(x); vsip_mdestroy_d(Bs); return B; } static vsip_cmview_d *cbidiag_d( vsip_cmview_d *A){ vsip_length m = vsip_cmgetcollength_d(A); vsip_length n = vsip_cmgetrowlength_d(A); vsip_cmview_d *B = cmclone_d(A); vsip_cmview_d *Bs= vsip_cmcloneview_d(B); vsip_cvview_d *x=vsip_cmcolview_d(B,0); vsip_cvview_d *v=cvclone_d(x); vsip_cvview_d *vs = vsip_cvcloneview_d(v); vsip_index i,j; for(i=0; i<n-1; i++){ vsip_cvputlength_d(v,m-i); vsip_cvcopy_d_d(ccol_sv_d(cmsv_d(B,Bs,i,i),x,0),v); chouseVector_d(v); vsip_csvmul_d(vsip_cdiv_d(vsip_cmplx_d(1.0,0.0),vsip_cvget_d(v,0)),v,v); chouseProd_d(v,Bs); vsip_cvcopy_d_d(cvsv_d(v,vs,1),cvsv_d(x,x,1)); if(i < n-2){ j = i+1; vsip_cvputlength_d(v,n-j); vsip_cvcopy_d_d(crow_sv_d(cmsv_d(B,Bs,i,j),x,0),v); chouseVector_d(v);vsip_cvconj_d(v,v); vsip_csvmul_d(vsip_cdiv_d(vsip_cmplx_d(1.0,0.0),vsip_cvget_d(v,0)),v,v); cprodHouse_d(Bs,v); vsip_cvcopy_d_d(cvsv_d(v,vs,1),cvsv_d(x,x,1)); } } if(m > n){ i=n-1; vsip_cvputlength_d(v,m-i); vsip_cvcopy_d_d(ccol_sv_d(cmsv_d(B,Bs,i,i),x,0),v); chouseVector_d(v); vsip_csvmul_d(vsip_cdiv_d(vsip_cmplx_d(1.0,0.0),vsip_cvget_d(v,0)),v,v); chouseProd_d(v,Bs); vsip_cvcopy_d_d(cvsv_d(v,vs,1),cvsv_d(x,x,1)); } vsip_cvdestroy_d(vs); vsip_cvalldestroy_d(v); vsip_cvdestroy_d(x); vsip_cmdestroy_d(Bs); return B; } static vsip_mview_f *UmatExtract_f(vsip_mview_f*B){ vsip_stride i; vsip_length m = vsip_mgetcollength_f(B); vsip_length n = vsip_mgetrowlength_f(B); vsip_mview_f *U=meye_f(m); vsip_mview_f *Bs, *Us; vsip_vview_f *v; vsip_scalar_f t; v = vsip_mcolview_f(B,0); Bs=vsip_mcloneview_f(B); Us=vsip_mcloneview_f(U); if (m > n){ i=n-1; col_sv_f(msv_f(B,Bs,i,i),v,0); t=vsip_vget_f(v,0); vsip_vput_f(v,0,1.0); houseProd_f(v,msv_f(U,Us,i,i)); vsip_vput_f(v,0,t); } for(i=n-2; i>=0; i--){ col_sv_f(msv_f(B,Bs,i,i),v,0); t=vsip_vget_f(v,0); vsip_vput_f(v,0,1.0); houseProd_f(v,msv_f(U,Us,i,i)); vsip_vput_f(v,0,t); } return U; } static vsip_cmview_f *cUmatExtract_f(vsip_cmview_f*B){ vsip_stride i; vsip_length m = vsip_cmgetcollength_f(B); vsip_length n = vsip_cmgetrowlength_f(B); vsip_cmview_f *U=cmeye_f(m); vsip_cmview_f *Bs, *Us; vsip_cvview_f *v; vsip_cscalar_f t; v = vsip_cmcolview_f(B,0); Bs=vsip_cmcloneview_f(B); Us=vsip_cmcloneview_f(U); if (m > n){ i=n-1; ccol_sv_f(cmsv_f(B,Bs,i,i),v,0); t=vsip_cvget_f(v,0); vsip_cvput_f(v,0,vsip_cmplx_f(1.0,0.0)); chouseProd_f(v,cmsv_f(U,Us,i,i)); vsip_cvput_f(v,0,t); } for(i=n-2; i>=0; i--){ ccol_sv_f(cmsv_f(B,Bs,i,i),v,0); t=vsip_cvget_f(v,0); vsip_cvput_f(v,0,vsip_cmplx_f(1.0,0.0)); chouseProd_f(v,cmsv_f(U,Us,i,i)); vsip_cvput_f(v,0,t); } return U; } static vsip_mview_f *VHmatExtract_f(vsip_mview_f*B){ vsip_stride i; vsip_length n = vsip_mgetrowlength_f(B); vsip_mview_f *Bs; vsip_mview_f *V=meye_f(n); vsip_mview_f *Vs; vsip_vview_f *v; vsip_scalar_f t; if(n < 3) return V; v = vsip_mrowview_f(B,0); Vs=vsip_mcloneview_f(V); Bs=vsip_mcloneview_f(B); for(i=n-3; i>=0; i--){ vsip_stride j=i+1; row_sv_f(msv_f(B,Bs,i,j),v,0); t=vsip_vget_f(v,0);vsip_vput_f(v,0,1.0); prodHouse_f(msv_f(V,Vs,j,j),v); vsip_vput_f(v,0,t); } vsip_vdestroy_f(v); vsip_mdestroy_f(Vs); vsip_mdestroy_f(Bs); return V; } static vsip_cmview_f *cVHmatExtract_f(vsip_cmview_f*B){ vsip_stride i; vsip_length n = vsip_cmgetrowlength_f(B); vsip_cmview_f *Bs; vsip_cmview_f *V=cmeye_f(n); vsip_cmview_f *Vs; vsip_cvview_f *v; vsip_cscalar_f t; if(n < 3) return V; v = vsip_cmrowview_f(B,0); Vs=vsip_cmcloneview_f(V); Bs=vsip_cmcloneview_f(B); for(i=n-3; i>=0; i--){ vsip_stride j=i+1; crow_sv_f(cmsv_f(B,Bs,i,j),v,0); t=vsip_cvget_f(v,0);vsip_cvput_f(v,0,vsip_cmplx_f(1.0,0.0)); cprodHouse_f(cmsv_f(V,Vs,j,j),v); vsip_cvput_f(v,0,t); } vsip_cvdestroy_f(v); vsip_cmdestroy_f(Vs); vsip_cmdestroy_f(Bs); return V; } static vsip_mview_d *UmatExtract_d(vsip_mview_d*B){ vsip_stride i; vsip_length m = vsip_mgetcollength_d(B); vsip_length n = vsip_mgetrowlength_d(B); vsip_mview_d *U=meye_d(m); vsip_mview_d *Bs, *Us; vsip_vview_d *v; vsip_scalar_d t; v = vsip_mcolview_d(B,0); Bs=vsip_mcloneview_d(B); Us=vsip_mcloneview_d(U); if (m > n){ i=n-1; col_sv_d(msv_d(B,Bs,i,i),v,0); t=vsip_vget_d(v,0); vsip_vput_d(v,0,1.0); houseProd_d(v,msv_d(U,Us,i,i)); vsip_vput_d(v,0,t); } for(i=n-2; i>=0; i--){ col_sv_d(msv_d(B,Bs,i,i),v,0); t=vsip_vget_d(v,0); vsip_vput_d(v,0,1.0); houseProd_d(v,msv_d(U,Us,i,i)); vsip_vput_d(v,0,t); } return U; } static vsip_cmview_d *cUmatExtract_d(vsip_cmview_d*B){ vsip_stride i; vsip_length m = vsip_cmgetcollength_d(B); vsip_length n = vsip_cmgetrowlength_d(B); vsip_cmview_d *U=cmeye_d(m); vsip_cmview_d *Bs, *Us; vsip_cvview_d *v; vsip_cscalar_d t; v = vsip_cmcolview_d(B,0); Bs=vsip_cmcloneview_d(B); Us=vsip_cmcloneview_d(U); if (m > n){ i=n-1; ccol_sv_d(cmsv_d(B,Bs,i,i),v,0); t=vsip_cvget_d(v,0); vsip_cvput_d(v,0,vsip_cmplx_d(1.0,0.0)); chouseProd_d(v,cmsv_d(U,Us,i,i)); vsip_cvput_d(v,0,t); } for(i=n-2; i>=0; i--){ ccol_sv_d(cmsv_d(B,Bs,i,i),v,0); t=vsip_cvget_d(v,0); vsip_cvput_d(v,0,vsip_cmplx_d(1.0,0.0)); chouseProd_d(v,cmsv_d(U,Us,i,i)); vsip_cvput_d(v,0,t); } return U; } static vsip_mview_d *VHmatExtract_d(vsip_mview_d*B){ vsip_stride i; vsip_length n = vsip_mgetrowlength_d(B); vsip_mview_d *Bs; vsip_mview_d *V=meye_d(n); vsip_mview_d *Vs; vsip_vview_d *v; vsip_scalar_d t; if(n < 3) return V; v = vsip_mrowview_d(B,0); Vs=vsip_mcloneview_d(V); Bs=vsip_mcloneview_d(B); for(i=n-3; i>=0; i--){ vsip_stride j=i+1; row_sv_d(msv_d(B,Bs,i,j),v,0); t=vsip_vget_d(v,0);vsip_vput_d(v,0,1.0); prodHouse_d(msv_d(V,Vs,j,j),v); vsip_vput_d(v,0,t); } vsip_vdestroy_d(v); vsip_mdestroy_d(Vs); vsip_mdestroy_d(Bs); return V; } static vsip_cmview_d *cVHmatExtract_d(vsip_cmview_d*B){ vsip_stride i; vsip_length n = vsip_cmgetrowlength_d(B); vsip_cmview_d *Bs; vsip_cmview_d *V=cmeye_d(n); vsip_cmview_d *Vs; vsip_cvview_d *v; vsip_cscalar_d t; if(n < 3) return V; v = vsip_cmrowview_d(B,0); Vs=vsip_cmcloneview_d(V); Bs=vsip_cmcloneview_d(B); for(i=n-3; i>=0; i--){ vsip_stride j=i+1; crow_sv_d(cmsv_d(B,Bs,i,j),v,0); t=vsip_cvget_d(v,0);vsip_cvput_d(v,0,vsip_cmplx_d(1.0,0.0)); cprodHouse_d(cmsv_d(V,Vs,j,j),v); vsip_cvput_d(v,0,t); } vsip_cvdestroy_d(v); vsip_cmdestroy_d(Vs); vsip_cmdestroy_d(Bs); return V; } static void csvdZeroCheckAndSet_f(vsip_scalar_f e, vsip_cvview_f *b0, vsip_cvview_f *b1){ vsip_index i; vsip_length n = vsip_cvgetlength_f(b1); vsip_cscalar_f z = vsip_cmplx_f(0.0,0.0); for(i=0; i<n; i++){ vsip_scalar_f b = vsip_cmag_f(vsip_cvget_f(b1,i)); vsip_scalar_f a = e*(vsip_cmag_f(vsip_cvget_f(b0,i)) + vsip_cmag_f(vsip_cvget_f(b0,i+1))); if( b < a ) vsip_cvput_f(b1,i,z); } } static void svdZeroCheckAndSet_f(vsip_scalar_f e, vsip_vview_f *b0, vsip_vview_f *b1){ vsip_index i; vsip_length n = vsip_vgetlength_f(b1); vsip_scalar_f z = 0.0; for(i=0; i<n; i++){ vsip_scalar_f b = vsip_mag_f(vsip_vget_f(b1,i)); vsip_scalar_f a = e*(vsip_mag_f(vsip_vget_f(b0,i)) + vsip_mag_f(vsip_vget_f(b0,i+1))); if( b < a ) vsip_vput_f(b1,i,z); } } static void csvdZeroCheckAndSet_d(vsip_scalar_d e, vsip_cvview_d *b0, vsip_cvview_d *b1){ vsip_index i; vsip_length n = vsip_cvgetlength_d(b1); vsip_cscalar_d z = vsip_cmplx_d(0.0,0.0); for(i=0; i<n; i++){ vsip_scalar_d b = vsip_cmag_d(vsip_cvget_d(b1,i)); vsip_scalar_d a = e*(vsip_cmag_d(vsip_cvget_d(b0,i)) + vsip_cmag_d(vsip_cvget_d(b0,i+1))); if( b < a ) vsip_cvput_d(b1,i,z); } } static void svdZeroCheckAndSet_d(vsip_scalar_d e, vsip_vview_d *b0, vsip_vview_d *b1){ vsip_index i; vsip_length n = vsip_vgetlength_d(b1); vsip_scalar_d z = 0.0; for(i=0; i<n; i++){ vsip_scalar_d b = vsip_mag_d(vsip_vget_d(b1,i)); vsip_scalar_d a = e*(vsip_mag_d(vsip_vget_d(b0,i)) + vsip_mag_d(vsip_vget_d(b0,i+1))); if( b < a ) vsip_vput_d(b1,i,z); } } static void biDiagPhaseToZero_f( vsip_mview_f *L, vsip_vview_f *d, vsip_vview_f *f, vsip_mview_f *R, vsip_scalar_f eps0) { vsip_length n_d=vsip_vgetlength_f(d); vsip_length n_f=vsip_vgetlength_f(f); vsip_index i,j; vsip_scalar_f ps; vsip_scalar_f m; vsip_vview_f *l = vsip_mcolview_f(L,0); vsip_vview_f *r = vsip_mrowview_f(R,0); for(i=0; i<n_d; i++){ ps=vsip_vget_f(d,i); m = vsip_mag_f(ps); ps=sign_f(ps); if(m > eps0){ col_sv_f(L,l,i);vsip_svmul_f(ps,l,l); vsip_vput_f(d,i,m); if (i < n_f) vsip_vput_f(f,i,ps*vsip_vget_f(f,i)); } else { vsip_vput_f(d,i,0.0); } } svdZeroCheckAndSet_f(eps0,d,f); for (i=0; i<n_f-1; i++){ j=i+1; ps = vsip_vget_f(f,i); m = vsip_mag_f(ps); ps=sign_f(ps); col_sv_f(L, l, j);vsip_svmul_f(ps,l,l); row_sv_f(R,r,j);vsip_svmul_f(ps,r,r); vsip_vput_f(f,i,m); vsip_vput_f(f,j,ps * vsip_vget_f(f,j)); } j=n_f; i=j-1; ps=vsip_vget_f(f,i); m=vsip_mag_f(ps); ps=sign_f(ps); vsip_vput_f(f,i,m); col_sv_f(L, l, j);vsip_svmul_f(ps,l,l); row_sv_f(R,r,j);vsip_svmul_f(ps,r,r); vsip_vdestroy_f(l); vsip_vdestroy_f(r); } static void cbiDiagPhaseToZero_f( vsip_cmview_f *L, vsip_cvview_f *d, vsip_cvview_f *f, vsip_cmview_f *R, vsip_scalar_f eps0) { vsip_length n_d=vsip_cvgetlength_f(d); vsip_length n_f=vsip_cvgetlength_f(f); vsip_index i,j; vsip_cscalar_f ps; vsip_scalar_f m; vsip_cvview_f *l = vsip_cmcolview_f(L,0); vsip_cvview_f *r = vsip_cmrowview_f(R,0); for(i=0; i<n_d; i++){ ps=vsip_cvget_f(d,i); if(ps.i == 0.0){ m = ps.r; if (m < 0.0) ps=vsip_cmplx_f(-1.0,0.0); else ps= vsip_cmplx_f(1.0,0.0); m = vsip_mag_f(m); } else { m=vsip_cmag_f(ps); ps.r /= m; ps.i/=m; } if(m > eps0){ ccol_sv_f(L,l,i);vsip_csvmul_f(ps,l,l); vsip_cvput_f(d,i,vsip_cmplx_f(m,0)); if (i < n_f) vsip_cvput_f(f,i,vsip_cjmul_f(vsip_cvget_f(f,i),ps)); }else{ vsip_cvput_f(d,i,vsip_cmplx_f(0.0,0.0)); } } csvdZeroCheckAndSet_f(eps0,d,f); for (i=0; i<n_f-1; i++){ j=i+1; ps = vsip_cvget_f(f,i); if (ps.i == 0.0){ m = ps.r; if (m < 0.0) ps=vsip_cmplx_f(-1.0,0.0); else ps= vsip_cmplx_f(1.0,0.0); m = vsip_mag_f(m); }else{ m=vsip_cmag_f(ps); ps.r /= m; ps.i/=m; } ccol_sv_f(L, l, j);vsip_csvmul_f(vsip_conj_f(ps),l,l); crow_sv_f(R,r,j);vsip_csvmul_f(ps,r,r); vsip_cvput_f(f,i,vsip_cmplx_f(m,0)); vsip_cvput_f(f,j,vsip_cmul_f(vsip_cvget_f(f,j),ps)); } j=n_f; i=j-1; ps=vsip_cvget_f(f,i); if (ps.i == 0.0){ m = ps.r; if(m < 0.0) ps=vsip_cmplx_f(-1.0,0.0); else ps= vsip_cmplx_f(1.0,0.0); m = vsip_mag_f(m); }else{ m=vsip_cmag_f(ps); ps.r /= m; ps.i/=m; } vsip_cvput_f(f,i,vsip_cmplx_f(m,0.0)); ccol_sv_f(L, l, j);vsip_csvmul_f(vsip_conj_f(ps),l,l); crow_sv_f(R,r,j);vsip_csvmul_f(ps,r,r); vsip_cvdestroy_f(l); vsip_cvdestroy_f(r); } static void biDiagPhaseToZero_d( vsip_mview_d *L, vsip_vview_d *d, vsip_vview_d *f, vsip_mview_d *R, vsip_scalar_d eps0) { vsip_length n_d=vsip_vgetlength_d(d); vsip_length n_f=vsip_vgetlength_d(f); vsip_index i,j; vsip_scalar_d ps; vsip_scalar_d m; vsip_vview_d *l = vsip_mcolview_d(L,0); vsip_vview_d *r = vsip_mrowview_d(R,0); for(i=0; i<n_d; i++){ ps=vsip_vget_d(d,i); m = vsip_mag_d(ps); ps=sign_d(ps); if(m > eps0){ col_sv_d(L,l,i);vsip_svmul_d(ps,l,l); vsip_vput_d(d,i,m); if (i < n_d) vsip_vput_d(f,i,ps*vsip_vget_d(f,i)); } else { vsip_vput_d(d,i,0.0); } } svdZeroCheckAndSet_d(eps0,d,f); for (i=0; i<n_f-1; i++){ j=i+1; ps = vsip_vget_d(f,i); m = vsip_mag_d(ps); ps=sign_d(ps); col_sv_d(L, l, j);vsip_svmul_d(ps,l,l); row_sv_d(R,r,j);vsip_svmul_d(ps,r,r); vsip_vput_d(f,i,m); vsip_vput_d(f,j,ps * vsip_vget_d(f,j)); } j=n_f; i=j-1; ps=vsip_vget_d(f,i); m=vsip_mag_d(ps); ps=sign_d(ps); vsip_vput_d(f,i,m); col_sv_d(L, l, j);vsip_svmul_d(ps,l,l); row_sv_d(R,r,j);vsip_svmul_d(ps,r,r); vsip_vdestroy_d(l); vsip_vdestroy_d(r); } static void cbiDiagPhaseToZero_d( vsip_cmview_d *L, vsip_cvview_d *d, vsip_cvview_d *f, vsip_cmview_d *R, vsip_scalar_d eps0) { vsip_length n_d=vsip_cvgetlength_d(d); vsip_length n_f=vsip_cvgetlength_d(f); vsip_index i,j; vsip_cscalar_d ps; vsip_scalar_d m; vsip_cvview_d *l = vsip_cmcolview_d(L,0); vsip_cvview_d *r = vsip_cmrowview_d(R,0); for(i=0; i<n_d; i++){ ps=vsip_cvget_d(d,i); if(ps.i == 0.0){ m = ps.r; if (m < 0.0) ps=vsip_cmplx_d(-1.0,0.0); else ps= vsip_cmplx_d(1.0,0.0); m = vsip_mag_d(m); } else { m=vsip_cmag_d(ps); ps.r /= m; ps.i/=m; } if(m > eps0){ ccol_sv_d(L,l,i);vsip_csvmul_d(ps,l,l); vsip_cvput_d(d,i,vsip_cmplx_d(m,0)); if (i < n_f) vsip_cvput_d(f,i,vsip_cjmul_d(vsip_cvget_d(f,i),ps)); }else{ vsip_cvput_d(d,i,vsip_cmplx_d(0.0,0.0)); } } csvdZeroCheckAndSet_d(eps0,d,f); for (i=0; i<n_f-1; i++){ j=i+1; ps = vsip_cvget_d(f,i); if (ps.i == 0.0){ m = ps.r; if (m < 0.0) ps=vsip_cmplx_d(-1.0,0.0); else ps= vsip_cmplx_d(1.0,0.0); m = vsip_mag_d(m); }else{ m=vsip_cmag_d(ps); ps.r /= m; ps.i/=m; } ccol_sv_d(L, l, j);vsip_csvmul_d(vsip_conj_d(ps),l,l); crow_sv_d(R,r,j);vsip_csvmul_d(ps,r,r); vsip_cvput_d(f,i,vsip_cmplx_d(m,0)); vsip_cvput_d(f,j,vsip_cmul_d(vsip_cvget_d(f,j),ps)); } j=n_f; i=j-1; ps=vsip_cvget_d(f,i); if (ps.i == 0.0){ m = ps.r; if(m < 0.0) ps=vsip_cmplx_d(-1.0,0.0); else ps= vsip_cmplx_d(1.0,0.0); m = vsip_mag_d(m); }else{ m=vsip_cmag_d(ps); ps.r /= m; ps.i/=m; } vsip_cvput_d(f,i,vsip_cmplx_d(m,0.0)); ccol_sv_d(L, l, j);vsip_csvmul_d(vsip_conj_d(ps),l,l); crow_sv_d(R,r,j);vsip_csvmul_d(ps,r,r); vsip_cvdestroy_d(l); vsip_cvdestroy_d(r); } static svdObj_f svdBidiag_f(vsip_mview_f* A) { svdObj_f retval; /* sv is a number < maximum singular value */ vsip_scalar_f sv = mnormFro_f(A)/(vsip_scalar_f)vsip_mgetrowlength_f(A); vsip_mview_f *B=bidiag_f(A); vsip_vview_f *d0=NULL,*f0=NULL; retval.init=0; if(!B) retval.init++; if(B) d0=vsip_mdiagview_f(B,0); if(!d0) retval.init++; if(B) f0=vsip_mdiagview_f(B,1); if(!f0) retval.init++; retval.d=vclone_f(d0); if(!retval.d) retval.init++; retval.f=vclone_f(f0); if(!retval.f) retval.init++; if(B) retval.L=UmatExtract_f(B); else retval.L=NULL; if(!retval.L) retval.init++; if(B) retval.R=VHmatExtract_f(B); else retval.R=NULL; if(!retval.R) retval.init++; /* eps0 is a number << maximum singular value */ retval.eps0=sv*1E-10; vsip_vdestroy_f(d0); vsip_vdestroy_f(f0); vsip_malldestroy_f(B); biDiagPhaseToZero_f(retval.L,retval.d,retval.f,retval.R,retval.eps0); return retval; } static csvdObj_f csvdBidiag_f(vsip_cmview_f* A) { csvdObj_f retval; /* sv is a number < maximum singular value */ vsip_scalar_f sv = cmnormFro_f(A)/(vsip_scalar_f)vsip_cmgetrowlength_f(A); vsip_cmview_f *B=cbidiag_f(A); vsip_cvview_f *dc=NULL,*fc=NULL; vsip_vview_f *d0=NULL, *f0=NULL; retval.init=0; if(!B) retval.init++; if(B) dc=vsip_cmdiagview_f(B,0); if(!dc) retval.init++; if(dc) d0=vsip_vrealview_f(dc); if(!d0) retval.init++; if(B) fc=vsip_cmdiagview_f(B,1); if(!fc) retval.init++; if(fc) f0 = vsip_vrealview_f(fc); if(!f0) retval.init++; if(B) retval.L=cUmatExtract_f(B); else retval.L=NULL; if(!retval.L) retval.init++; if(B) retval.R=cVHmatExtract_f(B); else retval.R=NULL; if(!retval.R) retval.init++; /* eps0 is a number << maximum singular value */ retval.eps0=sv*1E-10; cbiDiagPhaseToZero_f(retval.L,dc,fc,retval.R,retval.eps0); retval.d=vclone_f(d0); if(!retval.d) retval.init++; retval.f=vclone_f(f0); if(!retval.f) retval.init++; vsip_vdestroy_f(d0); vsip_vdestroy_f(f0); vsip_cvdestroy_f(dc); vsip_cvdestroy_f(fc); vsip_cmalldestroy_f(B); return retval; } static svdObj_d svdBidiag_d(vsip_mview_d* A) { svdObj_d retval; /* sv is a number < maximum singular value */ vsip_scalar_d sv = mnormFro_d(A)/(vsip_scalar_d)vsip_mgetrowlength_d(A); vsip_mview_d *B=bidiag_d(A); vsip_vview_d *d0=NULL,*f0=NULL; retval.init=0; if(!B) retval.init++; if(B) d0=vsip_mdiagview_d(B,0); if(!d0) retval.init++; if(B) f0=vsip_mdiagview_d(B,1); if(!f0) retval.init++; retval.d=vclone_d(d0); if(!retval.d) retval.init++; retval.f=vclone_d(f0); if(!retval.f) retval.init++; if(B) retval.L=UmatExtract_d(B); else retval.L=NULL; if(!retval.L) retval.init++; if(B) retval.R=VHmatExtract_d(B); else retval.R=NULL; if(!retval.R) retval.init++; /* eps0 is a number << maximum singular value */ retval.eps0=sv*1E-10; vsip_vdestroy_d(d0); vsip_vdestroy_d(f0); vsip_malldestroy_d(B); biDiagPhaseToZero_d(retval.L,retval.d,retval.f,retval.R,retval.eps0); return retval; } static csvdObj_d csvdBidiag_d(vsip_cmview_d* A) { csvdObj_d retval; /* sv is a number < maximum singular value */ vsip_scalar_d sv = cmnormFro_d(A)/(vsip_scalar_d)vsip_cmgetrowlength_d(A); vsip_cmview_d *B=cbidiag_d(A); vsip_cvview_d *dc=NULL,*fc=NULL; vsip_vview_d *d0=NULL, *f0=NULL; retval.init=0; if(!B) retval.init++; if(B) dc=vsip_cmdiagview_d(B,0); if(!dc) retval.init++; if(dc) d0=vsip_vrealview_d(dc); if(!d0) retval.init++; if(B) fc=vsip_cmdiagview_d(B,1); if(!fc) retval.init++; if(fc) f0 = vsip_vrealview_d(fc); if(!f0) retval.init++; if(B) retval.L=cUmatExtract_d(B); else retval.L=NULL; if(!retval.L) retval.init++; if(B) retval.R=cVHmatExtract_d(B); else retval.R=NULL; if(!retval.R) retval.init++; /* eps0 is a number << maximum singular value */ retval.eps0=sv*1E-10; cbiDiagPhaseToZero_d(retval.L,dc,fc,retval.R,retval.eps0); retval.d=vclone_d(d0); if(!retval.d) retval.init++; retval.f=vclone_d(f0); if(!retval.f) retval.init++; vsip_vdestroy_d(d0); vsip_vdestroy_d(f0); vsip_cvdestroy_d(dc); vsip_cvdestroy_d(fc); vsip_cmalldestroy_d(B); return retval; } /* for SVD Givens Coefficients are only calculated for real numbers */ static givensObj_f givensCoef_f(vsip_scalar_f x1, vsip_scalar_f x2) { givensObj_f retval; vsip_scalar_f t = vsip_hypot_f(x1,x2); if (x2 == 0.0){ retval.c=1.0;retval.s=0.0;retval.r=x1; } else if (x1 == 0.0) { retval.c=0.0;retval.s=sign_f(x2);retval.r=t; }else{ vsip_scalar_f sn = sign_f(x1); retval.c=vsip_mag_f(x1)/t;retval.s=sn*x2/t; retval.r=sn*t; } return retval; } static givensObj_d givensCoef_d(vsip_scalar_d x1, vsip_scalar_d x2) { givensObj_d retval; vsip_scalar_d t = vsip_hypot_d(x1,x2); if (x2 == 0.0){ retval.c=1.0;retval.s=0.0;retval.r=x1; } else if (x1 == 0.0) { retval.c=0.0;retval.s=sign_d(x2);retval.r=t; }else{ vsip_scalar_d sn = sign_d(x1); retval.c=vsip_mag_d(x1)/t;retval.s=sn * x2/t; retval.r=sn*t; } return retval; } static svdCorner svdCorners_f(vsip_vview_f* f) { svdCorner crnr; vsip_index j=vsip_vgetlength_f(f)-1; vsip_index i; while((j > 0) && (vsip_vget_f(f,j) == 0.0)) j-=1; if(j == 0 && vsip_vget_f(f,0) == 0.0){ crnr.i=0; crnr.j=0; } else { i = j; j += 1; while((i > 0) && (vsip_vget_f(f,i) != 0.0)) i -= 1; if((i == 0) && (vsip_vget_f(f,0)== 0.0)){ crnr.i=1; crnr.j=j+1; } else if (i==0){ crnr.i=0; crnr.j=j+1; } else { crnr.i=i+1; crnr.j=j+1; } } return crnr; } static svdCorner svdCorners_d(vsip_vview_d* f) { svdCorner crnr; vsip_index j=vsip_vgetlength_d(f)-1; vsip_index i; while((j > 0) && (vsip_vget_d(f,j) == 0.0)) j-=1; if(j == 0 && vsip_vget_d(f,0) == 0.0){ crnr.i=0; crnr.j=0; } else { i = j; j += 1; while((i > 0) && (vsip_vget_d(f,i) != 0.0)) i -= 1; if((i == 0) && (vsip_vget_d(f,0)== 0.0)){ crnr.i=1; crnr.j=j+1; } else if (i==0){ crnr.i=0; crnr.j=j+1; } else { crnr.i=i+1; crnr.j=j+1; } } return crnr; } static void phaseCheck_f(vsip_mview_f* L,vsip_vview_f* d,vsip_vview_f* f,vsip_mview_f* R,vsip_scalar_f eps0) { biDiagPhaseToZero_f(L,d,f,R,eps0); } static void cphaseCheck_f(vsip_cmview_f* L, vsip_vview_f* d, vsip_vview_f* f,vsip_cmview_f* R, vsip_scalar_f eps0) { vsip_length nf=vsip_vgetlength_f(f); vsip_index i,j; vsip_scalar_f ps; vsip_scalar_f m; vsip_cvview_f *l = vsip_cmcolview_f(L,0); vsip_cvview_f *r = vsip_cmrowview_f(R,0); for(i=0; i<vsip_vgetlength_f(d); i++){ ps=vsip_vget_f(d,i); m = vsip_mag_f(ps); ps=sign_f(ps); if(m > eps0){ ccol_sv_f(L,l,i);vsip_rscvmul_f(ps,l,l); vsip_vput_f(d,i,m); if (i < nf) vsip_vput_f(f,i,ps*vsip_vget_f(f,i)); } else { vsip_vput_f(d,i,0.0); } } svdZeroCheckAndSet_f(eps0,d,f); for (i=0; i<nf-1; i++){ j=i+1; ps = vsip_vget_f(f,i); m = vsip_mag_f(ps); ps=sign_f(ps); ccol_sv_f(L, l, j);vsip_rscvmul_f(ps,l,l); crow_sv_f(R,r,j);vsip_rscvmul_f(ps,r,r); vsip_vput_f(f,i,m); vsip_vput_f(f,j,ps * vsip_vget_f(f,j)); } j=nf; i=j-1; ps=vsip_vget_f(f,i); m=vsip_mag_f(ps); ps=sign_f(ps); vsip_vput_f(f,i,m); ccol_sv_f(L, l, j);vsip_rscvmul_f(ps,l,l); crow_sv_f(R,r,j);vsip_rscvmul_f(ps,r,r); } static void phaseCheck_d(vsip_mview_d* L,vsip_vview_d* d,vsip_vview_d* f,vsip_mview_d* R,vsip_scalar_d eps0) { biDiagPhaseToZero_d(L,d,f,R,eps0); } static void cphaseCheck_d(vsip_cmview_d* L, vsip_vview_d* d, vsip_vview_d* f,vsip_cmview_d* R, vsip_scalar_d eps0) { vsip_length nf=vsip_vgetlength_d(f); vsip_index i,j; vsip_scalar_d ps; vsip_scalar_d m; vsip_cvview_d *l = vsip_cmcolview_d(L,0); vsip_cvview_d *r = vsip_cmrowview_d(R,0); for(i=0; i<vsip_vgetlength_d(d); i++){ ps=vsip_vget_d(d,i); m = vsip_mag_f(ps); ps=sign_d(ps); if(m > eps0){ ccol_sv_d(L,l,i);vsip_rscvmul_d(ps,l,l); vsip_vput_d(d,i,m); if (i < nf) vsip_vput_d(f,i,ps*vsip_vget_d(f,i)); } else { vsip_vput_d(d,i,0.0); } } svdZeroCheckAndSet_d(eps0,d,f); for (i=0; i<nf-1; i++){ j=i+1; ps = vsip_vget_d(f,i); m = vsip_mag_d(ps); ps=sign_d(ps); ccol_sv_d(L, l, j);vsip_rscvmul_d(ps,l,l); crow_sv_d(R,r,j);vsip_rscvmul_d(ps,r,r); vsip_vput_d(f,i,m); vsip_vput_d(f,j,ps * vsip_vget_d(f,j)); } j=nf; i=j-1; ps=vsip_vget_d(f,i); m=vsip_mag_d(ps); ps=sign_d(ps); vsip_vput_d(f,i,m); ccol_sv_d(L, l, j);vsip_rscvmul_d(ps,l,l); crow_sv_d(R,r,j);vsip_rscvmul_d(ps,r,r); } static vsip_index zeroFind_f(vsip_vview_f* d, vsip_scalar_f eps0){ vsip_index j = vsip_vgetlength_f(d); vsip_scalar_f xd=vsip_vget_f(d,j-1); while(xd > eps0){ if (j > 1){ j -= 1; xd=vsip_vget_f(d,j-1); }else{ break; } } if(xd <= eps0) vsip_vput_f(d,j-1,0.0); if (j == 1) j=0; return j; } static vsip_index zeroFind_d(vsip_vview_d* d, vsip_scalar_d eps0){ vsip_index j = vsip_vgetlength_d(d); vsip_scalar_d xd=vsip_vget_d(d,j-1); while(xd > eps0){ if (j > 1){ j -= 1; xd=vsip_vget_d(d,j-1); }else{ break; } } if(xd <= eps0) vsip_vput_d(d,j-1,0.0); if (j == 1) j=0; return j; } static void zeroRow_f(vsip_mview_f* L,vsip_vview_f *d,vsip_vview_f *f) { vsip_length n = vsip_vgetlength_f(d); givensObj_f g; vsip_scalar_f xd,xf,t; vsip_index i; xd=vsip_vget_f(d,0); xf=vsip_vget_f(f,0); g=givensCoef_f(xd,xf); if (n == 1){ vsip_vput_f(f,0,0.0); vsip_vput_f(d,0,g.r); }else{ vsip_vput_f(f,0,0.0); vsip_vput_f(d,0,g.r); xf=vsip_vget_f(f,1); t= -xf * g.s; xf *= g.c; vsip_vput_f(f,1,xf); prodG_f(L,1,0,g.c,g.s); for(i=1; i<n-1; i++){ xd=vsip_vget_f(d,i); g=givensCoef_f(xd,t); prodG_f(L,i+1,0,g.c,g.s); vsip_vput_f(d,i,g.r); xf=vsip_vget_f(f,i+1); t=-xf * g.s; xf *= g.c; vsip_vput_f(f,i+1,xf); } xd=vsip_vget_f(d,n-1); g=givensCoef_f(xd,t); vsip_vput_f(d,n-1,g.r); prodG_f(L,n,0,g.c,g.s); } } static void zeroCol_f(vsip_vview_f *d,vsip_vview_f *f, vsip_mview_f* R) { vsip_length n = vsip_vgetlength_f(f); givensObj_f g; vsip_scalar_f xd,xf,t; vsip_index i,j,k; if (n == 1){ xd=vsip_vget_f(d,0); xf=vsip_vget_f(f,0); g=givensCoef_f(xd,xf); vsip_vput_f(d,0,g.r); vsip_vput_f(f,0,0.0); gtProd_f(0,1,g.c,g.s,R); }else if (n == 2){ xd=vsip_vget_f(d,1); xf=vsip_vget_f(f,1); g=givensCoef_f(xd,xf); vsip_vput_f(d,1,g.r); vsip_vput_f(f,1,0.0); xf=vsip_vget_f(f,0); t= -xf * g.s; xf *= g.c; vsip_vput_f(f,0,xf); gtProd_f(1,2,g.c,g.s,R); xd=vsip_vget_f(d,0); g=givensCoef_f(xd,t); vsip_vput_f(d,0,g.r); gtProd_f(0,2,g.c,g.s,R); }else{ i=n-1; j=i-1; k=i; xd=vsip_vget_f(d,i); xf=vsip_vget_f(f,i); g=givensCoef_f(xd,xf); xf=vsip_vget_f(f,j); vsip_vput_f(f,i,0.0); vsip_vput_f(d,i,g.r); t=-xf*g.s; xf*=g.c; vsip_vput_f(f,j,xf); gtProd_f(i,k+1,g.c,g.s,R); while (i > 1){ i = j; j = i-1; xd=vsip_vget_f(d,i); g=givensCoef_f(xd,t); vsip_vput_f(d,i,g.r); xf=vsip_vget_f(f,j); t= -xf * g.s; xf *= g.c; vsip_vput_f(f,j,xf); gtProd_f(i,k+1,g.c,g.s,R); } xd=vsip_vget_f(d,0); g=givensCoef_f(xd,t); vsip_vput_f(d,0,g.r); gtProd_f(0,k+1,g.c,g.s,R); } } static void zeroRow_d(vsip_mview_d* L,vsip_vview_d *d,vsip_vview_d *f) { vsip_length n = vsip_vgetlength_d(d); givensObj_d g; vsip_scalar_d xd,xf,t; vsip_index i; xd=vsip_vget_d(d,0); xf=vsip_vget_d(f,0); g=givensCoef_d(xd,xf); if (n == 1){ vsip_vput_d(f,0,0.0); vsip_vput_d(d,0,g.r); }else{ vsip_vput_d(f,0,0.0); vsip_vput_d(d,0,g.r); xf=vsip_vget_d(f,1); t= -xf * g.s; xf *= g.c; vsip_vput_d(f,1,xf); prodG_d(L,1,0,g.c,g.s); for(i=1; i<n-1; i++){ xd=vsip_vget_d(d,i); g=givensCoef_d(xd,t); prodG_d(L,i+1,0,g.c,g.s); vsip_vput_d(d,i,g.r); xf=vsip_vget_d(f,i+1); t=-xf * g.s; xf *= g.c; vsip_vput_d(f,i+1,xf); } xd=vsip_vget_d(d,n-1); g=givensCoef_d(xd,t); vsip_vput_d(d,n-1,g.r); prodG_d(L,n,0,g.c,g.s); } } static void zeroCol_d(vsip_vview_d *d,vsip_vview_d *f, vsip_mview_d* R) { vsip_length n = vsip_vgetlength_d(f); givensObj_d g; vsip_scalar_d xd,xf,t; vsip_index i,j,k; if (n == 1){ xd=vsip_vget_d(d,0); xf=vsip_vget_d(f,0); g=givensCoef_d(xd,xf); vsip_vput_d(d,0,g.r); vsip_vput_d(f,0,0.0); gtProd_d(0,1,g.c,g.s,R); }else if (n == 2){ xd=vsip_vget_d(d,1); xf=vsip_vget_d(f,1); g=givensCoef_d(xd,xf); vsip_vput_d(d,1,g.r); vsip_vput_d(f,1,0.0); xf=vsip_vget_d(f,0); t= -xf * g.s; xf *= g.c; vsip_vput_d(f,0,xf); gtProd_d(1,2,g.c,g.s,R); xd=vsip_vget_d(d,0); g=givensCoef_d(xd,t); vsip_vput_d(d,0,g.r); gtProd_d(0,2,g.c,g.s,R); }else{ i=n-1; j=i-1; k=i; xd=vsip_vget_d(d,i); xf=vsip_vget_d(f,i); g=givensCoef_d(xd,xf); xf=vsip_vget_d(f,j); vsip_vput_d(f,i,0.0); vsip_vput_d(d,i,g.r); t=-xf*g.s; xf*=g.c; vsip_vput_d(f,j,xf); gtProd_d(i,k+1,g.c,g.s,R); while (i > 1){ i = j; j = i-1; xd=vsip_vget_d(d,i); g=givensCoef_d(xd,t); vsip_vput_d(d,i,g.r); xf=vsip_vget_d(f,j); t= -xf * g.s; xf *= g.c; vsip_vput_d(f,j,xf); gtProd_d(i,k+1,g.c,g.s,R); } xd=vsip_vget_d(d,0); g=givensCoef_d(xd,t); vsip_vput_d(d,0,g.r); gtProd_d(0,k+1,g.c,g.s,R); } } static void czeroRow_f(vsip_cmview_f* L,vsip_vview_f *d,vsip_vview_f *f) { vsip_length n = vsip_vgetlength_f(d); givensObj_f g; vsip_scalar_f xd,xf,t; vsip_index i; xd=vsip_vget_f(d,0); xf=vsip_vget_f(f,0); g=givensCoef_f(xd,xf); if (n == 1){ vsip_vput_f(f,0,0.0); vsip_vput_f(d,0,g.r); }else{ vsip_vput_f(f,0,0.0); vsip_vput_f(d,0,g.r); xf=vsip_vget_f(f,1); t= -xf * g.s; xf *= g.c; vsip_vput_f(f,1,xf); cprodG_f(L,1,0,g.c,g.s); for(i=1; i<n-1; i++){ xd=vsip_vget_f(d,i); g=givensCoef_f(xd,t); cprodG_f(L,i+1,0,g.c,g.s); vsip_vput_f(d,i,g.r); xf=vsip_vget_f(f,i+1); t=-xf * g.s; xf *= g.c; vsip_vput_f(f,i+1,xf); } xd=vsip_vget_f(d,n-1); g=givensCoef_f(xd,t); vsip_vput_f(d,n-1,g.r); cprodG_f(L,n,0,g.c,g.s); } } static void czeroCol_f(vsip_vview_f *d,vsip_vview_f *f, vsip_cmview_f* R) { vsip_length n = vsip_vgetlength_f(f); givensObj_f g; vsip_scalar_f xd,xf,t; vsip_index i,j,k; if (n == 1){ xd=vsip_vget_f(d,0); xf=vsip_vget_f(f,0); g=givensCoef_f(xd,xf); vsip_vput_f(d,0,g.r); vsip_vput_f(f,0,0.0); cgtProd_f(0,1,g.c,g.s,R); }else if (n == 2){ xd=vsip_vget_f(d,1); xf=vsip_vget_f(f,1); g=givensCoef_f(xd,xf); vsip_vput_f(d,1,g.r); vsip_vput_f(f,1,0.0); xf=vsip_vget_f(f,0); t= -xf * g.s; xf *= g.c; vsip_vput_f(f,0,xf); cgtProd_f(1,2,g.c,g.s,R); xd=vsip_vget_f(d,0); g=givensCoef_f(xd,t); vsip_vput_f(d,0,g.r); cgtProd_f(0,2,g.c,g.s,R); }else{ i=n-1; j=i-1; k=i; xd=vsip_vget_f(d,i); xf=vsip_vget_f(f,i); g=givensCoef_f(xd,xf); xf=vsip_vget_f(f,j); vsip_vput_f(f,i,0.0); vsip_vput_f(d,i,g.r); t=-xf*g.s; xf*=g.c; vsip_vput_f(f,j,xf); cgtProd_f(i,k+1,g.c,g.s,R); while (i > 1){ i = j; j = i-1; xd=vsip_vget_f(d,i); g=givensCoef_f(xd,t); vsip_vput_f(d,i,g.r); xf=vsip_vget_f(f,j); t= -xf * g.s; xf *= g.c; vsip_vput_f(f,j,xf); cgtProd_f(i,k+1,g.c,g.s,R); } xd=vsip_vget_f(d,0); g=givensCoef_f(xd,t); vsip_vput_f(d,0,g.r); cgtProd_f(0,k+1,g.c,g.s,R); } } static void czeroRow_d(vsip_cmview_d* L,vsip_vview_d *d,vsip_vview_d *f) { vsip_length n = vsip_vgetlength_d(d); givensObj_d g; vsip_scalar_d xd,xf,t; vsip_index i; xd=vsip_vget_d(d,0); xf=vsip_vget_d(f,0); g=givensCoef_d(xd,xf); if (n == 1){ vsip_vput_d(f,0,0.0); vsip_vput_d(d,0,g.r); }else{ vsip_vput_d(f,0,0.0); vsip_vput_d(d,0,g.r); xf=vsip_vget_d(f,1); t= -xf * g.s; xf *= g.c; vsip_vput_d(f,1,xf); cprodG_d(L,1,0,g.c,g.s); for(i=1; i<n-1; i++){ xd=vsip_vget_d(d,i); g=givensCoef_d(xd,t); cprodG_d(L,i+1,0,g.c,g.s); vsip_vput_d(d,i,g.r); xf=vsip_vget_d(f,i+1); t=-xf * g.s; xf *= g.c; vsip_vput_d(f,i+1,xf); } xd=vsip_vget_d(d,n-1); g=givensCoef_d(xd,t); vsip_vput_d(d,n-1,g.r); cprodG_d(L,n,0,g.c,g.s); } } static void czeroCol_d(vsip_vview_d *d,vsip_vview_d *f, vsip_cmview_d* R) { vsip_length n = vsip_vgetlength_d(f); givensObj_d g; vsip_scalar_d xd,xf,t; vsip_index i,j,k; if (n == 1){ xd=vsip_vget_d(d,0); xf=vsip_vget_d(f,0); g=givensCoef_d(xd,xf); vsip_vput_d(d,0,g.r); vsip_vput_d(f,0,0.0); cgtProd_d(0,1,g.c,g.s,R); }else if (n == 2){ xd=vsip_vget_d(d,1); xf=vsip_vget_d(f,1); g=givensCoef_d(xd,xf); vsip_vput_d(d,1,g.r); vsip_vput_d(f,1,0.0); xf=vsip_vget_d(f,0); t= -xf * g.s; xf *= g.c; vsip_vput_d(f,0,xf); cgtProd_d(1,2,g.c,g.s,R); xd=vsip_vget_d(d,0); g=givensCoef_d(xd,t); vsip_vput_d(d,0,g.r); cgtProd_d(0,2,g.c,g.s,R); }else{ i=n-1; j=i-1; k=i; xd=vsip_vget_d(d,i); xf=vsip_vget_d(f,i); g=givensCoef_d(xd,xf); xf=vsip_vget_d(f,j); vsip_vput_d(f,i,0.0); vsip_vput_d(d,i,g.r); t=-xf*g.s; xf*=g.c; vsip_vput_d(f,j,xf); cgtProd_d(i,k+1,g.c,g.s,R); while (i > 1){ i = j; j = i-1; xd=vsip_vget_d(d,i); g=givensCoef_d(xd,t); vsip_vput_d(d,i,g.r); xf=vsip_vget_d(f,j); t= -xf * g.s; xf *= g.c; vsip_vput_d(f,j,xf); cgtProd_d(i,k+1,g.c,g.s,R); } xd=vsip_vget_d(d,0); g=givensCoef_d(xd,t); vsip_vput_d(d,0,g.r); cgtProd_d(0,k+1,g.c,g.s,R); } } static vsip_scalar_f svdMu_f(vsip_scalar_f d2,vsip_scalar_f f1,vsip_scalar_f d3,vsip_scalar_f f2) { vsip_scalar_f mu; vsip_scalar_f cu=d2 * d2 + f1 * f1; vsip_scalar_f cl=d3 * d3 + f2 * f2; vsip_scalar_f cd = d2 * f2; vsip_scalar_f D = (cu * cl - cd * cd); vsip_scalar_f T = (cu + cl); vsip_scalar_f root = vsip_sqrt_f(T*T - 4 * D); vsip_scalar_f lambda1 = (T + root)/(2.); vsip_scalar_f lambda2 = (T - root)/(2.); if(vsip_mag_f(lambda1 - cl) < vsip_mag_f(lambda2 - cl)) mu = lambda1; else mu = lambda2; return mu; } static vsip_scalar_d svdMu_d(vsip_scalar_d d2,vsip_scalar_d f1,vsip_scalar_d d3,vsip_scalar_d f2) { vsip_scalar_d mu; vsip_scalar_d cu=d2 * d2 + f1 * f1; vsip_scalar_d cl=d3 * d3 + f2 * f2; vsip_scalar_d cd = d2 * f2; vsip_scalar_d D = (cu * cl - cd * cd); vsip_scalar_d T = (cu + cl); vsip_scalar_d root = vsip_sqrt_d(T*T - 4 * D); vsip_scalar_d lambda1 = (T + root)/(2.); vsip_scalar_d lambda2 = (T - root)/(2.); if(vsip_mag_d(lambda1 - cl) < vsip_mag_d(lambda2 - cl)) mu = lambda1; else mu = lambda2; return mu; } static void svdStep_f(vsip_mview_f* L, vsip_vview_f* d, vsip_vview_f* f, vsip_mview_f *R) { givensObj_f g; vsip_length n = vsip_vgetlength_f(d); vsip_scalar_f mu=0.0, x1=0.0, x2=0.0; vsip_scalar_f t=0.0; vsip_index i,j,k; vsip_scalar_f d2,f1,d3,f2; if(n >= 3){ d2=vsip_vget_f(d,n-2);f1= vsip_vget_f(f,n-3);d3 = vsip_vget_f(d,n-1);f2= vsip_vget_f(f,n-2); } else if(n == 2){ d2=vsip_vget_f(d,0);f1= 0.0;d3 = vsip_vget_f(d,1);f2= vsip_vget_f(f,0); } else { d2=vsip_vget_f(d,0);f1 = 0.0;d3 = 0.0;f2 = 0.0; } mu = svdMu_f(d2,f1,d3,f2); x1=vsip_vget_f(d,0); x2 = x1 * vsip_vget_f(f,0); x1 *= x1; x1 -= mu; g=givensCoef_f(x1,x2); x1=vsip_vget_f(d,0);x2=vsip_vget_f(f,0); vsip_vput_f(f,0,g.c * x2 - g.s * x1); vsip_vput_f(d,0,x1 * g.c + x2 * g.s); t=vsip_vget_f(d,1); vsip_vput_f(d,1,t*g.c); t*=g.s; gtProd_f(0,1,g.c,g.s,R); for(i=0; i<n-2; i++){ j=i+1; k=i+2; g = givensCoef_f(vsip_vget_f(d,i),t); vsip_vput_f(d,i,g.r); x1=vsip_vget_f(d,j)*g.c; x2=vsip_vget_f(f,i)*g.s; t= x1 - x2; x1=vsip_vget_f(f,i) * g.c; x2=vsip_vget_f(d,j) * g.s ; vsip_vput_f(f,i,x1+x2); vsip_vput_f(d,j,t); x1=vsip_vget_f(f,j); t=g.s * x1; vsip_vput_f(f,j, x1*g.c); prodG_f(L,i, j, g.c, g.s); g=givensCoef_f(vsip_vget_f(f,i),t); vsip_vput_f(f,i,g.r); x1=vsip_vget_f(d,j); x2=vsip_vget_f(f,j); vsip_vput_f(d,j,g.c * x1 + g.s * x2); vsip_vput_f(f,j,g.c * x2 - g.s * x1); x1=vsip_vget_f(d,k); t=g.s * x1; vsip_vput_f(d,k,x1*g.c); gtProd_f(j,k, g.c, g.s,R); } i=n-2; j=n-1; g = givensCoef_f(vsip_vget_f(d,i),t); vsip_vput_f(d,i,g.r); x1=vsip_vget_f(d,j)*g.c; x2=vsip_vget_f(f,i)*g.s; t=x1 - x2; x1 = vsip_vget_f(f,i) * g.c; x2=vsip_vget_f(d,j) * g.s; vsip_vput_f(f,i,x1+x2); vsip_vput_f(d,j,t); prodG_f(L,i, j, g.c, g.s); } static void csvdStep_f(vsip_cmview_f* L, vsip_vview_f* d, vsip_vview_f* f, vsip_cmview_f *R) { givensObj_f g; vsip_length n = vsip_vgetlength_f(d); vsip_scalar_f mu=0.0, x1=0.0, x2=0.0; vsip_scalar_f t=0.0; vsip_index i,j,k; vsip_scalar_f d2,f1,d3,f2; if(n >= 3){ d2=vsip_vget_f(d,n-2);f1= vsip_vget_f(f,n-3);d3 = vsip_vget_f(d,n-1);f2= vsip_vget_f(f,n-2); } else if(n == 2){ d2=vsip_vget_f(d,0);f1= 0.0;d3 = vsip_vget_f(d,1);f2= vsip_vget_f(f,0); } else { d2=vsip_vget_f(d,0);f1 = 0.0;d3 = 0.0;f2 = 0.0; } mu = svdMu_f(d2,f1,d3,f2); x1=vsip_vget_f(d,0); x2 = x1 * vsip_vget_f(f,0); x1 *= x1; x1 -= mu; g=givensCoef_f(x1,x2); x1=vsip_vget_f(d,0);x2=vsip_vget_f(f,0); vsip_vput_f(f,0,g.c * x2 - g.s * x1); vsip_vput_f(d,0,x1 * g.c + x2 * g.s); t=vsip_vget_f(d,1); vsip_vput_f(d,1,t*g.c); t*=g.s; cgtProd_f(0,1,g.c,g.s,R); for(i=0; i<n-2; i++){ j=i+1; k=i+2; g = givensCoef_f(vsip_vget_f(d,i),t); vsip_vput_f(d,i,g.r); x1=vsip_vget_f(d,j)*g.c; x2=vsip_vget_f(f,i)*g.s; t= x1 - x2; x1=vsip_vget_f(f,i) * g.c; x2=vsip_vget_f(d,j) * g.s ; vsip_vput_f(f,i,x1+x2); vsip_vput_f(d,j,t); x1=vsip_vget_f(f,j); t=g.s * x1; vsip_vput_f(f,j, x1*g.c); cprodG_f(L,i, j, g.c, g.s); g=givensCoef_f(vsip_vget_f(f,i),t); vsip_vput_f(f,i,g.r); x1=vsip_vget_f(d,j); x2=vsip_vget_f(f,j); vsip_vput_f(d,j,g.c * x1 + g.s * x2); vsip_vput_f(f,j,g.c * x2 - g.s * x1); x1=vsip_vget_f(d,k); t=g.s * x1; vsip_vput_f(d,k,x1*g.c); cgtProd_f(j,k, g.c, g.s,R); } i=n-2; j=n-1; g = givensCoef_f(vsip_vget_f(d,i),t); vsip_vput_f(d,i,g.r); x1=vsip_vget_f(d,j)*g.c; x2=vsip_vget_f(f,i)*g.s; t=x1 - x2; x1 = vsip_vget_f(f,i) * g.c; x2=vsip_vget_f(d,j) * g.s; vsip_vput_f(f,i,x1+x2); vsip_vput_f(d,j,t); cprodG_f(L,i, j, g.c, g.s); } static void svdStep_d(vsip_mview_d* L, vsip_vview_d* d, vsip_vview_d* f, vsip_mview_d *R) { givensObj_d g; vsip_length n = vsip_vgetlength_d(d); vsip_scalar_d mu=0.0, x1=0.0, x2=0.0; vsip_scalar_d t=0.0; vsip_index i,j,k; vsip_scalar_d d2,f1,d3,f2; if(n >= 3){ d2=vsip_vget_d(d,n-2);f1= vsip_vget_d(f,n-3);d3 = vsip_vget_d(d,n-1);f2= vsip_vget_d(f,n-2); } else if(n == 2){ d2=vsip_vget_d(d,0);f1= 0.0;d3 = vsip_vget_d(d,1);f2= vsip_vget_d(f,0); } else { d2=vsip_vget_d(d,0);f1 = 0.0;d3 = 0.0;f2 = 0.0; } mu = svdMu_d(d2,f1,d3,f2); x1=vsip_vget_d(d,0); x2 = x1 * vsip_vget_d(f,0); x1 *= x1; x1 -= mu; g=givensCoef_d(x1,x2); x1=vsip_vget_d(d,0);x2=vsip_vget_d(f,0); vsip_vput_d(f,0,g.c * x2 - g.s * x1); vsip_vput_d(d,0,x1 * g.c + x2 * g.s); t=vsip_vget_d(d,1); vsip_vput_d(d,1,t*g.c); t*=g.s; gtProd_d(0,1,g.c,g.s,R); for(i=0; i<n-2; i++){ j=i+1; k=i+2; g = givensCoef_d(vsip_vget_d(d,i),t); vsip_vput_d(d,i,g.r); x1=vsip_vget_d(d,j)*g.c; x2=vsip_vget_d(f,i)*g.s; t= x1 - x2; x1=vsip_vget_d(f,i) * g.c; x2=vsip_vget_d(d,j) * g.s ; vsip_vput_d(f,i,x1+x2); vsip_vput_d(d,j,t); x1=vsip_vget_d(f,j); t=g.s * x1; vsip_vput_d(f,j, x1*g.c); prodG_d(L,i, j, g.c, g.s); g=givensCoef_d(vsip_vget_d(f,i),t); vsip_vput_d(f,i,g.r); x1=vsip_vget_d(d,j); x2=vsip_vget_d(f,j); vsip_vput_d(d,j,g.c * x1 + g.s * x2); vsip_vput_d(f,j,g.c * x2 - g.s * x1); x1=vsip_vget_d(d,k); t=g.s * x1; vsip_vput_d(d,k,x1*g.c); gtProd_d(j,k, g.c, g.s,R); } i=n-2; j=n-1; g = givensCoef_d(vsip_vget_d(d,i),t); vsip_vput_d(d,i,g.r); x1=vsip_vget_d(d,j)*g.c; x2=vsip_vget_d(f,i)*g.s; t=x1 - x2; x1 = vsip_vget_d(f,i) * g.c; x2=vsip_vget_d(d,j) * g.s; vsip_vput_d(f,i,x1+x2); vsip_vput_d(d,j,t); prodG_d(L,i, j, g.c, g.s); } static void csvdStep_d(vsip_cmview_d* L, vsip_vview_d* d, vsip_vview_d* f, vsip_cmview_d *R) { givensObj_d g; vsip_length n = vsip_vgetlength_d(d); vsip_scalar_d mu=0.0, x1=0.0, x2=0.0; vsip_scalar_d t=0.0; vsip_index i,j,k; vsip_scalar_d d2,f1,d3,f2; if(n >= 3){ d2=vsip_vget_d(d,n-2);f1= vsip_vget_d(f,n-3);d3 = vsip_vget_d(d,n-1);f2= vsip_vget_d(f,n-2); } else if(n == 2){ d2=vsip_vget_d(d,0);f1= 0.0;d3 = vsip_vget_d(d,1);f2= vsip_vget_d(f,0); } else { d2=vsip_vget_d(d,0);f1 = 0.0;d3 = 0.0;f2 = 0.0; } mu = svdMu_d(d2,f1,d3,f2); x1=vsip_vget_d(d,0); x2 = x1 * vsip_vget_d(f,0); x1 *= x1; x1 -= mu; g=givensCoef_d(x1,x2); x1=vsip_vget_d(d,0);x2=vsip_vget_d(f,0); vsip_vput_d(f,0,g.c * x2 - g.s * x1); vsip_vput_d(d,0,x1 * g.c + x2 * g.s); t=vsip_vget_d(d,1); vsip_vput_d(d,1,t*g.c); t*=g.s; cgtProd_d(0,1,g.c,g.s,R); for(i=0; i<n-2; i++){ j=i+1; k=i+2; g = givensCoef_d(vsip_vget_d(d,i),t); vsip_vput_d(d,i,g.r); x1=vsip_vget_d(d,j)*g.c; x2=vsip_vget_d(f,i)*g.s; t= x1 - x2; x1=vsip_vget_d(f,i) * g.c; x2=vsip_vget_d(d,j) * g.s ; vsip_vput_d(f,i,x1+x2); vsip_vput_d(d,j,t); x1=vsip_vget_d(f,j); t=g.s * x1; vsip_vput_d(f,j, x1*g.c); cprodG_d(L,i, j, g.c, g.s); g=givensCoef_d(vsip_vget_d(f,i),t); vsip_vput_d(f,i,g.r); x1=vsip_vget_d(d,j); x2=vsip_vget_d(f,j); vsip_vput_d(d,j,g.c * x1 + g.s * x2); vsip_vput_d(f,j,g.c * x2 - g.s * x1); x1=vsip_vget_d(d,k); t=g.s * x1; vsip_vput_d(d,k,x1*g.c); cgtProd_d(j,k, g.c, g.s,R); } i=n-2; j=n-1; g = givensCoef_d(vsip_vget_d(d,i),t); vsip_vput_d(d,i,g.r); x1=vsip_vget_d(d,j)*g.c; x2=vsip_vget_d(f,i)*g.s; t=x1 - x2; x1 = vsip_vget_d(f,i) * g.c; x2=vsip_vget_d(d,j) * g.s; vsip_vput_d(f,i,x1+x2); vsip_vput_d(d,j,t); cprodG_d(L,i, j, g.c, g.s); } static void svdIteration_f(vsip_mview_f* L0, vsip_vview_f* d0, vsip_vview_f* f0, vsip_mview_f* R0, vsip_scalar_f eps0) { vsip_vview_f *d=vsip_vcloneview_f(d0); vsip_vview_f *f=vsip_vcloneview_f(f0); vsip_mview_f *L=vsip_mcloneview_f(L0); vsip_mview_f *R=vsip_mcloneview_f(R0); vsip_length n; svdCorner cnr; vsip_index k; vsip_length cntr=0; vsip_length maxcntr=20*vsip_vgetlength_f(d0); while (cntr++ < maxcntr){ phaseCheck_f(L0,d0,f0,R0,eps0); cnr=svdCorners_f(f0); if (cnr.j == 0) break; ivsv_f(d0,d,cnr.i,cnr.j); ivsv_f(f0,f,cnr.i,cnr.j-1); imsv_f(L0,L,0,0,cnr.i,cnr.j); imsv_f(R0,R,cnr.i,cnr.j,0,0); n=vsip_vgetlength_f(f); k=zeroFind_f(d,eps0); if (k > 0){ if(vsip_vget_f(d,n) == 0.0){ zeroCol_f(d,f,R); }else{ imsv_f(L,L,0,0,k-1,0); ivsv_f(d0,d,k,0); ivsv_f(f0,f,k-1,0); zeroRow_f(L,d,f); } }else{ svdStep_f(L,d,f,R); } } vsip_vdestroy_f(d); vsip_vdestroy_f(f); vsip_mdestroy_f(L); vsip_mdestroy_f(R); } static void svdIteration_d(vsip_mview_d* L0, vsip_vview_d* d0, vsip_vview_d* f0, vsip_mview_d* R0, vsip_scalar_d eps0) { vsip_vview_d *d=vsip_vcloneview_d(d0); vsip_vview_d *f=vsip_vcloneview_d(f0); vsip_mview_d *L=vsip_mcloneview_d(L0); vsip_mview_d *R=vsip_mcloneview_d(R0); vsip_length n; svdCorner cnr; vsip_index k; vsip_length cntr=0; vsip_length maxcntr=20*vsip_vgetlength_d(d0); while (cntr++ < maxcntr){ phaseCheck_d(L0,d0,f0,R0,eps0); cnr=svdCorners_d(f0); if (cnr.j == 0) break; ivsv_d(d0,d,cnr.i,cnr.j); ivsv_d(f0,f,cnr.i,cnr.j-1); imsv_d(L0,L,0,0,cnr.i,cnr.j); imsv_d(R0,R,cnr.i,cnr.j,0,0); n=vsip_vgetlength_d(f); k=zeroFind_d(d,eps0); if (k > 0){ if(vsip_vget_d(d,n) == 0.0){ zeroCol_d(d,f,R); }else{ imsv_d(L,L,0,0,k-1,0); ivsv_d(d0,d,k,0); ivsv_d(f0,f,k-1,0); zeroRow_d(L,d,f); } }else{ svdStep_d(L,d,f,R); } } vsip_vdestroy_d(d); vsip_vdestroy_d(f); vsip_mdestroy_d(L); vsip_mdestroy_d(R); } static void csvdIteration_f(vsip_cmview_f* L0, vsip_vview_f* d0, vsip_vview_f* f0, vsip_cmview_f* R0, vsip_scalar_f eps0) { vsip_vview_f *d=vsip_vcloneview_f(d0); vsip_vview_f *f=vsip_vcloneview_f(f0); vsip_cmview_f *L=vsip_cmcloneview_f(L0); vsip_cmview_f *R=vsip_cmcloneview_f(R0); vsip_length n; svdCorner cnr; vsip_index k; vsip_length cntr=0; vsip_length maxcntr=20*vsip_vgetlength_f(d0); while (cntr++ < maxcntr){ cphaseCheck_f(L0,d0,f0,R0,eps0); cnr=svdCorners_f(f0); if (cnr.j == 0) break; ivsv_f(d0,d,cnr.i,cnr.j); ivsv_f(f0,f,cnr.i,cnr.j-1); cimsv_f(L0,L,0,0,cnr.i,cnr.j); cimsv_f(R0,R,cnr.i,cnr.j,0,0); n=vsip_vgetlength_f(f); k=zeroFind_f(d,eps0); if (k > 0){ if(vsip_vget_f(d,n) == 0.0){ czeroCol_f(d,f,R); }else{ cimsv_f(L,L,0,0,k-1,0); ivsv_f(d0,d,k,0); ivsv_f(f0,f,k-1,0); czeroRow_f(L,d,f); } }else{ csvdStep_f(L,d,f,R); } } vsip_vdestroy_f(d); vsip_vdestroy_f(f); vsip_cmdestroy_f(L); vsip_cmdestroy_f(R); } static void csvdIteration_d(vsip_cmview_d* L0, vsip_vview_d* d0, vsip_vview_d* f0, vsip_cmview_d* R0, vsip_scalar_d eps0) { vsip_vview_d *d=vsip_vcloneview_d(d0); vsip_vview_d *f=vsip_vcloneview_d(f0); vsip_cmview_d *L=vsip_cmcloneview_d(L0); vsip_cmview_d *R=vsip_cmcloneview_d(R0); vsip_length n; svdCorner cnr; vsip_index k; vsip_length cntr=0; vsip_length maxcntr=20*vsip_vgetlength_d(d0); while (cntr++ < maxcntr){ cphaseCheck_d(L0,d0,f0,R0,eps0); cnr=svdCorners_d(f0); if (cnr.j == 0) break; ivsv_d(d0,d,cnr.i,cnr.j); ivsv_d(f0,f,cnr.i,cnr.j-1); cimsv_d(L0,L,0,0,cnr.i,cnr.j); cimsv_d(R0,R,cnr.i,cnr.j,0,0); n=vsip_vgetlength_d(f); k=zeroFind_d(d,eps0); if (k > 0){ if(vsip_vget_d(d,n) == 0.0){ czeroCol_d(d,f,R); }else{ cimsv_d(L,L,0,0,k-1,0); ivsv_d(d0,d,k,0); ivsv_d(f0,f,k-1,0); czeroRow_d(L,d,f); } }else{ csvdStep_d(L,d,f,R); } } vsip_vdestroy_d(d); vsip_vdestroy_d(f); vsip_cmdestroy_d(L); vsip_cmdestroy_d(R); } static void svdSort_f(vsip_mview_f* L0,vsip_vview_f* d,vsip_mview_f* R0){ vsip_length n=vsip_vgetlength_f(d); vsip_vview_vi* indx_L = vsip_vcreate_vi(n,VSIP_MEM_NONE); vsip_vview_vi* indx_R = vsip_vcreate_vi(n,VSIP_MEM_NONE); vsip_mview_f *L=vsip_mcloneview_f(L0); vsip_vsortip_f(d,VSIP_SORT_BYVALUE,VSIP_SORT_DESCENDING,VSIP_TRUE,indx_L); vsip_vcopy_vi_vi(indx_L,indx_R); imsv_f( L0, L, 0,0, 0, n); vsip_mpermute_once_f(L,VSIP_COL,indx_L,L); vsip_mpermute_once_f(R0,VSIP_ROW,indx_R,R0); vsip_valldestroy_vi(indx_L); vsip_valldestroy_vi(indx_R); vsip_mdestroy_f(L); } static void csvdSort_f(vsip_cmview_f* L0,vsip_vview_f* d,vsip_cmview_f* R0){ vsip_length n=vsip_vgetlength_f(d); vsip_vview_vi* indx_L = vsip_vcreate_vi(n,VSIP_MEM_NONE); vsip_vview_vi* indx_R = vsip_vcreate_vi(n,VSIP_MEM_NONE); vsip_cmview_f *L=vsip_cmcloneview_f(L0); vsip_vsortip_f(d,VSIP_SORT_BYVALUE,VSIP_SORT_DESCENDING,VSIP_TRUE,indx_L); vsip_vcopy_vi_vi(indx_L,indx_R); cimsv_f( L0, L, 0,0, 0, n); vsip_cmpermute_once_f(L,VSIP_COL,indx_L,L); vsip_cmpermute_once_f(R0,VSIP_ROW,indx_R,R0); vsip_valldestroy_vi(indx_L); vsip_valldestroy_vi(indx_R); vsip_cmdestroy_f(L); } static void svdSort_d(vsip_mview_d* L0,vsip_vview_d* d,vsip_mview_d* R0){ vsip_length n=vsip_vgetlength_d(d); vsip_vview_vi* indx_L = vsip_vcreate_vi(n,VSIP_MEM_NONE); vsip_vview_vi* indx_R = vsip_vcreate_vi(n,VSIP_MEM_NONE); vsip_mview_d *L=vsip_mcloneview_d(L0); vsip_vsortip_d(d,VSIP_SORT_BYVALUE,VSIP_SORT_DESCENDING,VSIP_TRUE,indx_L); vsip_vcopy_vi_vi(indx_L,indx_R); imsv_d( L0, L, 0,0, 0, n); vsip_mpermute_once_d(L,VSIP_COL,indx_L,L); vsip_mpermute_once_d(R0,VSIP_ROW,indx_R,R0); vsip_valldestroy_vi(indx_L); vsip_valldestroy_vi(indx_R); vsip_mdestroy_d(L); } static void csvdSort_d(vsip_cmview_d* L0,vsip_vview_d* d,vsip_cmview_d* R0){ vsip_length n=vsip_vgetlength_d(d); vsip_vview_vi* indx_L = vsip_vcreate_vi(n,VSIP_MEM_NONE); vsip_vview_vi* indx_R = vsip_vcreate_vi(n,VSIP_MEM_NONE); vsip_cmview_d *L=vsip_cmcloneview_d(L0); vsip_vsortip_d(d,VSIP_SORT_BYVALUE,VSIP_SORT_DESCENDING,VSIP_TRUE,indx_L); vsip_vcopy_vi_vi(indx_L,indx_R); cimsv_d( L0, L, 0,0, 0, n); vsip_cmpermute_once_d(L,VSIP_COL,indx_L,L); vsip_cmpermute_once_d(R0,VSIP_ROW,indx_R,R0); vsip_valldestroy_vi(indx_L); vsip_valldestroy_vi(indx_R); vsip_cmdestroy_d(L); } svdObj_f svd_f(vsip_mview_f *A){ svdObj_f svd = svdBidiag_f(A); svdIteration_f(svd.L,svd.d,svd.f,svd.R,svd.eps0); svdSort_f(svd.L,svd.d,svd.R); return svd; } csvdObj_f csvd_f(vsip_cmview_f *A){ csvdObj_f svd = csvdBidiag_f(A); csvdIteration_f(svd.L,svd.d,svd.f,svd.R,svd.eps0); csvdSort_f(svd.L,svd.d,svd.R); return svd; } svdObj_d svd_d(vsip_mview_d *A){ svdObj_d svd = svdBidiag_d(A); svdIteration_d(svd.L,svd.d,svd.f,svd.R,svd.eps0); svdSort_d(svd.L,svd.d,svd.R); return svd; } csvdObj_d csvd_d(vsip_cmview_d *A){ csvdObj_d svd = csvdBidiag_d(A); csvdIteration_d(svd.L,svd.d,svd.f,svd.R,svd.eps0); csvdSort_d(svd.L,svd.d,svd.R); return svd; } <file_sep>/* Created RJudd March 18, 2012 */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"vsip.h" #include"vsip_mviewattributes_f.h" #include"vsip_vviewattributes_f.h" #include"vsip_cmviewattributes_f.h" #include"vsip_cvviewattributes_f.h" #include"vsip_scalars.h" #include"VI_mrowview_f.h" #include"VI_mcolview_f.h" #include"VI_cmrowview_f.h" #include"VI_cmcolview_f.h" static void vrect_f(vsip_vview_f* r, vsip_vview_f* t, vsip_cvview_f* a) { vsip_length n = r->length; vsip_stride cast = a->block->cstride, rrst = r->block->rstride, trst = r->block->rstride; vsip_scalar_f *apr = (vsip_scalar_f*) ((a->block->R->array) + cast * a->offset), *rp = (vsip_scalar_f*) ((r->block->array) + rrst * r->offset), *tp = (vsip_scalar_f*) ((t->block->array) + trst * t->offset); vsip_scalar_f *api = (vsip_scalar_f*) ((a->block->I->array) + cast * a->offset); vsip_scalar_f temp = 0; vsip_stride ast = cast * a->stride, rst = rrst * r->stride, tst = trst * t->stride; while(n-- > 0){ temp = *rp * VSIP_SIN_D(*tp); *apr = *rp * VSIP_COS_D(*tp); *api = temp; apr += ast; api += ast; rp += rst; tp += tst; } } void vsip_mrect_f( const vsip_mview_f* r, const vsip_mview_f *t, const vsip_cmview_f* a){ vsip_index i; vsip_vview_f rv; vsip_vview_f tv; vsip_cvview_f av; if(a->row_stride < a->col_stride){ for(i=0; i < a->col_length; i++){ VI_mrowview_f(r,i,&rv); VI_mrowview_f(t,i,&tv);VI_cmrowview_f(a,i,&av); vrect_f(&rv,&tv,&av); } } else { for(i=0; i < a->col_length; i++){ VI_mcolview_f(r,i,&rv); VI_mcolview_f(t,i,&tv);VI_cmcolview_f(a,i,&av); vrect_f(&rv,&tv,&av); } } } <file_sep>from vsip import * def __isSizeCompatible(a,b): if 'mview' in a.type and 'mview' in b.type: if (a.rowlength == b.rowlength) and (a.collength == b.collength): return True elif 'vview' in a.type and 'vview' in b.type: if a.length == b.length: return True else: return False # DON'T know how to implement yet # vsip_svfirst_p # Functions that return a value are only supported as properties on views # vsip_scminmgsqval_p # vsip_sminmgval_p # vsip_sminval_p # vsip_scmaxmgsqval_p # vsip_smaxmgval_p # vsip_smaxval_p # vsip_sclip_p def clip(a,t1,t2,c1,c2,r): """ Function clip may be done in-place """ f={'mview_d':vsip_mclip_d, 'mview_f':vsip_mclip_f, 'mview_i':vsip_mclip_i, 'mview_si':vsip_mclip_si, 'vview_d':vsip_vclip_d, 'vview_f':vsip_vclip_f, 'vview_i':vsip_vclip_i, 'vview_si':vsip_vclip_si, 'vview_uc':vsip_vclip_uc} assert 'pyJvsip' in repr(a),\ 'Argument one must be a pyJvsip view object in clip' assert 'pyJvsip' in repr(r),\ 'Argument six must be a pyJvsip view object in clip' assert a.type == r.type,'Input and output views for clip must be the same type' assert __isSizeCompatible(a,r),'Input and output views for clip must be the same size' assert a.type in f,'Type <:'+a.type+':> not supported for clip' assert isinstance(t1,int) or isinstance(t1,float) assert isinstance(t2,int) or isinstance(t2,float) assert isinstance(c1,int) or isinstance(c1,float) assert isinstance(c2,int) or isinstance(c2,float) f[a.type](a.vsip,t1,t2,c1,c2,r.vsip) return r # vsip_sinvclip_p def invclip(a,t1,t2,t3,c1,c2,r): """ Function invclip may be done in-place """ f={'mview_d':vsip_minvclip_d, 'mview_f':vsip_minvclip_f, 'vview_d':vsip_vinvclip_d, 'vview_f':vsip_vinvclip_f, 'vview_i':vsip_vinvclip_i, 'vview_si':vsip_vinvclip_si, 'vview_uc':vsip_vinvclip_uc} assert 'pyJvsip' in repr(a),\ 'Argument one must be a pyJvsip view object in invclip' assert 'pyJvsip' in repr(r),\ 'Argument seven must be a pyJvsip view object in invclip' assert a.type == r.type,'Input and output views for invclip must be the same type' assert __isSizeCompatible(a,r),'Input and output views for invclip must be the same size' assert a.type in f,'Type <:'+a.type+':> not supported for invclip' assert isinstance(t1,int) or isinstance(t1,float) assert isinstance(t2,int) or isinstance(t2,float) assert isinstance(t3,int) or isinstance(t3,float) assert isinstance(c1,int) or isinstance(c1,float) assert isinstance(c2,int) or isinstance(c2,float) f[a.type](a.vsip,t1,t2,t3,c1,c2,r.vsip) return r # vsip_sindexbool def indexbool(a,b): """ Ussage: L=indexbool(a,b): Where a is a vector or matrix view of type _bl b is a vector of type _vi if a is a vector and _mi if a is a matrix Returns L is a length indicating number of non-false entries in input view a See VSIPL specification for more details. """ f={'mview_blvview_mi':vsip_mindexbool, 'vview_blvview_vi':vsip_vindexbool } assert 'pyJvsip' in repr(a),\ 'Argument one must be a pyJvsip view object in indexbool' assert 'pyJvsip' in repr(b),\ 'Argument two must be a pyJvsip view object in indexbool' t=a.type+b.type assert t in f,'Type <:'+t+':> not supported by indexbool' return f[t](a.vsip,b.vsip) # vsip_smax_p def max(a,b,c): """ """ f={'mview_dmview_dmview_d':vsip_mmax_d, 'mview_fmview_fmview_f':vsip_mmax_f, 'vview_dvview_dvview_d':vsip_vmax_d, 'vview_fvview_fvview_f':vsip_vmax_f} assert 'pyJvsip' in repr(a),\ 'Argument one must be a pyJvsip view object in max' assert 'pyJvsip' in repr(a),\ 'Argument two must be a pyJvsip view object in max' assert 'pyJvsip' in repr(a),\ 'Argument three must be a pyJvsip view object in max' assert __isSizeCompatible(a,b) and __isSizeCompatible(a,c),\ 'Size error in max' t=a.type+b.type+c.type assert t in f,'Type <:'+t+':> not supported by max' f[t](a.vsip,b.vsip,c.vsip) return c # vsip_smaxmg_p def maxmg(a,b,c): """ """ f={'mview_dmview_dmview_d':vsip_mmaxmg_d, 'mview_fmview_fmview_f':vsip_mmaxmg_f, 'vview_dvview_dvview_d':vsip_vmaxmg_d, 'vview_fvview_fvview_f':vsip_vmaxmg_f} assert 'pyJvsip' in repr(a),\ 'Argument one must be a pyJvsip view object in maxmg' assert 'pyJvsip' in repr(b),\ 'Argument two must be a pyJvsip view object in maxmg' assert 'pyJvsip' in repr(c),\ 'Argument three must be a pyJvsip view object in maxmg' assert __isSizeCompatible(a,b) and __isSizeCompatible(a,c),\ 'Size error in maxmg' t=a.type+b.type+c.type assert t in f,'Type <:'+t+':> not supported by maxmg' f[t](a.vsip,b.vsip,c.vsip) return c # vsip_scmaxmgsq_p def cmaxmgsq(a,b,c): """ """ f={'cmview_dcmview_dmview_d':vsip_mcmaxmgsq_d, 'cmview_fcmview_fmview_f':vsip_mcmaxmgsq_f, 'cvview_dcvview_dvview_d':vsip_vcmaxmgsq_d, 'cvview_fcvview_fvview_f':vsip_vcmaxmgsq_f} assert 'pyJvsip' in repr(a),\ 'Argument one must be a pyJvsip view object in cmaxmgsq' assert 'pyJvsip' in repr(b),\ 'Argument two must be a pyJvsip view object in cmaxmgsq' assert 'pyJvsip' in repr(c),\ 'Argument three must be a pyJvsip view object in cmaxmgsq' assert __isSizeCompatible(a,b) and __isSizeCompatible(a,c),\ 'Size error in cmaxmgsq' t=a.type+b.type+c.type assert t in f,'Type <:'+t+':> not supported by cmaxmgsq' f[t](a.vsip,b.vsip,c.vsip) return c # vsip_smin_p def min(a,b,c): """ """ f={'mview_dmview_dmview_d':vsip_mmin_d, 'mview_fmview_fmview_f':vsip_mmin_f, 'vview_dvview_dvview_d':vsip_vmin_d, 'vview_fvview_fvview_f':vsip_vmin_f} assert 'pyJvsip' in repr(a),\ 'Argument one must be a pyJvsip view object in min' assert 'pyJvsip' in repr(b),\ 'Argument two must be a pyJvsip view object in min' assert 'pyJvsip' in repr(c),\ 'Argument three must be a pyJvsip view object in min' assert __isSizeCompatible(a,b) and __isSizeCompatible(a,c),\ 'Size error in min' t=a.type+b.type+c.type assert t in f,'Type <:'+t+':> not supported by min' f[t](a.vsip,b.vsip,c.vsip) return c # vsip_sminmg_p def minmg(a,b,c): """ """ f={'mview_dmview_dmview_d':vsip_mminmg_d, 'mview_fmview_fmview_f':vsip_mminmg_f, 'vview_dvview_dvview_d':vsip_vminmg_d, 'vview_fvview_fvview_f':vsip_vminmg_f} assert 'pyJvsip' in repr(a),\ 'Argument one must be a pyJvsip view object in minmg' assert 'pyJvsip' in repr(b),\ 'Argument two must be a pyJvsip view object in minmg' assert 'pyJvsip' in repr(c),\ 'Argument three must be a pyJvsip view object in minmg' assert __isSizeCompatible(a,b) and __isSizeCompatible(a,c),\ 'Size error in minmg' t=a.type+b.type+c.type assert t in f,'Type <:'+t+':> not supported by minmg' f[t](a.vsip,b.vsip,c.vsip) return c # vsip_scminmgsq_p def cminmgsq(a,b,c): """ """ f={'cmview_dcmview_dmview_d':vsip_mcminmgsq_d, 'cmview_fcmview_fmview_f':vsip_mcminmgsq_f, 'cvview_dcvview_dvview_d':vsip_vcminmgsq_d, 'cvview_fcvview_fvview_f':vsip_vcminmgsq_f} assert 'pyJvsip' in repr(a),\ 'Argument one must be a pyJvsip view object in cminmgsq' assert 'pyJvsip' in repr(b),\ 'Argument two must be a pyJvsip view object in cminmgsq' assert 'pyJvsip' in repr(c),\ 'Argument three must be a pyJvsip view object in cminmgsq' assert __isSizeCompatible(a,b) and __isSizeCompatible(a,c),\ 'Size error in minmgsq' t=a.type+b.type+c.type assert t in f,'Type <:'+t+':> not supported by cminmgsq' f[t](a.vsip,b.vsip,c.vsip) return c <file_sep>import Foundation import vsip public class TimeSeries{ public let Fs: Double public let c: Double public let Dsens: Double public let Nsens: Int public let Nsim_noise: Int public let Nsim: Int public let Nts: Int public var fir: OpaquePointer? public var noise: OpaquePointer? public var bl_noise: OpaquePointer? public var rand: OpaquePointer? public var t: OpaquePointer? public var t_dt: OpaquePointer? public var m_data: OpaquePointer? public var v_data: OpaquePointer? public var freqs: [Double] = [] public var bearings: [Double] = [] public var d_t: Double { return self.Dsens/self.c } public init(param: Param) { var tL = 2.0 * param.Fs! tL /= Double(param.Nsens!) * param.Dsens!/param.c! tL += Double(param.Nts! + 1) let L = Int(2 * tL) self.Nsim = param.Nsim! self.freqs = param.freqs self.bearings = param.bearings self.Nts = param.Nts! self.Nsens = param.Nsens! self.c = param.c! self.Dsens = param.Dsens! self.Nsim_noise=param.Nsim_noise! self.Fs = param.Fs! if let kernel = vsip_vcreate_kaiser_d(6,1,VSIP_MEM_NONE){ if let t = vsip_fir_create_d(kernel,VSIP_NONSYM, vsip_length(L) , 2 , VSIP_STATE_SAVE,0,VSIP_ALG_TIME){ self.fir = t } if let t = vsip_vcreate_d(vsip_length(L),VSIP_MEM_NONE){ self.noise = t } if let t = vsip_vcreate_d(vsip_length(Int(tL)),VSIP_MEM_NONE) { self.bl_noise = t } if let t = vsip_randcreate(7,1,1,VSIP_PRNG) { self.rand = t } if let t = vsip_vcreate_d(vsip_length(param.Nts!),VSIP_MEM_NONE) { self.t = t } if let t = vsip_vcreate_d(vsip_length(param.Nts!),VSIP_MEM_NONE) { self.t_dt = t let step = 1.0 / param.Fs! vsip_vramp_d(0.0,step,self.t); } if let t = vsip_mcreate_d(vsip_length(param.Nsens!),vsip_length(param.Nts!),VSIP_ROW,VSIP_MEM_NONE) { self.m_data = t if let t = vsip_mrowview_d(self.m_data,0){ self.v_data = t } } vsip_valldestroy_d(kernel) } } deinit { vsip_fir_destroy_d(self.fir); vsip_valldestroy_d(self.noise); vsip_valldestroy_d(self.bl_noise); vsip_randdestroy(self.rand); vsip_valldestroy_d(self.t); vsip_valldestroy_d(self.t_dt); vsip_vdestroy_d(self.v_data); vsip_malldestroy_d(self.m_data); } public func zero(){ vsip_mfill_d(0.0,m_data) } public func rowview(_ i: Int){ var mattr: vsip_mattr_d = vsip_mattr_d() var vattr: vsip_vattr_d = vsip_vattr_d() vsip_mgetattrib_d(m_data,&mattr) vattr.offset = vsip_offset(Int(mattr.offset) + i * Int(mattr.col_stride)) vattr.length = mattr.row_length vattr.stride = mattr.row_stride vsip_vputattrib_d(v_data,&vattr) } public func nb_sim(){ let d_t = self.d_t for i in 0..<Nsim { let f = freqs[i] let b = d_t * cos(bearings[i] * Double.pi/180) for j in 0..<Nsens { let dt = Double(j) * b vsip_svadd_d(dt,t,t_dt) vsip_svmul_d(2.0 * Double.pi * f,t_dt,t_dt) vsip_vcos_d(t_dt,t_dt) vsip_svmul_d(3.0,t_dt,t_dt) rowview(j); vsip_vadd_d(t_dt,v_data,v_data); } // next sensor } // next bearing } public func noise_sim(){ let d_t = Fs * self.d_t let o_0 = d_t * Double(Nsens) + 1.0 let a_stp = Double.pi / Double(self.Nsim_noise) var bl_attr: vsip_vattr_d = vsip_vattr_d() vsip_vgetattrib_d(bl_noise,&bl_attr) for j in 0..<Nsim_noise { let a_crct = cos(Double(j) * a_stp) vsip_vrandn_d(rand,noise); vsip_firflt_d(fir,noise,bl_noise); vsip_svmul_d(12.0/Double(Nsim_noise),bl_noise,bl_noise); vsip_vputlength_d(bl_noise,vsip_length(Nts)) for i in 0..<Nsens { let index = vsip_index(o_0 + Double(i) * d_t * a_crct) vsip_vputoffset_d(bl_noise, index) rowview(i) vsip_vadd_d(bl_noise,v_data,v_data); } vsip_vputattrib_d(bl_noise,&bl_attr); } vsip_smadd_d(-vsip_mmeanval_d(m_data),m_data,m_data); } public func instance() -> OpaquePointer { return self.m_data! } } <file_sep>/* Created R Judd */ /* Copyright (c) 2006 <NAME> */ /* MIT style license, see Copyright notice in top level directory */ /* $Id: toeplitz_f.h,v 1.1 2006/05/16 16:45:18 judd Exp $ */ #include"VU_vprintm_f.include" static void toeplitz_f(void) { vsip_mview_f *A = vsip_mcreate_f(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *B = vsip_mcreate_f(4,1,VSIP_ROW,VSIP_MEM_NONE); vsip_vview_f *b = vsip_mcolview_f(B,0); vsip_vview_f *t = vsip_vcreate_f(4,VSIP_MEM_NONE), *x = vsip_vcreate_f(4,VSIP_MEM_NONE), *w = vsip_vcreate_f(4,VSIP_MEM_NONE), *y = vsip_vcreate_f(4,VSIP_MEM_NONE); printf("********\nTEST toeplitz_f\n"); printf("\nTest toeplitz_f\n"); vsip_vput_f(t,(vsip_index)0,(vsip_scalar_f)5.0); vsip_vput_f(t,(vsip_index)1,(vsip_scalar_f)0.5); vsip_vput_f(t,(vsip_index)2,(vsip_scalar_f)0.2); vsip_vput_f(t,(vsip_index)3,(vsip_scalar_f)0.1); vsip_vput_f(y,(vsip_index)0,(vsip_scalar_f)4.0); vsip_vput_f(y,(vsip_index)1,(vsip_scalar_f)-1.0); vsip_vput_f(y,(vsip_index)2,(vsip_scalar_f)3.0); vsip_vput_f(y,(vsip_index)3,(vsip_scalar_f)-2.0); /* place full (lower diagonal part) matrix in A */ vsip_mput_f(A,0,0,vsip_vget_f(t,0)); vsip_mput_f(A,1,0,vsip_vget_f(t,1)); vsip_mput_f(A,1,1,vsip_vget_f(t,0)); vsip_mput_f(A,2,0,vsip_vget_f(t,2)); vsip_mput_f(A,2,1,vsip_vget_f(t,1)); vsip_mput_f(A,2,2,vsip_vget_f(t,0)); vsip_mput_f(A,3,0,vsip_vget_f(t,3)); vsip_mput_f(A,3,1,vsip_vget_f(t,2)); vsip_mput_f(A,3,2,vsip_vget_f(t,1)); vsip_mput_f(A,3,3,vsip_vget_f(t,0)); /* place y in B */ vsip_vcopy_f_f(y,b); /* solve using cholesky */ { vsip_chol_f *chol = vsip_chold_create_f(VSIP_TR_LOW,4); vsip_chold_f(chol,A); vsip_cholsol_f(chol,B); vsip_chold_destroy_f(chol); } printf("the solution using cholesky is\n"); VU_vprintm_f("7.5",b); printf("t=\n");VU_vprintm_f("6.4",t); printf("y=\n");VU_vprintm_f("6.4",y); vsip_toepsol_f(t,y,w,x); printf("t=\n");VU_vprintm_f("6.4",t); printf("y=\n");VU_vprintm_f("6.4",y); printf("w=\n");VU_vprintm_f("6.4",w); printf("the solution using toeplitz is\n"); printf("x=\n");VU_vprintm_f("6.4",x); vsip_vsub_f(x,b,b); if(fabs(vsip_vsumval_f(b)) < .00001) printf("\ncorrect\n"); else printf("\nerror\n"); vsip_valldestroy_f(t); vsip_valldestroy_f(x); vsip_valldestroy_f(w); vsip_valldestroy_f(y); vsip_malldestroy_f(A); vsip_vdestroy_f(b); vsip_malldestroy_f(B); } <file_sep>/* Created RJudd November 2, 2002 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_cblockbind_d_as.h,v 2.0 2003/02/22 15:18:28 judd Exp $ */ /* VI_cblockbind_d always split */ if(b != (vsip_cblock_d*)NULL){ b->r_data = (vsip_scalar_d*)malloc( N * sizeof(vsip_scalar_d)); b->i_data = (vsip_scalar_d*)malloc( N * sizeof(vsip_scalar_d)); b->R = vsip_blockbind_d((vsip_scalar_d*)NULL,N,h); b->I = vsip_blockbind_d((vsip_scalar_d*)NULL,N,h); if( (b->r_data == NULL) || (b->i_data == NULL) || (b->R == (vsip_block_d*)NULL) || (b->I == (vsip_block_d*)NULL) ) { /* malloc problems, cleanup & exit */ if(b->r_data != NULL) free(b->r_data); if(b->i_data != NULL) free(b->i_data); if(b->R != NULL) free(b->R); if(b->I != NULL) free(b->I); free(b); b = (vsip_cblock_d*)NULL; } else { b->size = N; b->kind = VSIP_USER_BLOCK; b->admit = VSIP_RELEASED_BLOCK; b->markings = VSIP_VALID_STRUCTURE_OBJECT; b->bindings = 0; b->Rp = Rp; b->Ip = Ip; b->cstride = 1; /* set up derived blocks */ b->R->kind = VSIP_DERIVED_BLOCK; b->I->kind = VSIP_DERIVED_BLOCK; b->R->rstride = b->cstride; b->I->rstride = b->cstride; b->R->parent = b; b->I->parent = b; } } <file_sep>/* Created by RJudd June 13, 2002 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_rcfftop_d_fftw.h,v 2.0 2003/02/22 15:18:33 judd Exp $ */ #ifndef _VI_RCFFTOP_D_FFTW_H #define _VI_RCFFTOP_D_FFTW_H #include"VI_fftw_obj.h" /* Note x and z must be unit stride */ /* This is required by the specification */ void vsip_rcfftop_d( const vsip_fft_d *Offt, const vsip_vview_d *x, const vsip_cvview_d *z) { vsip_fft_d Nfft = *Offt; vsip_fft_d *fft = &Nfft; vsipl_fftw_obj *obj = (vsipl_fftw_obj*)fft->ext_fft_obj; vsip_length n = fft->N; vsip_scalar_d scale = .5 * fft->scale; /* Get phase shift pointers */ vsip_cvview_d *w = fft->temp; vsip_stride w_str = w->stride * w->block->R->rstride; vsip_scalar_d *wr = w->block->R->array + w->offset * w->block->R->rstride; vsip_scalar_d *wi = w->block->I->array + w->offset * w->block->I->rstride; /* view stride should always be 1 so memory stride is just block stride */ vsip_stride z_str = z->block->R->rstride * z->stride; vsip_stride x_str = x->block->rstride * x->stride; vsip_offset offset = (vsip_offset)(z->offset * z->block->R->rstride); #if defined(VSIP_ASSUME_COMPLEX_IS_INTERLEAVED) /* do top and bottom together stop in the middle */ vsip_length n_end = (vsip_length)(fft->N/2); /* offsets into memory of z data */ vsip_offset offset_end = (vsip_offset)((z->offset + n) * z->block->R->rstride); /* begining of output; go through forward */ vsip_scalar_d *fr = z->block->R->array + offset; vsip_scalar_d *fi = z->block->I->array + offset; /* end of output; go through backward */ vsip_scalar_d *br = z->block->R->array + offset_end; vsip_scalar_d *bi = z->block->I->array + offset_end; /* Need some temporary storage */ vsip_scalar_d temp1,temp2,temp3; /* make a pointer to use in fftw. Here is where interleaved is assumed */ fftw_complex *in = (fftw_complex*)(x->block->array + x->offset * x_str); fftw_complex *out = (fftw_complex*)fr; /* do the fft; note stride is one so use fftw_one */ fftw_one(obj->p,in,out); /* sort things out */ /* do the final point */ *br = fft->scale * (*fr - *fi); *bi = 0; /* do the zero point */ *fr = fft->scale * (*fr + *fi); *fi = 0; n = fft->N; /* do all others */ while(n-- > n_end + 1){ wr += w_str; wi += w_str; fr += z_str; fi += z_str; br -= z_str; bi -= z_str; temp1 = scale * (*fr + *br + *wr * (*fi + *bi) - *wi * (*fr - *br)); temp2 = scale * (*br + *fr - *wr * (*bi + *fi) - *wi * (*br - *fr)); temp3 = scale * (*fi - *bi - *wr * (*fr - *br) - *wi * (*fi + *bi)); *bi = scale * (*bi - *fi + *wr * (*br - *fr) - *wi * (*bi + *fi)); *br = temp2; *fi = temp3; *fr = temp1; } if(!(fft->N % 2)){ /* do the odd middle point */ fr += z_str; fi += z_str; *fr = fft->scale * *fr; *fi = -fft->scale * *fi; } #else /* get the pointer to the real and imaginary part of output */ vsip_scalar_d *zptr_r = z->block->R->array + offset; vsip_scalar_d *zptr_i = z->block->I->array + offset; /* get the pointer to the input data */ vsip_scalar_d *xptr = x->block->array + x_str * x->offset; /* pointers for use with fftw */ fftw_complex *ptr = obj->in,*f,*b; /* copy the data from the input vector to fftw data buffer */ while(n-- > 0){ (*ptr).re = (fftw_real)*xptr; xptr += x_str; (*ptr).im = (fftw_real)*xptr; ptr++; xptr += x_str; } /* do the fft */ fftw_one(obj->p,obj->in,obj->out); /* do sorting work here */ /* reset our counter */ n = fft->N; /* pointer to begining of fftw output */ f = &(obj->out[0]); /* pointer to end of fftw output */ b = &(obj->out[fft->N-1]); /* calculate the zero point */ *zptr_r = fft->scale * ((vsip_scalar_d)(*f).re + (vsip_scalar_d)(*f).im); *zptr_i = 0; zptr_r += z_str; zptr_i += z_str; wr += w_str; wi += w_str; f++; /* do all others EXCEPT the final point */ while(n-- > 1){ *zptr_r = scale * ((vsip_scalar_d)(*f).re + (vsip_scalar_d)(*b).re + *wr * ((vsip_scalar_d)(*f).im + (vsip_scalar_d)(*b).im) - *wi * ((vsip_scalar_d)(*f).re - (vsip_scalar_d)(*b).re)); *zptr_i = scale * ((vsip_scalar_d)(*f).im - (vsip_scalar_d)(*b).im - *wr * ((vsip_scalar_d)(*f).re - (vsip_scalar_d)(*b).re) - *wi * ((vsip_scalar_d)(*f).im + (vsip_scalar_d)(*b).im)); zptr_r += z_str; zptr_i += z_str; wr += w_str; wi += w_str; b--; f++; } /* do the final point */ *zptr_r = fft->scale * ((vsip_scalar_d)(*b).re - (vsip_scalar_d)(*b).im); *zptr_i = 0; #endif return; } #endif /* _VI_RCFFTOP_D_FFTW_H */ <file_sep>/* Created RJudd December 30, 1997 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cvmag_f.c,v 2.0 2003/02/22 15:18:51 judd Exp $ */ /* Modified RJudd June 28, 1998 */ /* to add complex block support */ /* Removed Development Mode RJudd Sept 00 */ #include"vsip.h" #include"vsip_vviewattributes_f.h" #include"vsip_cvviewattributes_f.h" void (vsip_cvmag_f)( const vsip_cvview_f* a, const vsip_vview_f* r) { { /* register */ vsip_length n = r->length; vsip_scalar_f s,ss; vsip_stride cast = a->block->cstride; vsip_scalar_f *ap_r = (vsip_scalar_f*) ((a->block->R->array) + cast * a->offset), *rp = (vsip_scalar_f*) ((r->block->array) + r->offset * r->block->rstride); vsip_scalar_f *ap_i = (vsip_scalar_f*) ((a->block->I->array) + cast * a->offset); /* register */ vsip_stride ast = (cast * a->stride), rst = r->stride * r->block->rstride; while(n-- > 0){ s = (vsip_scalar_f)((*ap_r > 0) ? *ap_r: -*ap_r) + ((*ap_i >0) ? *ap_i: -*ap_i); ss = s * s; if(ss == 0){ *rp = 0; } else { *rp = s * (vsip_scalar_f)sqrt((*ap_r * *ap_r)/ss + (*ap_i * *ap_i)/ss); } ap_r += ast; ap_i += ast; rp += rst; } } } <file_sep>/* Created RJudd January 27, 1999 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_gemp_d.c,v 2.3 2008/03/03 18:36:36 judd Exp $ */ #include"vsip_mviewattributes_d.h" #include"vsip_vviewattributes_d.h" #include"vsip.h" #define VI_GEMP_jki_D {\ vsip_scalar_d *ap_ik = ap0, *ap_0k = ap0;\ vsip_scalar_d *bp_kj = bp0, *bp_0j = bp0;\ vsip_scalar_d *rp_ij = rp0, *rp_0j = rp0;\ if(b1 != 1.0) vsip_smmul_d(b1,r,r);\ while(r_r_l-- > 0){ /* j */\ rp_ij = rp_0j;\ bp_kj = bp_0j;\ while(a_r_l-- > 0){ /* k */\ b_scalar = a1 * *bp_kj;\ bp_kj += b_st_c;\ ap_ik = ap_0k;\ while(a_c_l-- > 0){ /* i */\ *rp_ij = *ap_ik * b_scalar + *rp_ij;\ rp_ij += r_st_c;\ ap_ik += a_st_c;\ } a_c_l = a->col_length;\ ap_0k += a_st_r;\ rp_ij = rp_0j;\ } a_r_l = a->row_length;\ rp_0j += r_st_r;\ bp_0j += b_st_r;\ ap_0k = ap0;\ }} #define VI_GEMP_ijk_D { \ vsip_scalar_d *ap_ik = ap0, *ap_i0 = ap0;\ vsip_scalar_d *bp_kj = bp0, *bp_0j = bp0;\ vsip_scalar_d *rp_ij = rp0, *rp_i0 = rp0;\ while(a_c_l-- > 0){ /* i */\ rp_ij = rp_i0;\ bp_0j = bp0;\ while(r_r_l-- > 0){ /* j */\ ap_ik = ap_i0;\ temp = 0;\ bp_kj = bp_0j;\ while(a_r_l-- > 0){ /* k */\ temp += *ap_ik * *bp_kj;\ ap_ik += a_st_r;\ bp_kj += b_st_c;\ } a_r_l = a->row_length;\ *rp_ij = b1 * *rp_ij + a1 * temp;\ rp_ij += r_st_r;\ bp_0j += b_st_r;\ } r_r_l = r->row_length;\ rp_i0 += r_st_c;\ ap_i0 += a_st_c;\ }} #define VI_GEMP_ikj_D {\ vsip_scalar_d *ap_ik = ap0, *ap_i0 = ap0;\ vsip_scalar_d *bp_kj = bp0, *bp_k0 = bp0;\ vsip_scalar_d *rp_ij = rp0, *rp_i0 = rp0;\ if(b1 != 1.0) vsip_smmul_d(b1,r,r);\ while(a_c_l-- > 0){ /* i */\ ap_ik = ap_i0;\ while(a_r_l-- > 0){ /* k */\ a_scalar = a1 * *ap_ik;\ ap_ik += a_st_r;\ bp_kj = bp_k0;\ rp_ij = rp_i0;\ while(r_r_l-- > 0){ /* j */\ *rp_ij = *bp_kj * a_scalar + *rp_ij;\ rp_ij += r_st_r;\ bp_kj += b_st_r;\ } r_r_l = r->row_length;\ bp_k0 += b_st_c;\ }a_r_l = a->row_length;\ bp_k0 = bp0;\ rp_i0 += r_st_c;\ ap_i0 += a_st_c;\ }} void vsip_gemp_d(vsip_scalar_d alpha, const vsip_mview_d *AA, vsip_mat_op OpA, const vsip_mview_d *BB, vsip_mat_op OpB, vsip_scalar_d beta, const vsip_mview_d *r){ register vsip_scalar_d a1 = alpha; register vsip_scalar_d b1 = beta; vsip_mview_d At = *AA, Bt = *BB; vsip_mview_d *a = &At, *b = &Bt; if(OpA == VSIP_MAT_TRANS){ a->row_length = AA->col_length; a->col_length = AA->row_length; a->row_stride = AA->col_stride; a->col_stride = AA->row_stride; } if(OpB == VSIP_MAT_TRANS){ b->row_length = BB->col_length; b->col_length = BB->row_length; b->row_stride = BB->col_stride; b->col_stride = BB->row_stride; } { /* c => column major, r => row major */ /* decide if ccc => 0 ccr=> 1, crc => 2, etc to rrr => 7 */ unsigned method = (unsigned)(r->row_stride <= r->col_stride) + (unsigned)(b->row_stride <= b->col_stride) * 2 + (unsigned)(a->row_stride <= a->col_stride) * 4; vsip_stride a_st_r = a->row_stride * a->block->rstride, a_st_c = a->col_stride * a->block->rstride, b_st_r = b->row_stride * b->block->rstride, b_st_c = b->col_stride * b->block->rstride, r_st_r = r->row_stride * r->block->rstride, r_st_c = r->col_stride * r->block->rstride; vsip_length a_c_l = a->col_length; /* i_size */ vsip_length r_r_l = r->row_length; /* j_size */ vsip_length a_r_l = a->row_length; /* k_size */ register vsip_scalar_d a_scalar, b_scalar, temp; vsip_scalar_d *ap = (a->block->array) + a->offset * a->block->rstride, *bp = (b->block->array) + b->offset * b->block->rstride, *rp = (r->block->array) + r->offset * r->block->rstride; vsip_scalar_d *ap0 = ap, *bp0 = bp, *rp0 = rp; switch(method){ case 0 : VI_GEMP_jki_D; break; /* ccc */ case 1 : VI_GEMP_ikj_D; break; /* ccr */ case 2 : VI_GEMP_jki_D; break; /* crc */ case 3 : VI_GEMP_ikj_D; break; /* crr */ case 4 : VI_GEMP_ijk_D; break; /* rcc */ case 5 : VI_GEMP_ijk_D; break; /* rcr */ case 6 : VI_GEMP_ikj_D; break; /* rrc */ case 7 : VI_GEMP_ikj_D; /* rrr */ } } } <file_sep>/* Created RJudd January 4, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vcmaxmgsqval_f.c,v 2.0 2003/02/22 15:19:11 judd Exp $ */ /* Modified RJudd June 28, 1998 */ /* to add complex block support */ /* Removed Development Mode RJudd Sept 00 */ #include"vsip.h" #include"vsip_cvviewattributes_f.h" vsip_scalar_f (vsip_vcmaxmgsqval_f)( const vsip_cvview_f* a, vsip_index *j) { { /* register */ vsip_length n = a->length, n0 ; vsip_stride cast = a->block->cstride; vsip_scalar_f *apr = (vsip_scalar_f*) ((a->block->R->array) + cast * a->offset); vsip_scalar_f *api = (vsip_scalar_f*) ((a->block->I->array) + cast * a->offset); vsip_scalar_f r = 0, magsq = 0; /* register */ vsip_stride ast = (cast * a->stride); n0 = n - 1; if(j != NULL) *j = (vsip_index) 0; while(n-- > 0){ magsq = *apr * *apr + *api * *api; if(r < magsq){ r = magsq; if(j != NULL) *j = (vsip_index) ( n0 - n); } apr += ast; api += ast; } return r; } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vfirst_i.h,v 2.1 2007/04/18 17:05:54 judd Exp $ */ #include"VU_vprintm_i.include" static vsip_bool first_test_i( vsip_scalar_i a, vsip_scalar_i b) { if(a>b){ return VSIP_TRUE; } else { return VSIP_FALSE; } } static void vfirst_i(void){ printf("********\nTEST vfirst_i\n"); { vsip_scalar_i data1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9}; vsip_scalar_i data2[] = { -1, -2, 4, -4, -5, 7, -7, -8, -9}; vsip_scalar_i ans_data[] = {2,2,2,5,5,5,9,9,9}; vsip_block_i *block_a = vsip_blockbind_i(data1,9,VSIP_MEM_NONE); vsip_block_i *block_b = vsip_blockbind_i(data2,9,VSIP_MEM_NONE); vsip_block_i *block_ans = vsip_blockbind_i(ans_data,9,VSIP_MEM_NONE); vsip_vview_i *a = vsip_vbind_i(block_a,0,1,9); vsip_vview_i *b = vsip_vbind_i(block_b,0,1,9); vsip_vview_i *ans = vsip_vbind_i(block_ans,0,1,9); vsip_index j=0; vsip_vview_i *r = vsip_vcreate_i(9,VSIP_MEM_NONE); vsip_vview_i *chk = vsip_vcreate_i(9,VSIP_MEM_NONE); vsip_blockadmit_i(block_a,VSIP_TRUE); vsip_blockadmit_i(block_b,VSIP_TRUE); vsip_blockadmit_i(block_ans,VSIP_TRUE); printf("vsip_vfirst_f(index,function*,b,a)"); printf("If index > a,b length then return index\n"); if(vsip_vfirst_i(10,first_test_i,b,a) == (vsip_index)10){ printf("correct\n"); fflush(stdout); } else { printf("error \n"); fflush(stdout); } printf("check for correct index, if not true return length \n"); for(j=0; j<9; j++){ vsip_vput_i(r,j,(vsip_scalar_i)vsip_vfirst_i(j,first_test_i,b,a)); } printf("vector a\n");VU_vprintm_i("3",a); printf("vector b\n");VU_vprintm_i("3",b); printf("vector r\n");VU_vprintm_i("3",r); printf("right answer\n");VU_vprintm_i("3",ans); vsip_vsub_i(r,ans,chk); vsip_vmul_i(chk,chk,chk); /* make sure we don't get zero by mistake */ if(vsip_vsumval_i(chk) > 0) printf("error\n"); else printf("correct\n"); } return; } <file_sep>/* Created By RJudd October 14, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_rcfftop_create_f_fftw.h,v 2.0 2003/02/22 15:18:33 judd Exp $ */ /* real to complex fft */ #ifndef _VI_RCFFTOP_CREATE_F_FFTW_H #define _VI_RCFFTOP_CREATE_F_FFTW_H /* selectively include functions in fftw_obj */ #define __VSIPL_FFTWOBJ_INIT #define __VSIPL_FFTWOBJ_FIN #include"VI_vrealview_f.h" #include"VI_vimagview_f.h" #include"VI_vramp_f.h" #include"VI_vcos_f.h" #include"VI_vsin_f.h" #include"VI_fftw_obj.h" #define VI_ft_f_PI 3.1415926535897932384626433 /* For this function N is required to be even */ vsip_fft_f* vsip_rcfftop_create_f( vsip_length N, vsip_scalar_f scale, unsigned int ntimes, vsip_alg_hint hint) { vsip_fft_f *fft = (vsip_fft_f*) malloc(sizeof(vsip_fft_f)); vsipl_fftw_obj *obj; fftw_direction fftw_dir = FFTW_FORWARD; int flags = (hint == VSIP_ALG_TIME) ? FFTW_MEASURE : FFTW_ESTIMATE; int init; if(fft == NULL) return (vsip_fft_f*) NULL; fft->N = N/2; fft->scale = scale; fft->d = VSIP_FFT_FWD; fft->pn = NULL; fft->p0 = NULL; fft->pF = NULL; fft->wt = (vsip_cvview_f*)NULL; fft->index = (NULL); fft->hint = hint; fft->ntimes = ntimes; fft->type = VSIP_RCFFTOP; fft->temp = vsip_cvcreate_f(fft->N,VSIP_MEM_NONE); init = vsipl_fftwobj_init(&obj,fftw_dir,fft->N,flags); if((init!=0) || (fft->temp == (vsip_cvview_f*)NULL)){ if(init != 0) vsipl_fftwobj_fin(obj); if(fft->temp != NULL) vsip_cvdestroy_f(fft->temp); free(fft); return (vsip_fft_f*)NULL; } fft->ext_fft_obj = (void*)obj; { vsip_vview_f wt1,wt2; vsip_vview_f *wtR = VI_vrealview_f(fft->temp,&wt1); vsip_vview_f *wtI = VI_vimagview_f(fft->temp,&wt2); VI_vramp_f((vsip_scalar_f)0,(vsip_scalar_f)VI_ft_f_PI/fft->N,wtR); VI_vsin_f(wtR,wtI); VI_vcos_f(wtR,wtR); } return fft; } #endif /* _VI_RCFFTOP_CREATE_F_FFTW_H */ <file_sep>/* Created RJudd */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cchol_d.h,v 2.1 2004/07/30 16:03:04 judd Exp $ */ #include"VU_cmprintm_d.include" static void cchol_d(void){ printf("********\nTEST cchol_d\n"); { vsip_index i,j; /* use this block for default creater */ /* vsip_cblock_d *ablock = vsip_cblockcreate_d(200,VSIP_MEM_NONE); */ /* use this block to ensure split complex */ vsip_scalar_d rdta[200]; vsip_scalar_d idta[200]; vsip_cblock_d *ablock = vsip_cblockbind_d(rdta,idta,200,VSIP_MEM_NONE); vsip_cmview_d *R = vsip_cmcreate_d(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *RH = vsip_cmcreate_d(4,4,VSIP_ROW,VSIP_MEM_NONE); /* vsip_cmview_d *A = vsip_cmcreate_d(4,4,VSIP_ROW,VSIP_MEM_NONE); */ vsip_cmview_d *A = vsip_cmbind_d(ablock,40,-9,4,-2,4); /* vsip_cmview_d *B = vsip_cmcreate_d(4,3,VSIP_COL,VSIP_MEM_NONE); */ vsip_cmview_d *B = vsip_cmbind_d(ablock,100,10,4,3,3); vsip_cchol_d *chol = vsip_cchold_create_d(VSIP_TR_UPP,4); vsip_cmview_d *ans = vsip_cmcreate_d(4,3,VSIP_ROW,VSIP_MEM_NONE); vsip_scalar_d chk; vsip_scalar_d data_R[4][4] = { {1.0, -2.0, 3.0, 1.0}, {0.0, 2.0, 4.0, -1.0}, {0.0, 0.0, 4.0, 3.0}, {0.0, 0.0, 0.0, 6.0} }; vsip_scalar_d data_I[4][4] = { {0.0, 2.0, 2.0, 1.0}, {0.0, 0.0, 2.0, -4.0}, {0.0, 0.0, 0.0, 2.0}, {0.0, 0.0, 0.0, 0.0} }; vsip_scalar_d data_Br[4][3] = { {1.0, 2.0, 3.0}, {0.0, 1.0, 2.0}, {3.0, 0.0, 1.0}, {3.0, 4.0, 5.0}}; vsip_scalar_d data_Bi[4][3] = { {1.0, 0.5, 3.2}, {2.0, 0.0, 0.6}, {0.6, 2.0, 0.0}, {5.0, 7.0, 8.0}}; vsip_scalar_d data_ans_r[4][3] = { {13.6236, 27.5451, 43.1573}, {-0.1104, 5.2370, 3.3312}, {-0.8403, -1.9410, -2.9823}, { 0.7000, 0.8125, 1.7375} }; vsip_scalar_d data_ans_i[4][3] = { {19.4965, 5.3707, 40.9604}, { 6.7292, 5.4896, 15.8781}, {-1.4021, -0.3776, -2.9688}, {0.3694, -0.1632, 0.4667} }; vsip_cblockadmit_d(ablock,VSIP_FALSE); for(i=0; i<4; i++) for(j=0; j<4; j++) vsip_cmput_d(R,i,j,vsip_cmplx_d(data_R[i][j],data_I[i][j])); for(i=0; i<4; i++){ for(j=0; j<3; j++){ vsip_cmput_d(B,i,j,vsip_cmplx_d(data_Br[i][j],data_Bi[i][j])); vsip_cmput_d(ans,i,j,vsip_cmplx_d(data_ans_r[i][j],data_ans_i[i][j])); } } vsip_cmherm_d(R,RH); vsip_cmprod_d(RH,R,A); printf("R = \n");VU_cmprintm_d("4.2",R); printf("RH = \n");VU_cmprintm_d("4.2",RH); printf("A = R * RH\n");VU_cmprintm_d("4.2",A); printf("B \n");VU_cmprintm_d("4.2",B); vsip_cchold_d(chol,A); vsip_ccholsol_d(chol,B); printf("Solve using cholesky AX = B\n X = \n");VU_cmprintm_d("4.2",B); vsip_cchold_destroy_d(chol); printf("right answer \n ans = \n");VU_cmprintm_d("4.2",ans); vsip_cmsub_d(ans,B,B); chk = vsip_cmmeansqval_d(B); if(chk > .001) printf("error\n"); else printf("correct\n"); { vsip_clu_d *lu = vsip_clud_create_d(4); vsip_cmview_d *Bans = vsip_cmcreate_d(4,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cmprod_d(RH,R,A); for(i=0; i<4; i++) for(j=0; j<3; j++) vsip_cmput_d(B,i,j,vsip_cmplx_d(data_Br[i][j],data_Bi[i][j])); vsip_clud_d(lu,A); vsip_clusol_d(lu,VSIP_MAT_NTRANS,B); printf("Solve using LUD AX = B\n X = \n");VU_cmprintm_d("4.2",B); vsip_clud_destroy_d(lu); vsip_cmprod_d(RH,R,A); vsip_cmprod_d(A,B,Bans); printf("Bans = A X \n");VU_cmprintm_d("4.2",Bans); vsip_cmsub_d(ans,B,B); chk = vsip_cmmeansqval_d(B); if(chk > .001) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(Bans); } vsip_cmalldestroy_d(R); vsip_cmalldestroy_d(RH); vsip_cmdestroy_d(B); vsip_cmalldestroy_d(A); } } <file_sep>/* * vsip_svadd_vi.c * tvcpp_xcode * * Created by <NAME> on 7/17/06. * Copyright 2006 * See Copyright statement in top level directory * */ /* $Id: vsip_svadd_vi.c,v 2.2 2007/04/16 18:37:19 judd Exp $ */ #include"vsip.h" #include"vsip_vviewattributes_vi.h" void (vsip_svadd_vi)( vsip_scalar_vi a, const vsip_vview_vi *b, const vsip_vview_vi *r) { register vsip_scalar_vi alpha = a; vsip_length n = r->length; vsip_stride bst = b->stride, rst = r->stride; vsip_scalar_vi *bp = (b->block->array) + b->offset, *rp = (r->block->array) + r->offset; while(n-- > 0){ *rp = alpha + *bp; bp += bst; rp += rst; } } <file_sep>/* Created By RJudd June 10, 2002 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_ccfftop_create_d_fftw.h,v 2.0 2003/02/22 15:18:30 judd Exp $ */ /* use fftw to calculate fft */ #define __VSIPL_FFTWOBJ_INIT #define __VSIPL_FFTWOBJ_FIN #include"VI_fftw_obj.h" vsip_fft_d* vsip_ccfftop_create_d(vsip_length N, vsip_scalar_d scale, vsip_fft_dir dir, unsigned int ntimes, vsip_alg_hint hint) { vsipl_fftw_obj *obj; fftw_direction fftw_dir; int flags; int init; vsip_fft_d *fft = (vsip_fft_d*) malloc(sizeof(vsip_fft_d)); if(fft == NULL) return (vsip_fft_d*) NULL; if(dir == VSIP_FFT_FWD) fftw_dir = FFTW_FORWARD; else fftw_dir = FFTW_BACKWARD; if(hint == VSIP_ALG_TIME) flags = FFTW_MEASURE; else flags = FFTW_ESTIMATE; init = vsipl_fftwobj_init(&obj,fftw_dir,N,flags); if(init!=0){ vsipl_fftwobj_fin(obj); free(fft); return (vsip_fft_d*)NULL; } fft->ext_fft_obj = (void*)obj; fft->N = N; fft->scale = scale; fft->d = dir; fft->hint = hint; fft->ntimes = ntimes; fft->type = VSIP_CCFFTOP; fft->pn = NULL; fft->p0 = NULL; fft->pF = NULL; fft->index = NULL; fft->wt = (vsip_cvview_d*)NULL; fft->temp = (vsip_cvview_d*)NULL; return fft; } <file_sep>/* Created By RJudd June 10, 2002 */ /* SPAWARSYSCEN code 2857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_fft_destroy_f_fftw.h,v 2.0 2003/02/22 15:18:32 judd Exp $ */ /* fft if fftw is defined */ #include"vsip.h" #include"vsip_fftattributes_f.h" #define __VSIPL_FFTWOBJ_FIN #include"VI_fftw_obj.h" #include"VI_cvalldestroy_f.h" int vsip_fft_destroy_f(vsip_fft_f *fft) { if(fft != NULL){ vsipl_fftw_obj *obj = (vsipl_fftw_obj*)fft->ext_fft_obj; if(fft->wt != NULL)VI_cvalldestroy_f(fft->wt); if(fft->temp != NULL)VI_cvalldestroy_f(fft->temp); if(fft->pn != NULL)free(fft->pn); if(fft->p0 != NULL)free(fft->p0); if(fft->pF != NULL)free(fft->pF); if(fft->index != NULL)free(fft->index); vsipl_fftwobj_fin(obj); free(fft); } return 0; } <file_sep>/* Created <NAME> 2, 2013 */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"svd_f.h" static vsip_vview_f *vsv_f(vsip_vview_f *v, vsip_vview_f *vs, vsip_index i) { vsip_vattr_f attr; vsip_vgetattrib_f(v,&attr); attr.offset += i * attr.stride; attr.length -= i; vsip_vputattrib_f(vs,&attr); return vs; } static vsip_mview_f* msv_f(vsip_mview_f *B,vsip_mview_f *BS, vsip_index i,vsip_index j) { vsip_mattr_f attr; vsip_mgetattrib_f(B,&attr); attr.row_length -= j; attr.col_length -= i; attr.offset += j * attr.row_stride + i * attr.col_stride; vsip_mputattrib_f(BS,&attr); return BS; } static vsip_mview_f* imsv_f( vsip_mview_f *B, vsip_mview_f *BS, vsip_index i1,vsip_index j1, vsip_index i2, vsip_index j2) { vsip_mattr_f attr; vsip_mgetattrib_f(B,&attr); if(j1 == 0) j1 =attr.col_length; if(j2 == 0) j2 =attr.row_length; attr.col_length = (j1 - i1); attr.row_length = (j2 - i2); attr.offset += i2 * attr.row_stride + i1 * attr.col_stride; vsip_mputattrib_f(BS,&attr); return BS; } static vsip_vview_f *ivsv_f( vsip_vview_f *v, vsip_vview_f *vs, vsip_index i,vsip_index j) { vsip_vattr_f attr; vsip_vgetattrib_f(v,&attr); if(j==0) j=attr.length; attr.offset += i * attr.stride; attr.length = j-i; vsip_vputattrib_f(vs,&attr); return vs; } /* same */ static vsip_vview_f *col_sv_f(vsip_mview_f*Am,vsip_vview_f* vv,vsip_index col) { vsip_mattr_f A; vsip_vattr_f v; vsip_mgetattrib_f(Am,&A); v.offset = A.offset + col * A.row_stride; v.stride = A.col_stride; v.length = A.col_length; vsip_vputattrib_f(vv,&v); return vv; } static vsip_vview_f *row_sv_f(vsip_mview_f*Am,vsip_vview_f* vv,vsip_index row) { vsip_mattr_f A; vsip_vattr_f v; vsip_mgetattrib_f(Am,&A); v.offset = A.offset + row * A.col_stride; v.stride = A.row_stride; v.length = A.row_length; vsip_vputattrib_f(vv,&v); return vv; } static vsip_vview_f *diag_sv_f(vsip_mview_f* Am,vsip_vview_f* a, vsip_stride i) { vsip_mattr_f A; vsip_vattr_f v; vsip_mgetattrib_f(Am,&A); vsip_vgetattrib_f(a,&v); v.stride=A.row_stride + A.col_stride; if(i==0){ v.length = A.row_length; v.offset = A.offset; } else if (i == 1){ v.offset = A.offset + A.row_stride; v.length = A.row_length - 1; } else { printf("Failed in diag_sv_f\n"); exit(0); } vsip_vputattrib_f(a,&v); return a; } static vsip_vview_f* vclone_f(vsip_vview_f*x, vsip_vview_f *v) { vsip_vputlength_f(v,vsip_vgetlength_f(x)); vsip_vcopy_f_f(x,v); return v; } static vsip_scalar_f vnorm2_f(vsip_vview_f *v) { return vsip_sqrt_f(vsip_vsumsqval_f(v)); } static vsip_scalar_f mnormFro_f(vsip_mview_f *v) { return vsip_sqrt_f(vsip_msumsqval_f(v)); } static vsip_mview_f* meye_f(vsip_length n) { vsip_vview_f *d = (vsip_vview_f*) NULL; vsip_mview_f *retval = (vsip_mview_f*)NULL; retval = vsip_mcreate_f(n,n,VSIP_ROW,VSIP_MEM_NONE); if(retval) d = vsip_mdiagview_f(retval,0); if(d){ vsip_mfill_f(0.0,retval); vsip_vfill_f(1.0,d); vsip_vdestroy_f(d); } else { vsip_malldestroy_f(retval); retval = (vsip_mview_f*) NULL; } return retval; } static void svdZeroCheckAndSet_f(vsip_scalar_f e, vsip_vview_f *b0, vsip_vview_f *b1) { vsip_index i; vsip_length n = vsip_vgetlength_f(b1); vsip_scalar_f z = 0.0; for(i=0; i<n; i++){ vsip_scalar_f b = vsip_mag_f(vsip_vget_f(b1,i)); vsip_scalar_f a = e*(vsip_mag_f(vsip_vget_f(b0,i)) + vsip_mag_f(vsip_vget_f(b0,i+1))); if( b < a ) vsip_vput_f(b1,i,z); } } /* same */ /* sign function as defined in http://www.netlib.org/lapack/lawnspdf/lawn148.pdf */ static vsip_scalar_f sign_f(vsip_scalar_f a_in) { if(a_in < 0.0) return -1.0; else return 1.0; } /* same */ static void biDiagPhaseToZero_f( svdObj_f *svd) { vsip_mview_f *L = svd->L; vsip_vview_f *d = svd->d; vsip_vview_f *f = svd->f; vsip_mview_f *R = svd->R; vsip_scalar_f eps0 = svd->eps0; vsip_length n_d=vsip_vgetlength_f(d); vsip_length n_f=vsip_vgetlength_f(f); vsip_index i,j; vsip_scalar_f ps; vsip_scalar_f m; vsip_vview_f *l = svd->ls_one; vsip_vview_f *r = svd->rs_one; for(i=0; i<n_d; i++){ ps=vsip_vget_f(d,i); m = vsip_mag_f(ps); ps=sign_f(ps); if(m > eps0){ col_sv_f(L,l,i);vsip_svmul_f(ps,l,l); vsip_vput_f(d,i,m); if (i < n_f) vsip_vput_f(f,i,ps*vsip_vget_f(f,i)); } else { vsip_vput_f(d,i,0.0); } } svdZeroCheckAndSet_f(eps0,d,f); for (i=0; i<n_f-1; i++){ j=i+1; ps = vsip_vget_f(f,i); m = vsip_mag_f(ps); ps=sign_f(ps); col_sv_f(L, l, j);vsip_svmul_f(ps,l,l); row_sv_f(R,r,j);vsip_svmul_f(ps,r,r); vsip_vput_f(f,i,m); vsip_vput_f(f,j,ps * vsip_vget_f(f,j)); } j=n_f; i=j-1; ps=vsip_vget_f(f,i); m=vsip_mag_f(ps); ps=sign_f(ps); vsip_vput_f(f,i,m); col_sv_f(L, l, j);vsip_svmul_f(ps,l,l); row_sv_f(R,r,j);vsip_svmul_f(ps,r,r); } static void phaseCheck_f(svdObj_f *svd) { biDiagPhaseToZero_f(svd); } void houseProd_f(vsip_vview_f *v, vsip_mview_f *A) { vsip_mattr_f a_atr; vsip_vview_f *w; vsip_mview_f *B; vsip_mgetattrib_f(A,&a_atr); B=vsip_mcreate_f(a_atr.col_length,a_atr.row_length,VSIP_ROW,VSIP_MEM_NONE); w = vsip_vcreate_f(a_atr.row_length,VSIP_MEM_NONE); vsip_scalar_f beta = 2.0/vsip_vdot_f(v,v); vsip_vmprod_f(v,A,w); vsip_vouter_f(beta,v,w,B); vsip_msub_f(A,B,A); vsip_valldestroy_f(w); vsip_malldestroy_f(B); } /* need to remove create */ void prodHouse_f(vsip_mview_f *A, vsip_vview_f *v) { vsip_mattr_f a_atr; vsip_vview_f *w; vsip_mview_f *B; vsip_mgetattrib_f(A,&a_atr); B=vsip_mcreate_f(a_atr.col_length,a_atr.row_length,VSIP_ROW,VSIP_MEM_NONE); w = vsip_vcreate_f(a_atr.col_length,VSIP_MEM_NONE); vsip_scalar_f beta = 2.0/vsip_vdot_f(v,v); vsip_mvprod_f(A,v,w); vsip_vouter_f(beta,w,v,B); vsip_msub_f(A,B,A); vsip_valldestroy_f(w); vsip_malldestroy_f(B); } /* need to remove create */ static vsip_vview_f *houseVector_f(vsip_vview_f* x) { vsip_scalar_f nrm=vnorm2_f(x); vsip_scalar_f t = vsip_vget_f(x,0); vsip_scalar_f s = t + sign_f(t) * nrm; vsip_vput_f(x,0,s); nrm = vnorm2_f(x); if (nrm == 0.0) vsip_vput_f(x,0,1.0); else vsip_svmul_f(1.0/nrm,x,x); return x; } static void VHmatExtract_f(svdObj_f *svd) { vsip_mview_f*B = svd->B; vsip_index i,j; vsip_length n = vsip_mgetrowlength_f(B); vsip_mview_f *Bs=svd->Bs; vsip_mview_f *V=svd->R; vsip_mview_f *Vs=svd->Rs; vsip_vview_f *v; vsip_scalar_f t; if(n < 3) return; v = row_sv_f(B,svd->bs,0); for(i=n-3; i>0; i--){ j=i+1; row_sv_f(msv_f(B,Bs,i,j),v,0); t=vsip_vget_f(v,0);vsip_vput_f(v,0,1.0); prodHouse_f(msv_f(V,Vs,j,j),v); vsip_vput_f(v,0,t); } row_sv_f(msv_f(B,Bs,0,1),v,0); t=vsip_vget_f(v,0);vsip_vput_f(v,0,1.0); prodHouse_f(msv_f(V,Vs,1,1),v); vsip_vput_f(v,0,t); } static void UmatExtract_f(svdObj_f *svd) { vsip_mview_f* B=svd->B; vsip_mview_f *U=svd->L; vsip_index i; vsip_length m = vsip_mgetcollength_f(B); vsip_length n = vsip_mgetrowlength_f(B); vsip_mview_f *Bs=svd->Bs; vsip_mview_f *Us=svd->Ls; vsip_vview_f *v; vsip_scalar_f t; v = col_sv_f(B,svd->bs,0); if (m > n){ i=n-1; col_sv_f(msv_f(B,Bs,i,i),v,0); t=vsip_vget_f(v,0); vsip_vput_f(v,0,1.0); houseProd_f(v,msv_f(U,Us,i,i)); vsip_vput_f(v,0,t); } for(i=n-2; i>0; i--){ col_sv_f(msv_f(B,Bs,i,i),v,0); t=vsip_vget_f(v,0); vsip_vput_f(v,0,1.0); houseProd_f(v,msv_f(U,Us,i,i)); vsip_vput_f(v,0,t); } col_sv_f(msv_f(B,Bs,0,0),v,0); t=vsip_vget_f(v,0); vsip_vput_f(v,0,1.0); houseProd_f(v,msv_f(U,Us,0,0)); vsip_vput_f(v,0,t); } static void bidiag_f(svdObj_f *svd) { vsip_mview_f *B = svd->B; vsip_mview_f *Bs = svd->Bs; vsip_length m = vsip_mgetcollength_f(B); vsip_length n = vsip_mgetrowlength_f(B); vsip_vview_f *x=col_sv_f(B,svd->bs,0); vsip_vview_f *v=vclone_f(x,svd->t); vsip_vview_f *vs = svd->ts; vsip_index i,j; for(i=0; i<n-1; i++){ vsip_vputlength_f(v,m-i); vsip_vcopy_f_f(col_sv_f(msv_f(B,Bs,i,i),x,0),v); houseVector_f(v); vsip_svmul_f(1.0/vsip_vget_f(v,0),v,v); houseProd_f(v,Bs); vsip_vcopy_f_f(vsv_f(v,vs,1),vsv_f(x,x,1)); if(i < n-2){ j = i+1; vsip_vputlength_f(v,n-j); vsip_vcopy_f_f(row_sv_f(msv_f(B,Bs,i,j),x,0),v); houseVector_f(v); vsip_svmul_f(1.0/vsip_vget_f(v,0),v,v); prodHouse_f(Bs,v); vsip_vcopy_f_f(vsv_f(v,vs,1),vsv_f(x,x,1)); } } if(m > n){ i=n-1; vsip_vputlength_f(v,m-i); vsip_vcopy_f_f(col_sv_f(msv_f(B,Bs,i,i),x,0),v); houseVector_f(v); vsip_svmul_f(1.0/vsip_vget_f(v,0),v,v); houseProd_f(v,Bs); vsip_vcopy_f_f(vsv_f(v,vs,1),vsv_f(x,x,1)); } } static void svdBidiag_f(svdObj_f *svd) { vsip_mview_f *B = svd->B; /* eps0 is a number << maximum singular value */ svd->eps0=mnormFro_f(B)/(vsip_scalar_f)vsip_mgetrowlength_f(B)*1E-10; bidiag_f(svd); UmatExtract_f(svd); VHmatExtract_f(svd); biDiagPhaseToZero_f(svd); vsip_vcopy_f_f(diag_sv_f(B,svd->bs,0),svd->d); vsip_vcopy_f_f(diag_sv_f(B,svd->bs,1),svd->f); } static void gtProd_f(vsip_index i, vsip_index j, vsip_scalar_f c,vsip_scalar_f s, svdObj_f* svd) { vsip_mview_f* R = svd->Rs; vsip_vview_f *a1= row_sv_f(R,svd->rs_one, i); vsip_vview_f *a2= row_sv_f(R,svd->rs_two, j); vsip_vview_f *a1c=vclone_f(a1,svd->t); vsip_svmul_f(c,a1c,a1); vsip_vsma_f(a2,s,a1,a1); vsip_svmul_f(-s,a1c,a1c); vsip_vsma_f(a2,c,a1c,a2); } static void prodG_f(svdObj_f* svd,vsip_index i, vsip_index j,vsip_scalar_f c, vsip_scalar_f s) { vsip_mview_f* L = svd->Ls; vsip_vview_f *a1= col_sv_f(L,svd->ls_one,i); vsip_vview_f *a2= col_sv_f(L,svd->ls_two,j); vsip_vview_f *a1c=vclone_f(a1,svd->t); vsip_svmul_f(c,a1c,a1); vsip_vsma_f(a2,s,a1,a1); vsip_svmul_f(-s,a1c,a1c);vsip_vsma_f(a2,c,a1c,a2); } static givensObj_f givensCoef_f(vsip_scalar_f x1, vsip_scalar_f x2) { givensObj_f retval; vsip_scalar_f t = vsip_hypot_f(x1,x2); if (x2 == 0.0){ retval.c=1.0;retval.s=0.0;retval.r=x1; } else if (x1 == 0.0) { retval.c=0.0;retval.s=sign_f(x2);retval.r=t; }else{ vsip_scalar_f sn = sign_f(x1); retval.c=vsip_mag_f(x1)/t;retval.s=sn*x2/t; retval.r=sn*t; } return retval; } /* same */ static void zeroCol_f(svdObj_f *svd) { vsip_vview_f *d=svd->ds; vsip_vview_f *f=svd->fs; vsip_length n = vsip_vgetlength_f(f); givensObj_f g; vsip_scalar_f xd,xf,t; vsip_index i,j,k; if (n == 1){ xd=vsip_vget_f(d,0); xf=vsip_vget_f(f,0); g=givensCoef_f(xd,xf); vsip_vput_f(d,0,g.r); vsip_vput_f(f,0,0.0); gtProd_f(0,1,g.c,g.s,svd); }else if (n == 2){ xd=vsip_vget_f(d,1); xf=vsip_vget_f(f,1); g=givensCoef_f(xd,xf); vsip_vput_f(d,1,g.r); vsip_vput_f(f,1,0.0); xf=vsip_vget_f(f,0); t= -xf * g.s; xf *= g.c; vsip_vput_f(f,0,xf); gtProd_f(1,2,g.c,g.s,svd); xd=vsip_vget_f(d,0); g=givensCoef_f(xd,t); vsip_vput_f(d,0,g.r); gtProd_f(0,2,g.c,g.s,svd); }else{ i=n-1; j=i-1; k=i; xd=vsip_vget_f(d,i); xf=vsip_vget_f(f,i); g=givensCoef_f(xd,xf); xf=vsip_vget_f(f,j); vsip_vput_f(f,i,0.0); vsip_vput_f(d,i,g.r); t=-xf*g.s; xf*=g.c; vsip_vput_f(f,j,xf); gtProd_f(i,k+1,g.c,g.s,svd); while (i > 1){ i = j; j = i-1; xd=vsip_vget_f(d,i); g=givensCoef_f(xd,t); vsip_vput_f(d,i,g.r); xf=vsip_vget_f(f,j); t= -xf * g.s; xf *= g.c; vsip_vput_f(f,j,xf); gtProd_f(i,k+1,g.c,g.s,svd); } xd=vsip_vget_f(d,0); g=givensCoef_f(xd,t); vsip_vput_f(d,0,g.r); gtProd_f(0,k+1,g.c,g.s,svd); } } static void zeroRow_f(svdObj_f *svd) { vsip_vview_f *d = svd->ds; vsip_vview_f *f = svd->fs; vsip_length n = vsip_vgetlength_f(d); givensObj_f g; vsip_scalar_f xd,xf,t; vsip_index i; xd=vsip_vget_f(d,0); xf=vsip_vget_f(f,0); g=givensCoef_f(xd,xf); if (n == 1){ vsip_vput_f(f,0,0.0); vsip_vput_f(d,0,g.r); }else{ vsip_vput_f(f,0,0.0); vsip_vput_f(d,0,g.r); xf=vsip_vget_f(f,1); t= -xf * g.s; xf *= g.c; vsip_vput_f(f,1,xf); prodG_f(svd,1,0,g.c,g.s); for(i=1; i<n-1; i++){ xd=vsip_vget_f(d,i); g=givensCoef_f(xd,t); prodG_f(svd,i+1,0,g.c,g.s); vsip_vput_f(d,i,g.r); xf=vsip_vget_f(f,i+1); t=-xf * g.s; xf *= g.c; vsip_vput_f(f,i+1,xf); } xd=vsip_vget_f(d,n-1); g=givensCoef_f(xd,t); vsip_vput_f(d,n-1,g.r); prodG_f(svd,n,0,g.c,g.s); } } static vsip_scalar_f svdMu_f(vsip_scalar_f d2,vsip_scalar_f f1,vsip_scalar_f d3,vsip_scalar_f f2) { vsip_scalar_f mu; vsip_scalar_f cu=d2 * d2 + f1 * f1; vsip_scalar_f cl=d3 * d3 + f2 * f2; vsip_scalar_f cd = d2 * f2; vsip_scalar_f D = (cu * cl - cd * cd); vsip_scalar_f T = (cu + cl); vsip_scalar_f root = vsip_sqrt_f(T*T - 4 * D); vsip_scalar_f lambda1 = (T + root)/(2.); vsip_scalar_f lambda2 = (T - root)/(2.); if(vsip_mag_f(lambda1 - cl) < vsip_mag_f(lambda2 - cl)) mu = lambda1; else mu = lambda2; return mu; } /* same */ static vsip_index zeroFind_f(vsip_vview_f* d, vsip_scalar_f eps0) { vsip_index j = vsip_vgetlength_f(d); vsip_scalar_f xd=vsip_vget_f(d,j-1); while(xd > eps0){ if (j > 1){ j -= 1; xd=vsip_vget_f(d,j-1); }else{ break; } } if(xd <= eps0) vsip_vput_f(d,j-1,0.0); if (j == 1) j=0; return j; } /* same */ static svdCorner svdCorners_f(vsip_vview_f* f) { svdCorner crnr; vsip_index j=vsip_vgetlength_f(f)-1; vsip_index i; while((j > 0) && (vsip_vget_f(f,j) == 0.0)) j-=1; if(j == 0 && vsip_vget_f(f,0) == 0.0){ crnr.i=0; crnr.j=0; } else { i = j; j += 1; while((i > 0) && (vsip_vget_f(f,i) != 0.0)) i -= 1; if((i == 0) && (vsip_vget_f(f,0)== 0.0)){ crnr.i=1; crnr.j=j+1; } else if (i==0){ crnr.i=0; crnr.j=j+1; } else { crnr.i=i+1; crnr.j=j+1; } } return crnr; } /* same */ static void svdStep_f(svdObj_f *svd) { vsip_vview_f *d = svd->ds; vsip_vview_f *f = svd->fs; givensObj_f g; vsip_length n = vsip_vgetlength_f(d); vsip_scalar_f mu=0.0, x1=0.0, x2=0.0; vsip_scalar_f t=0.0; vsip_index i,j,k; vsip_scalar_f d2,f1,d3,f2; if(n >= 3){ d2=vsip_vget_f(d,n-2);f1= vsip_vget_f(f,n-3);d3 = vsip_vget_f(d,n-1);f2= vsip_vget_f(f,n-2); } else if(n == 2){ d2=vsip_vget_f(d,0);f1= 0.0;d3 = vsip_vget_f(d,1);f2= vsip_vget_f(f,0); } else { d2=vsip_vget_f(d,0);f1 = 0.0;d3 = 0.0;f2 = 0.0; } mu = svdMu_f(d2,f1,d3,f2); x1=vsip_vget_f(d,0); x2 = x1 * vsip_vget_f(f,0); x1 *= x1; x1 -= mu; g=givensCoef_f(x1,x2); x1=vsip_vget_f(d,0);x2=vsip_vget_f(f,0); vsip_vput_f(f,0,g.c * x2 - g.s * x1); vsip_vput_f(d,0,x1 * g.c + x2 * g.s); t=vsip_vget_f(d,1); vsip_vput_f(d,1,t*g.c); t*=g.s; gtProd_f(0,1,g.c,g.s,svd); for(i=0; i<n-2; i++){ j=i+1; k=i+2; g = givensCoef_f(vsip_vget_f(d,i),t); vsip_vput_f(d,i,g.r); x1=vsip_vget_f(d,j)*g.c; x2=vsip_vget_f(f,i)*g.s; t= x1 - x2; x1=vsip_vget_f(f,i) * g.c; x2=vsip_vget_f(d,j) * g.s ; vsip_vput_f(f,i,x1+x2); vsip_vput_f(d,j,t); x1=vsip_vget_f(f,j); t=g.s * x1; vsip_vput_f(f,j, x1*g.c); prodG_f(svd,i, j, g.c, g.s); g=givensCoef_f(vsip_vget_f(f,i),t); vsip_vput_f(f,i,g.r); x1=vsip_vget_f(d,j); x2=vsip_vget_f(f,j); vsip_vput_f(d,j,g.c * x1 + g.s * x2); vsip_vput_f(f,j,g.c * x2 - g.s * x1); x1=vsip_vget_f(d,k); t=g.s * x1; vsip_vput_f(d,k,x1*g.c); gtProd_f(j,k, g.c, g.s,svd); } i=n-2; j=n-1; g = givensCoef_f(vsip_vget_f(d,i),t); vsip_vput_f(d,i,g.r); x1=vsip_vget_f(d,j)*g.c; x2=vsip_vget_f(f,i)*g.s; t=x1 - x2; x1 = vsip_vget_f(f,i) * g.c; x2=vsip_vget_f(d,j) * g.s; vsip_vput_f(f,i,x1+x2); vsip_vput_f(d,j,t); prodG_f(svd,i, j, g.c, g.s); } static void svdIteration_f(svdObj_f* svd) { vsip_mview_f *L0 = svd->L; vsip_mview_f *L = svd->Ls; vsip_vview_f *d0 = svd->d; vsip_vview_f *d = svd->ds; vsip_vview_f *f0 = svd->f; vsip_vview_f *f = svd->fs; vsip_mview_f *R0 = svd->R; vsip_mview_f *R= svd->Rs; vsip_scalar_f eps0 = svd->eps0; vsip_length n; svdCorner cnr; vsip_index k; vsip_length cntr=0; vsip_length maxcntr=20*vsip_vgetlength_f(d0); while (cntr++ < maxcntr){ phaseCheck_f(svd); cnr=svdCorners_f(f0); if (cnr.j == 0) break; ivsv_f(d0,d,cnr.i,cnr.j); ivsv_f(f0,f,cnr.i,cnr.j-1); imsv_f(L0,L,0,0,cnr.i,cnr.j); imsv_f(R0,R,cnr.i,cnr.j,0,0); n=vsip_vgetlength_f(f); k=zeroFind_f(d,eps0); if (k > 0){ if(vsip_vget_f(d,n) == 0.0){ zeroCol_f(svd); }else{ imsv_f(L,L,0,0,k-1,0); ivsv_f(d0,d,k,0); ivsv_f(f0,f,k-1,0); zeroRow_f(svd); } }else{ svdStep_f(svd); } } } static void svdSort_f(svdObj_f *svd) { vsip_vview_f *d = svd->d; vsip_length n=vsip_vgetlength_f(d); vsip_vview_vi* indx_L = svd->indx_L; vsip_vview_vi* indx_R = svd->indx_R; vsip_mview_f *L0 = svd->L; vsip_mview_f *L=svd->Ls; vsip_mview_f *R0 = svd->R; vsip_vsortip_f(d,VSIP_SORT_BYVALUE,VSIP_SORT_DESCENDING,VSIP_TRUE,indx_L); vsip_vcopy_vi_vi(indx_L,indx_R); imsv_f( L0, L, 0,0, 0, n); vsip_mpermute_once_f(L,VSIP_COL,indx_L,L); vsip_mpermute_once_f(R0,VSIP_ROW,indx_R,R0); } svdObj_f* svdInit_f(vsip_length m, vsip_length n) { svdObj_f *s=malloc(sizeof(svdObj_f)); if(m < n){ printf("Column length must not be less than row length"); return NULL; } if(!s) { printf("\nfailed to allocate svd object\n"); return NULL; } s->init=0; if(!(s->t = vsip_vcreate_f(m,VSIP_MEM_NONE))){ s->ts = NULL; s->init++; } else { if(!(s->ts = vsip_vcloneview_f(s->t))) s->init++; } if(!(s->B=vsip_mcreate_f(m,n,VSIP_ROW,VSIP_MEM_NONE))){ s->Bs = NULL; s->bs=NULL; s->init++; } else { if(!(s->Bs=vsip_mcloneview_f(s->B))) s->init++; if(!(s->bs=vsip_mrowview_f(s->B,0))) s->init++; } if(!(s->L=meye_f(m))){ s->Ls=NULL; s->init++; } else { if(!(s->Ls = vsip_mcloneview_f(s->L))) s->init++; if(!(s->ls_two = vsip_mrowview_f(s->Ls,0))) s->init++; if(!(s->ls_one = vsip_mrowview_f(s->Ls,0))) s->init++; } if(!(s->R=meye_f(n))){ s->Rs=NULL; s->init++; } else { if(!(s->Rs = vsip_mcloneview_f(s->R))) s->init++; if(!(s->rs_two = vsip_mrowview_f(s->Rs,0))) s->init++; if(!(s->rs_one = vsip_mrowview_f(s->Rs,0))) s->init++; } if(!(s->indx_L=vsip_vcreate_vi(n,VSIP_MEM_NONE))) s->init++; if(!(s->indx_R=vsip_vcreate_vi(n,VSIP_MEM_NONE))) s->init++; if(!(s->d = vsip_vcreate_f(n,VSIP_MEM_NONE))){ s->init++; s->ds = NULL; } else { if(!(s->ds = vsip_vcloneview_f(s->d))) s->init++; } if(!(s->f = vsip_vcreate_f(n-1,VSIP_MEM_NONE))){ s->init++; s->fs = NULL; } else { if(!(s->fs = vsip_vcloneview_f(s->f))) s->init++; } if(s->init) svdFinalize_f(s); return s; } void svdFinalize_f(svdObj_f *s) { vsip_vdestroy_f(s->ts); vsip_valldestroy_f(s->t); vsip_vdestroy_f(s->rs_one); vsip_vdestroy_f(s->rs_two); vsip_mdestroy_f(s->Rs); vsip_vdestroy_f(s->ls_one); vsip_vdestroy_f(s->ls_two); vsip_mdestroy_f(s->Ls); vsip_mdestroy_f(s->Bs); vsip_vdestroy_f(s->bs); vsip_malldestroy_f(s->B); vsip_malldestroy_f(s->R); vsip_malldestroy_f(s->L); vsip_valldestroy_vi(s->indx_L); vsip_valldestroy_vi(s->indx_R); vsip_vdestroy_f(s->ds); vsip_valldestroy_f(s->d); vsip_vdestroy_f(s->fs); vsip_valldestroy_f(s->f); s=NULL; } svdObj_f *svd_f(vsip_mview_f *A) { svdObj_f *svd = svdInit_f(vsip_mgetcollength_f(A),vsip_mgetrowlength_f(A)); if(!svd){ printf("malloc failure for SVD"); exit(0);} vsip_mcopy_f_f(A,svd->B); svdBidiag_f(svd); svdIteration_f(svd); svdSort_f(svd); return svd; }<file_sep>#ifndef __cppJvsip__Block__ #define __cppJvsip__Block__ #include<cstring> #include<iostream> #include"gen.h" #include"elementary.h" #include"scalar.h" namespace jvsip{ using namespace vsip; class Block{ friend class View; void *obj; // Vsip object Pointer. Must be Cast on use. string d; // depth "r" or "c" or "mi" string p; // precision string "f", "d", "i", "vi", "l" string s; // shape, for Block is "block"; string t; // type is depth and precision as in "f", "cf", "d", "mi", "cd" vsip_length n; int count; public: Block(string t, Scalar l); Block(const Block & blk) : d(blk.d), p(blk.p), s(blk.s), t(blk.t),n(blk.n),obj(blk.obj){ count ++; } ~Block(); void* vsip() const {return obj;} string shape() const {return s;} string precision() const {return p;} string depth() const {return d;} string type() const {return t;} Scalar length() const {return Scalar(n);} }; } #endif /* defined(__cppJvsip__Block_) */ <file_sep>// // solverTests.swift // SwiftVsip // // Created by <NAME> on 11/23/16. // Copyright © 2016 JVSIP. All rights reserved. // import XCTest @testable import SwiftVsip class solverTests: XCTestCase { func testCovarianceSolver() { let A = Vsip.Matrix(columnLength: 10, rowLength: 6, type: .cd, major: VSIP_ROW) let BX = Vsip.Matrix(columnLength: 10, rowLength: 3, type: .cd, major: VSIP_ROW) let X = Vsip.Matrix(columnLength: 6, rowLength: 3, type: .cd, major: VSIP_ROW) let ANS = Vsip.Matrix(columnLength: 6, rowLength: 3, type: .cd, major: VSIP_ROW) /* create space for ccovsol data */ let ablock = Vsip.Block(length: 500,type: .cd) let A1 = ablock.bind(200,columnStride: -3,columnLength: 10,rowStride: -31,rowLength: 6) let a0 = Vsip.Scalar(vsip_cmplx_d(0.0,0.0)) A.fill(a0) BX.fill(a0) print("********\nTEST ccovsol_d\n"); print("Test covariance solver vsip_ccovsol_d\n"); /* Solving for X in A X = B */ /* A is (M,N) M >= N; X is (N,K), B is (N,K) */ for i in 0..<A.rowLength { // Data for matrix A; fill by column let ac = A.col(i) let _ = ac.real.ramp(Vsip.Scalar(-1.3), increment: Vsip.Scalar(1.1)) let _ = ac.imag.ramp(Vsip.Scalar(1.3), increment: Vsip.Scalar(-1.1)) } let ad = A.diagview let _ = ad.real.ramp(Vsip.Scalar(3.0), increment: Vsip.Scalar(1.2)) let _ = ad.imag.ramp(Vsip.Scalar(3.0), increment: Vsip.Scalar(-1.2)) for i in 0..<BX.columnLength { //Data for matrix B; fill by row let bxr = BX.row(i) let _ = bxr.real.ramp(Vsip.Scalar(0.1), increment: Vsip.Scalar(Double(i)/3.0)) let _ = bxr.imag.ramp(Vsip.Scalar(0.2), increment: Vsip.Scalar(Double(i)/3.0)) } print("Input data \n") print("A = "); A.mPrint("4.2") print("\nB = "); BX.mPrint("4.2") let chol = Vsip.Chold(type: .cd, size: 6) let B = Vsip.Matrix(columnLength: 6, rowLength: 3, type: .cd, major: VSIP_ROW) let AHA = Vsip.Matrix(columnLength: 6, rowLength: 6, type: .cd, major: VSIP_ROW) let AH = Vsip.Matrix(columnLength: 6, rowLength: 10,type: .cd, major: VSIP_ROW) /* solve using Cholesky and AHA matrix */ print("\nSolve using Cholesky"); print("\nA is input matrix, AT (AH) is transpose (Hermitian) of A\n"); print("Solve for X least squares using (AH prod A ) prod X = AH prod B\n"); /* calculate matrix AHA = AH * A */ Vsip.herm(A, output: AH); Vsip.prod(AH, prod: A,resultsIn: AHA); /* calculate AH * B */ Vsip.prod(AH, prod: BX, resultsIn: X); print("\nAH prod A = "); AHA.mPrint("4.2") print("\nAH prod B = ");X.mPrint("4.2") let _ = chol.decompose(AHA) let _ = chol.solve(X) // B replaced by X print("\nX = "); X.mPrint("7.5") /* check */ print("\ncheck\n (AH prod A) prod X := AH prod B"); /* restore AHA */ Vsip.prod(AH, prod: A, resultsIn: AHA) /* calculate AHA prod X */ Vsip.prod(AHA, prod: X, resultsIn: B) Vsip.copy(from: X, to: ANS); /* if correct Need ANSwer */ /* for check place AH * BX into X */ Vsip.prod(AH, prod: BX, resultsIn: X) print("\nAHA * X ="); //VU_cmprintm_d("4.2",B); Vsip.sub(X, subtract: B, resultsIn: X) var check = Vsip.Jvsip.normFro(view: X).reald if(check < 0.0001) { print("correct") } else { print("error") } /* restore X for use by covsol */ Vsip.prod(AH, prod: BX, resultsIn: X); /* solve using ccovsol */ /* copy data so we can solve covariance problem later on */ Vsip.copy(from: A, to: A1) print("\nSolve using ccovsol_d "); let _ = Vsip.covsol(A1,inputOutput: X) print("Expect X to be\n"); ANS.mPrint("7.5") print("\nX = ") X.mPrint("7.5") Vsip.sub(ANS, subtract: X, resultsIn: X) check = Vsip.Jvsip.normFro(view: X).reald if check < 0.0001 { print("correct"); } else { print("error\n"); } } func testlud(){ print("********\nTEST lud_d\n"); let block = Vsip.Block(length: 500, type: .d); let AC = block.bind(0, columnStride: 6, columnLength: 6, rowStride: 1, rowLength: 6) let AG = block.bind(36, columnStride: 2, columnLength: 6, rowStride: 18, rowLength: 6) let IC = block.bind(150, columnStride: 1, columnLength: 6, rowStride: 6, rowLength: 6) let IG = block.bind(200, columnStride: 2, columnLength: 6, rowStride: 14, rowLength: 6) let B = block.bind(300, columnStride: 6, columnLength: 6, rowStride: 1, rowLength: 6) let A = block.bind(350, columnStride: 6, columnLength: 6, rowStride: 1, rowLength: 6) let X = block.bind(400, columnStride: 5, columnLength: 6, rowStride: 1, rowLength: 3) let Y = block.bind(450, columnStride: 3, columnLength: 6, rowStride: 1, rowLength: 3) let ludC = Vsip.LUD(type: .d, size: 6) let ludG = Vsip.LUD(type: .d, size: 6) var chk = 0.0 // data[6][6] let data = [ [0.50, 7.00, 10.00, 12.00, -3.00, 0.00], [2.00, 13.00, 18.00, 6.00, 0.00, 130.00], [3.00, -9.00, 2.00, 3.00, 2.00, -9.00], [4.00, 2.00, 2.00, 4.00, 1.00, 2.00], [0.20, 2.00, 9.00, 4.00, 1.00, 2.00], [0.10, 2.00, 0.30, 4.00, 1.00, 2.00]] // ydata[6][3] let ydata = [ [ 77.85, 155.70, 311.40], [ 942.00, 1884.00, 3768.00], [ 1.00, 2.00, 4.00], [ 68.00, 136.00, 272.00], [ 85.20, 170.40, 340.80], [ 59.00, 118.00, 236.00]] let Ydata = X.empty // Ident[6][6] => identity matrix let Ident = Vsip.Matrix(columnLength: 6, rowLength: 6, type: .d, major: VSIP_COL) Ident.fill(Vsip.Scalar(0.0)) Ident.diagview.fill(Vsip.Scalar(1.0)) // put data in our matrices // we could use (for instance) > let AC = A.copy but we also test view indexing for robustness // thus the obnoxious block binds in the first few lines. for i in 0..<6 { for j in 0..<6 { A[i,j] = Vsip.Scalar(data[i][j]) } for j in 0..<3 { X[i,j] = Vsip.Scalar(ydata[i][j]) } } Vsip.copy(from: A, to: AC) Vsip.copy(from: A, to: AG) Vsip.copy(from: Ident, to: IG) Vsip.copy(from: Ident, to: IC) Vsip.copy(from: X, to: Ydata) print("Matrix A = \n");A.mPrint("7.2");fflush(stdout) let _ = ludC.decompose(AC) // AC and AG are modified and used by lud decompose operation let _ = ludG.decompose(AG) print("vsip_lusol(lud,VSIP_MAT_NTRANS,X)\n"); print("Where I is the identity matrix") print("Solve A X = I \n"); fflush(stdout); let _ = ludC.solve(matOp: VSIP_MAT_NTRANS, IC) let _ = ludG.solve(matOp: VSIP_MAT_NTRANS, IG) print("for compact case X = \n");IC.mPrint("8.4"); fflush(stdout); print("for general case X = \n");IG.mPrint("8.4"); fflush(stdout); chk = Vsip.Jvsip.normFro(view: (IC - IG)).reald (chk > 1.0E-10) ? print("error\n") : print("correct\n"); fflush(stdout); Vsip.prod(A,prod: IC, resultsIn: B) chk = Vsip.Jvsip.normFro(view: (B - Ident)).reald (chk > 1.0E-10) ? print("error\n") : print("correct\n"); fflush(stdout); print("(line 175) chk = \(chk)") Vsip.prod(A,prod: IG, resultsIn: B) chk = Vsip.Jvsip.normFro(view: (B - Ident)).reald (chk > 1.0E-10) ? print("error\n") : print("correct\n"); fflush(stdout); print("(line 179) chk = \(chk)") print("mprod(A,X) = \n"); B.mPrint("8.4"); fflush(stdout); (chk > 1.0E-10) ? print("error\n") : print("correct\n"); fflush(stdout); /************************************************/ /* check case VSIP_MAT_TRANS */ print("Matrix Transpose A = \n"); A.transview.mPrint("7.2");fflush(stdout) Vsip.copy(from: Ident, to: IC) Vsip.copy(from: Ident, to: IG) print("vsip_lusol(lud,VSIP_MAT_TRANS,X)\n"); print("Solve trans(A) X = I \n"); fflush(stdout); let _ = ludC.solve(matOp: VSIP_MAT_TRANS, IC) let _ = ludG.solve(matOp: VSIP_MAT_TRANS,IG) print("for compact case X = \n");IC.mPrint("8.4"); fflush(stdout); print("for general case X = \n");IG.mPrint("8.4"); fflush(stdout); chk = Vsip.Jvsip.normFro(view: (IC - IG)).reald (chk > 1.0E-10) ? print("error\n") : print("correct\n"); fflush(stdout); Vsip.prod(A.transview,prod: IC, resultsIn: B); chk = Vsip.Jvsip.normFro(view: (B-Ident)).reald (chk > 1.0E-10) ? print("error\n") : print("correct\n") Vsip.prod(A.transview,prod: IG, resultsIn: B); chk = Vsip.Jvsip.normFro(view: (B - Ident)).reald print("mprod(trans(A),X) = \n"); B.mPrint("8.3") (chk > 1.0E-10) ? print("error\n") : print("correct\n") /************************************************/ /* check case A X = B for VSIP_MAT_NTRANS */ print("check A X = Y; VSIP_MAT_NTRANS\n"); print("Y = \n");X.mPrint("8.4") let _ = ludC.solve(matOp: VSIP_MAT_NTRANS, X) print("X = \n"); X.mPrint("8.4"); Vsip.prod(A,prod: X, resultsIn: Y) print(" Y = A X\n");Y.mPrint("8.4") chk = Vsip.Jvsip.normFro(view: (Y - Ydata)).reald (chk > 1.0E-10) ? print("error\n") : print("correct\n"); fflush(stdout); /************************************************/ /* check case trans(A) X = B for VSIP_MAT_TRANS */ Vsip.copy(from: Ydata, to: X) print("Y = \n"); X.mPrint("8.4") let _ = ludG.solve(matOp: VSIP_MAT_TRANS, X) Vsip.prod(A.transview,prod: X, resultsIn: Y) print("X = \n");X.mPrint("8.4") print("Y = trans(A) X\n");Y.mPrint("8.4") chk = Vsip.Jvsip.normFro(view: (Y - Ydata)).reald (chk > 1.0E-10) ? print("error\n") : print("correct\n"); fflush(stdout) } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mget_put_uc.h,v 2.0 2003/02/22 15:23:34 judd Exp $ */ static void mget_put_uc(void){ printf("********\nTEST mget_put_uc\n"); { vsip_scalar_uc data_a[] = { 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1}; vsip_scalar_uc ans[6][2] = {{ 0, 1},{ 1, 0},{ 1, 0},{ 1, 0},{ 0, 1},{ 0, 1}}; vsip_block_uc *block_a = vsip_blockbind_uc(data_a,12,VSIP_MEM_NONE); vsip_mview_uc *a = vsip_mbind_uc(block_a,0,2,6,1,2); vsip_block_uc *block_b = vsip_blockcreate_uc(50,VSIP_MEM_NONE); vsip_mview_uc *b = vsip_mbind_uc(block_b,5,5,6,2,2); vsip_index i,j; vsip_blockadmit_uc(block_a,VSIP_TRUE); /* copy <a> into <b> */ for(i=0; i<6; i++) for(j=0; j<2; j++) vsip_mput_uc(b,i,j,vsip_mget_uc(a,i,j)); /* check <a> against ans */ printf("check unit stride compact view\n"); for(i=0; i<6; i++) for(j=0; j<2; j++) { vsip_scalar_uc chk = (ans[i][j] - vsip_mget_uc(a,i,j)); (chk == 0) ? printf("correct\n") : printf("error\n"); fflush(stdout); } printf("check general stride view\n"); for(i=0; i<6; i++) for(j=0; j<2; j++){ vsip_scalar_uc chk = (ans[i][j] - vsip_mget_uc(b,i,j)); (chk == 0) ? printf("correct\n") : printf("error\n"); fflush(stdout); } vsip_malldestroy_uc(a); vsip_malldestroy_uc(b); } return; } <file_sep>/* Created RJudd */ /* $Id: vsip_permute_init.c,v 2.1 2008/08/17 18:01:49 judd Exp $ */ /* * vsip_permute_init.c * Created by <NAME> on 8/5/07. * */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"vsip.h" #include"vsip_permuteattributes.h" #include"vsip_vviewattributes_vi.h" /* this will init or re-init */ vsip_permute *vsip_permute_init( vsip_permute *perm, const vsip_vview_vi *vi){ vsip_length m = perm->n_vi; vsip_scalar_vi *in_p = vi->block->array + vi->offset; vsip_stride in_strd = vi->stride; if(perm){ /* check to make sure we have a created perm object */ vsip_index i; vsip_scalar_vi *in = perm->in; /* find rows that need to move*/ for(i=0; i<m; i++){ /* out i is an index of rows (cols) that are permuted; other rows do not permute */ in[i] = in_p[i * in_strd]; /* perm has its own copy of input vi */ } } return perm; /* for convenience */ } <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: permute_d.h,v 1.1 2008/09/20 22:34:50 judd Exp $ */ static void permute_d(void){ printf("********\nTEST permute for double\n"); { int i,j; vsip_vview_vi *v_ind = vsip_vcreate_vi(10,VSIP_MEM_NONE); vsip_scalar_vi vi[10]={4, 3, 2, 1, 6, 5, 0, 7, 8, 9}; /* pemute data for p */ vsip_mview_d *indta = vsip_mcreate_d(10,10,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *outdta = vsip_mcreate_d(10,10,VSIP_COL,VSIP_MEM_NONE); vsip_permute* perm; vsip_scalar_d ansdta_byrow[100]={\ 4.0, 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9, \ 3.0, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, \ 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, \ 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, \ 6.0, 6.1, 6.2, 6.3, 6.4, 6.5, 6.6, 6.7, 6.8, 6.9, \ 5.0, 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 5.7, 5.8, 5.9, \ 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, \ 7.0, 7.1, 7.2, 7.3, 7.4, 7.5, 7.6, 7.7, 7.8, 7.9, \ 8.0, 8.1, 8.2, 8.3, 8.4, 8.5, 8.6, 8.7, 8.8, 8.9, \ 9.0, 9.1, 9.2, 9.3, 9.4, 9.5, 9.6, 9.7, 9.8, 9.9}; vsip_scalar_d ansdta_bycol[100]={\ 0.4, 0.3, 0.2, 0.1, 0.6, 0.5, 0.0, 0.7, 0.8, 0.9, \ 1.4, 1.3, 1.2, 1.1, 1.6, 1.5, 1.0, 1.7, 1.8, 1.9, \ 2.4, 2.3, 2.2, 2.1, 2.6, 2.5, 2.0, 2.7, 2.8, 2.9, \ 3.4, 3.3, 3.2, 3.1, 3.6, 3.5, 3.0, 3.7, 3.8, 3.9, \ 4.4, 4.3, 4.2, 4.1, 4.6, 4.5, 4.0, 4.7, 4.8, 4.9, \ 5.4, 5.3, 5.2, 5.1, 5.6, 5.5, 5.0, 5.7, 5.8, 5.9, \ 6.4, 6.3, 6.2, 6.1, 6.6, 6.5, 6.0, 6.7, 6.8, 6.9, \ 7.4, 7.3, 7.2, 7.1, 7.6, 7.5, 7.0, 7.7, 7.8, 7.9, \ 8.4, 8.3, 8.2, 8.1, 8.6, 8.5, 8.0, 8.7, 8.8, 8.9, \ 9.4, 9.3, 9.2, 9.1, 9.6, 9.5, 9.0, 9.7, 9.8, 9.9}; vsip_mview_d *ans_byrow = vsip_mcreate_d(10,10,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *ans_bycol = vsip_mcreate_d(10,10,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *chk = vsip_mcreate_d(10,10,VSIP_ROW,VSIP_MEM_NONE); vsip_mcopyfrom_user_d(ansdta_byrow,VSIP_ROW, ans_byrow); vsip_mcopyfrom_user_d(ansdta_bycol,VSIP_ROW, ans_bycol); /* Example of by row */ for(i=0; i<10; i++){ for(j=0; j<10; j++){ vsip_mput_d(indta,i,j,(float)j/10.0 + (float)i ); /* create some data to permute */ } } vsip_vcopyfrom_user_vi(vi,v_ind); perm = vsip_mpermute_create_d(10,10,VSIP_ROW); /* create the permutation object */ vsip_permute_init(perm,v_ind); /* initialze the object with p */ vsip_mpermute_d(indta, perm, outdta); /* permute out of place */ printf("permute vector p\n"); for(i=0; i<10; i++){ printf("%2d,",(int)vi[i]); } printf("\ninput\n"); for(i=0; i<10; i++){ for(j=0; j<10; j++){ printf("%3.1f, ",vsip_mget_d(indta,i,j)); } printf("\n"); } printf("\noutput (by row out-of-place)\n"); for(i=0; i<10; i++){ for(j=0; j<10; j++){ printf("%3.1f, ",vsip_mget_d(outdta,i,j)); } printf("\n"); } vsip_msub_d(outdta,ans_byrow,chk); vsip_mmag_d(chk,chk); if(vsip_msumval_d(chk) == 0) printf("correct\n"); else printf("error\n"); printf("\noutput (by row in-place)\n"); vsip_mpermute_d(indta, perm, indta); for(i=0; i<10; i++){ for(j=0; j<10; j++){ printf("%3.1f, ",vsip_mget_d(indta,i,j)); } printf("\n"); } vsip_msub_d(indta,ans_byrow,chk); vsip_mmag_d(chk,chk); if(vsip_msumval_d(chk) == 0) printf("correct\n"); else printf("error\n"); /* re-init input matrix and destroy and create new perm object */ for(i=0; i<10; i++){ for(j=0; j<10; j++){ vsip_mput_d(indta,i,j,(float)j/10.0 + (float)i ); /* create some data to permute */ } } vsip_permute_destroy(perm); /* destroy old permutation object */ perm = vsip_mpermute_create_d(10,10,VSIP_COL); /* create new permutation object */ vsip_permute_init(perm,v_ind); /* initialze the object with p */ vsip_mpermute_d(indta, perm, outdta); /* permute out of place */ printf("\noutput (by column out-of-place)\n"); for(i=0; i<10; i++){ for(j=0; j<10; j++){ printf("%3.1f, ",vsip_mget_d(outdta,i,j)); } printf("\n"); } vsip_msub_d(outdta,ans_bycol,chk); vsip_mmag_d(chk,chk); if(vsip_msumval_d(chk) == 0) printf("correct\n"); else printf("error\n"); printf("\noutput (by column in-place)\n"); vsip_mpermute_d(indta, perm, indta); for(i=0; i<10; i++){ for(j=0; j<10; j++){ printf("%3.1f, ",vsip_mget_d(indta,i,j)); } printf("\n"); } vsip_msub_d(indta,ans_bycol,chk); vsip_mmag_d(chk,chk); if(vsip_msumval_d(chk) == 0) printf("correct\n"); else printf("error\n"); vsip_permute_destroy(perm); vsip_valldestroy_vi(v_ind); vsip_malldestroy_d(indta); vsip_malldestroy_d(outdta); vsip_malldestroy_d(ans_bycol); vsip_malldestroy_d(ans_byrow); } return; } <file_sep>from vsip import * N=8 #length of vector init = vsip_init(None) def VU_vprint_f(a): print(" ".join(["%4.0f" % vsip_vget_f(a,i) for i in range(vsip_vgetlength_f(a))])) A = vsip_vcreate_f(N,0) B = vsip_vcreate_f(N,0) C = vsip_vcreate_f(N,0) vsip_vramp_f(0,1,A) print("A = \n"); VU_vprint_f(A) vsip_vfill_f(5,B) print("B = \n"); VU_vprint_f(B) vsip_vadd_f(A,B,C) print("C = \n"); VU_vprint_f(C) vsip_valldestroy_f(A) vsip_valldestroy_f(B) vsip_valldestroy_f(C) vsip_finalize(None) <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_length_i.h,v 2.1 2007/04/18 17:05:56 judd Exp $ */ static void get_put_length_i(void){ printf("********\nTEST get_put_length_i\n"); { vsip_offset ivo = 3; vsip_stride ivs = 0; vsip_length ivl = 3; vsip_length jvl = 5; vsip_stride irs = 0, ics = 0; vsip_length irl = 2, icl = 3; vsip_length jrl = 5, jcl = 2; vsip_stride ixs = 0, iys = 0, izs = 0; vsip_length ixl = 2, iyl = 3, izl = 4; vsip_length jxl = 3, jyl = 4, jzl = 2; vsip_block_i *b = vsip_blockcreate_i(80,VSIP_MEM_NONE); vsip_vview_i *v = vsip_vbind_i(b,ivo,ivs,ivl); vsip_mview_i *m = vsip_mbind_i(b,ivo,ics,icl,irs,irl); vsip_tview_i *t = vsip_tbind_i(b,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_length s; printf("test vgetlength_i\n"); fflush(stdout); { s = vsip_vgetlength_i(v); (s == ivl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputlength_i\n"); fflush(stdout); { vsip_vputlength_i(v,jvl); s = vsip_vgetlength_i(v); (s == jvl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /*************************************************************************/ printf("test mgetrowlength_i\n"); fflush(stdout); { s = vsip_mgetrowlength_i(m); (s == irl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputrowlength_i\n"); fflush(stdout); { vsip_mputrowlength_i(m,jrl); s = vsip_mgetrowlength_i(m); (s == jrl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test mgetcollength_i\n"); fflush(stdout); { s = vsip_mgetcollength_i(m); (s == icl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputcollength_i\n"); fflush(stdout); { vsip_mputcollength_i(m,jcl); s = vsip_mgetcollength_i(m); (s == jcl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /*************************************************************************/ printf("test tgetxlength_i\n"); fflush(stdout); { s = vsip_tgetxlength_i(t); (s == ixl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputxlength_i\n"); fflush(stdout); { vsip_tputxlength_i(t,jxl); s = vsip_tgetxlength_i(t); (s == jxl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test tgetylength_i\n"); fflush(stdout); { s = vsip_tgetylength_i(t); (s == iyl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputylength_i\n"); fflush(stdout); { vsip_tputylength_i(t,jyl); s = vsip_tgetylength_i(t); (s == jyl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test tgetzlength_i\n"); fflush(stdout); { s = vsip_tgetzlength_i(t); (s == izl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputzlength_i\n"); fflush(stdout); { vsip_tputzlength_i(t,jzl); s = vsip_tgetzlength_i(t); (s == jzl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } vsip_vdestroy_i(v); vsip_mdestroy_i(m); vsip_talldestroy_i(t); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vswap_uc.c,v 2.0 2003/02/22 15:19:19 judd Exp $ */ #include"vsip.h" #include"vsip_vviewattributes_uc.h" void (vsip_vswap_uc)( const vsip_vview_uc* a, const vsip_vview_uc* b) { { /* register */ unsigned int n = (unsigned int) a->length; /* register */ int ast = (int) a->stride, bst = (int) b->stride; vsip_scalar_uc *ap = (a->block->array) + a->offset, *bp = (b->block->array) + b->offset, temp; while(n-- > 0){ temp = *ap; *ap = *bp; *bp = temp; ap += ast; bp += bst; } } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmkron_d.h,v 2.0 2003/02/22 15:23:21 judd Exp $ */ #include"VU_cmprintm_d.include" static void cmkron_d(void){ printf("********\nTEST cmkron_d\n"); { vsip_cscalar_d alpha = vsip_cmplx_d(-3,2); vsip_scalar_d data_a_r[] = { 1, 1, 2, 0.5}; /* (2,2) rowmajor */ vsip_scalar_d data_a_i[] = { 1, -1, .5, 2}; vsip_scalar_d data_b_r[] = { 3, 4, 1, 5, 3, 4, 2, 2, 3}; /* (3,3) rowmajor */ vsip_scalar_d data_b_i[] = { 1, 1, 5, 1, 0.5, 1, 2, -2, -1}; vsip_scalar_d ans_r[] = { -14.0, -19.0, 0, -8.0, -9.0, -26.00, -24.0, -14.5, -19.0, -10.0, -5.5, -9.00, -8.0, -12.0, -16.0, -12.0, 8.0, 2.00, -23.5, -30.5, -19.5, -11.5, -17.0, 19.50, -37.5, -22.25, -30.5, -22.5, -14.0, -17.00, -19.0, -9.0, -18.5, -1.0, -21.0, -21.50}; vsip_scalar_d ans_i[] = { -8.0, -9.0, -26.0, 14.0, 19.0, 0, -10.0, -5.5, -9.0, 24.0, 14.5, 19.0, -12.0, 8.0, 2.0, 8.0, 12.0, 16.0, 0.5, 3.0, -32.5, -20.5, -25.5, -32.5, 5.5, 4.0, 3.0, -30.5, -17.75, -25.5, -9.0, 19.0, 14.5, -21.0, 1.0, -9.5}; vsip_cblock_d *block_a = vsip_cblockbind_d(data_a_r,data_a_i,4,VSIP_MEM_NONE); vsip_cblock_d *block_b = vsip_cblockbind_d(data_b_r,data_b_i,9,VSIP_MEM_NONE); vsip_cblock_d *block = vsip_cblockcreate_d(100,VSIP_MEM_NONE); vsip_cblock_d *ans_block = vsip_cblockbind_d(ans_r,ans_i,36,VSIP_MEM_NONE); vsip_cmview_d *a = vsip_cmbind_d(block_a,0,2,2,1,2); vsip_cmview_d *t_b = vsip_cmbind_d(block_b,0,3,3,1,3); vsip_cmview_d *b = vsip_cmbind_d(block,95,-1,3,-9,3); vsip_cmview_d *c = vsip_cmcreate_d(6,6,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_d *ansm = vsip_cmbind_d(ans_block,0,6,6,1,6); vsip_cmview_d *chk = vsip_cmcreate_d(6,6,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *chk_r = vsip_mrealview_d(chk); vsip_cblockadmit_d(block_a,VSIP_TRUE); vsip_cblockadmit_d(block_b,VSIP_TRUE); vsip_cblockadmit_d(ans_block,VSIP_TRUE); vsip_cmcopy_d_d(t_b,b); printf("vsip_cmkron_d(alpha,a,b,c)\n"); vsip_cmkron_d(alpha,a,b,c); printf("alpha = %f %+fi\n",alpha.r,alpha.i); printf("matrix a\n");VU_cmprintm_d("8.6",a); printf("matrix b\n");VU_cmprintm_d("8.6",b); printf("matrix c\n");VU_cmprintm_d("8.6",c); printf("right answer\n");VU_cmprintm_d("8.4",ansm); vsip_cmsub_d(c,ansm,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(a); vsip_cmalldestroy_d(t_b); vsip_cmalldestroy_d(b); vsip_cmalldestroy_d(c); vsip_mdestroy_d(chk_r); vsip_cmalldestroy_d(chk); vsip_cmalldestroy_d(ansm); } return; } <file_sep>from vsip import * def __isSizeCompatible(a,b): if 'mview' in a.type and 'mview' in b.type: if (a.rowlength == b.rowlength) and (a.collength == b.collength): return True elif 'vview' in a.type and 'vview' in b.type: if a.length == b.length: return True else: return False # vsip_shisto_p def histo(a,b_min,b_max,op,b): """ See VSIP specification for more details. Usage: histo(in,b_min,b_max,op,out) where: in is a VSIP matrix or vector view b_min is a scalar of the same type as b indicating the minimum bin threshold b_max is a scalar of the same type as b indicating the maximum bin threshold op indicates if data is being accumulated. It should be a string either 'RESET' or 'ACCUM'. out is a vector view of the same precision as the in view. """ f={'mview_dvview_d':vsip_mhisto_d, 'mview_fvview_f':vsip_mhisto_f, 'mview_ivview_i':vsip_mhisto_i, 'mview_sivview_si':vsip_mhisto_si, 'vview_dvview_d':vsip_vhisto_d, 'vview_fvview_f':vsip_vhisto_f, 'vview_ivview_i':vsip_vhisto_i, 'vview_sivview_si':vsip_vhisto_si} assert 'pyJvsip' in repr(a),\ 'Input argument must be a pyJvsip view object for function histo' assert 'pyJvsip' in repr(b),\ 'Output argument must be a pyJvsip view object for function histo' t=a.type+b.type assert t in f,'Type <:'+t+':> not supported for freqswap' assert (isinstance(b_min,float) or isinstance(b_min,int)) and \ (isinstance(b_max,float) or isinstance(b_max,int)) if op == 1: vsipOp=VSIP_HIST_RESET elif op == 2: vsipOp=VSIP_HIST_ACCUM elif 'RESET' in op: vsipOp=VSIP_HIST_RESET elif 'ACCUM' in op: vsipOp=VSIP_HIST_ACCUM else: print('Operator flag not recognized') return if '_i' in t or '_si' in t: assert isinstance(b_min,int) and isinstance(b_max,int), \ 'Type <:'+t+':> requires int max and min bin arguments' f[t](a.vsip,int(b_min),int(b_max),vsipOp,b.vsip) return b else: f[t](a.vsip,float(b_min),float(b_max),vsipOp,b.vsip) return b # vsip_dsfreqswap_f def freqswap(a): """ Usage: freqswqp(a) Where: a is a view of precision float or double. Frequency swap is an in-place operation. For convenience the input/output view a is returned See VSIP specification for more details. """ f={'cvview_d':vsip_cvfreqswap_d, 'vview_d':vsip_vfreqswap_d, 'cmview_d':vsip_cmfreqswap_d, 'mview_d':vsip_mfreqswap_d, 'cvview_f':vsip_cvfreqswap_f, 'vview_f':vsip_vfreqswap_f, 'cmview_f':vsip_cmfreqswap_f, 'mview_f':vsip_mfreqswap_f} assert 'pyJvsip' in repr(a),\ 'Argument must be a pyJvsip view object for function freqswap' t=a.type assert t in f,'Type <:%s:> not supported for freqswap'%t f[t](a.vsip) return a <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id */ #include"VU_vprintm_si.include" static void vcopyto_user_si(void){ printf("********\nTEST vcopyto_user_si\n"); { int i; vsip_block_si *block = vsip_blockcreate_si(200,VSIP_MEM_NONE); vsip_scalar_si ans[5]={0,1,2,3,4},output[5]; vsip_vview_si *view = vsip_vbind_si(block,100,-3,5); vsip_vview_si *all = vsip_vbind_si(block,0,1,200); vsip_scalar_si check = 0; vsip_vfill_si(-1,all); vsip_vramp_si(0,1.0,view); vsip_vcopyto_user_si(view,output); VU_vprintm_si("1",view); for(i=0; i<5; i++){ printf("%d\n",(int)output[i]); check += fabs((float)(output[i] - ans[i])); } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_vdestroy_si(all); vsip_vdestroy_si(view); vsip_blockdestroy_si(block); } return; } <file_sep>import vsiputils as vsip # VU Functions def size(a): """ size(view) will return a tuple of (offset,stride,length) if view is a vsipl vector or (offset, col_stride, col_length, row_stride, row_length) if view is a vsipl matrix """ f={'vview_d':'_vsize(vsip.getattrib(a))', 'vview_f': '_vsize(vsip.getattrib(a))', 'cvview_d':'_vsize(vsip.getattrib(a))', 'cvview_f':'_vsize(vsip.getattrib(a))', 'vview_vi':'_vsize(vsip.getattrib(a))', 'vview_mi':'_vsize(vsip.getattrib(a))', 'vview_bl':'_vsize(vsip.getattrib(a))', 'vview_i':'_vsize(vsip.getattrib(a))', 'vview_si':'_vsize(vsip.getattrib(a))', 'vview_uc':'_vsize(vsip.getattrib(a))', 'mview_d':'_msize(vsip.getattrib(a))', 'mview_f':'_msize(vsip.getattrib(a))', 'cmview_d':'_msize(vsip.getattrib(a))', 'cmview_f':'_msize(vsip.getattrib(a))', 'mview_bl':'_msize(vsip.getattrib(a))', 'mview_i':'_msize(vsip.getattrib(a))', 'mview_si':'_msize(vsip.getattrib(a))', 'mview_uc':'_msize(vsip.getattrib(a))'} def _vsize(attr): return (attr.offset,attr.stride,attr.length) def _msize(attr): return (attr.offset,attr.col_stride,attr.col_length,attr.row_stride, attr.row_length) t=vsip.getType(a) if t[1] in f: return eval(f[t[1]]) else: print('Not a supported type') return False def FFTdataGenRamp(a): """ FFTdataGenRamp(v) expects argument 'v' to ba a complex VSIPL vector. The vector is filled with data which, when the fft is applied, should turn into a ramp starting a 0 with increment 1. This function is normally used for testing FFT codes. """ from math import cos as ccos,sin as ssin,pi def _gen(a): N=int(vsip.getlength(a)) npm=N/2 c=pi/float(N) vsip.put(a,0,(float(N) - 1.0)/2.0) indx=0; if N % 2: for i in range(npm): indx = i+1 x = c * float(i) + c x = -0.5j * ccos(x)/ssin(x) - 0.5 vsip.put(a,indx,x) for i in range(npm,0,-1): indx +=1 x=vsip.get(a,i) x.i=-x.i vsip.put(a,indx,x) else: npm -= 1 for i in range(npm): indx = i+1 x = c * float(i) + c x = -0.5j * ccos(x)/ssin(x) - 0.5 vsip.put(a,indx,x) x=-0.5 indx +=1 vsip.put(a,indx,x) for i in range(npm,0,-1): indx +=1 x=vsip.get(a,i) x.i=-x.i vsip.put(a,indx,x) t=vsip.getType(a) sz=() if t[0]: sz=size(a) if len(sz) == 3 and (t[1] == 'cvview_f' or t[1] == 'cvview_d'): _gen(a) return a else: print('Not a supported type. Should be a vsip complex float vector vector') return False def randCreate(t,seed,length): """ Create a VSIPL vector view and populate it with random numbers. type "t" is (for example) 'vview_dnprngU' for double vector ('vview_d') filled with uniform ('U') numbers from the non-portable random number generator ('nprng => VSIP_NPRNG'). Another example would be 'cvview_fprngN' for a complex float vector('cvview_f') tilled with a normal distribution ('N') from the VSIP defined portable random number generator ('prng' => VSIP_PRNG). """ def rcfn(t,s,f,l): a=vsip.create(t,l); s=vsip.create('rand',(s,1,1,f)) vsip.randn(s,a) vsip.destroy(s) return a def rcfu(t,s,f,l): a=vsip.create(t,l); s=vsip.create('rand',(s,1,1,f)) vsip.randu(s,a) vsip.destroy(s) return a f={'vview_dprngN':"rcfn('vview_d',seed,VSIP_PRNG,length)", 'vview_fprngN':"rcfn('vview_f',seed,VSIP_PRNG,length)", 'cvview_dprngN':"rcfn('cvview_d',seed,VSIP_PRNG,length)", 'cvview_fprngN':"rcfn('cvview_f',seed,VSIP_PRNG,length)", 'vview_dprngU':"rcfu('vview_d',seed,VSIP_PRNG,length)", 'vview_fprngU':"rcfu('vview_f',seed,VSIP_PRNG,length)", 'cvview_dprngU':"rcfu('cvview_d',seed,VSIP_PRNG,length)", 'cvview_fprngU':"rcfu('cvview_f',seed,VSIP_PRNG,length)", 'vview_dnprngN':"rcfn('vview_d',seed,VSIP_NPRNG,length)", 'vview_fnprngN':"rcfn('vview_d',seed,VSIP_NPRNG,length)", 'cvview_dnprngN':"rcfn('cvview_d',seed,VSIP_NPRNG,length)", 'cvview_fnprngN':"rcfn('cvview_f',seed,VSIP_NPRNG,length)", 'vview_dnprngU':"rcfu('vview_d',seed,VSIP_NPRNG,length)", 'vview_fnprngU':"rcfu('vview_f',seed,VSIP_NPRNG,length)", 'cvview_dnprngU':"rcfu('cvview_d',seed,VSIP_NPRNG,length)", 'cvview_fnprngU':"rcfu('cvview_f',seed,VSIP_NPRNG,length)"} if t in f: return eval(f[t]) else: print('Type ' + t + ' not supported for randCreate') return False def mprint(m,fmt): """ This function will print a VSIPL matrix or vector suitable for pasting into Octave or Matlab. usage: mprint(<vsip matrix/vector>, fmt) fmt is a string corresponding to a simple fmt statement. For instance '%6.5f' prints as 6 characters wide with 5 decimal digits. Note format converts this statement to '% 6.5f' or '%+6.5f' so keep the input simple. """ def _fmt1(c): if c != '%': return c else: return '% ' def _fmt2(c): if c != '%': return c else: return '%+' def _fmtfunc(fmt1,fmt2,y): x = vsip.cscalarToComplex(y) if type(x) == complex: return fmt1 % x.real + fmt2 % x.imag + "i" else: return fmt % x tm=['mview_d','mview_f','cmview_d','cmview_f','mview_i','mview_uc','mview_si','mview_bl'] tv=['vview_d','vview_f','cvview_d','cvview_f','vview_i','vview_uc','vview_si','vview_bl','vview_vi','vview_mi'] t=vsip.getType(m)[1] tfmt=[_fmt1(c) for c in fmt] fmt1 = "".join(tfmt) tfmt=[_fmt2(c) for c in fmt] fmt2 = "".join(tfmt) if t in tm: cl=vsip.getcollength(m) rl=vsip.getrowlength(m) for i in range(cl): M=[] for j in range(rl): M.append(_fmtfunc(fmt1,fmt2,vsip.get(m,(i,j)))) if i == 0: print("["+" ".join(M) + ";") elif i < cl-1: print(" "+" ".join(M) + ";") else: print(" "+" ".join(M) + "]") elif t in tv: l=vsip.getlength(m) V=[_fmtfunc(fmt1,fmt2,vsip.get(m,i)) for i in range(l)] print("[" + " ".join(V) + "]") else: print('Object not VSIP vector or matrix') def mstring(m,fmt): """ This function will print a VSIPL matrix or vector suitable for pasting into Octave or Matlab. usage: mprint(<vsip matrix/vector>, fmt) fmt is a string corresponding to a simple fmt statement. For instance '%6.5f' prints as 6 characters wide with 5 decimal digits. Note format converts this statement to '% 6.5f' or '%+6.5f' so keep the input simple. """ def _fmt1(c): if c != '%': return c else: return '% ' def _fmt2(c): if c != '%': return c else: return '%+' def _fmtfunc(fmt1,fmt2,y): x = vsip.cscalarToComplex(y) if type(x) == complex: s = fmt1 % x.real s += fmt2 % x.imag s += "i" return s else: return fmt1 % x tm=['mview_d','mview_f','cmview_d','cmview_f','mview_i','mview_uc','mview_si','mview_bl'] tv=['vview_d','vview_f','cvview_d','cvview_f','vview_i','vview_uc','vview_si','vview_bl','vview_vi','vview_mi'] t=vsip.getType(m)[1] tfmt=[_fmt1(c) for c in fmt] fmt1 = "".join(tfmt) tfmt=[_fmt2(c) for c in fmt] fmt2 = "".join(tfmt) if t in tm: cl=vsip.getcollength(m) rl=vsip.getrowlength(m) s=str() for i in range(cl): M=[] for j in range(rl): M.append(_fmtfunc(fmt1,fmt2,vsip.get(m,(i,j)))) if i == 0: s += "["+" ".join(M) + ";\n" elif i < cl-1: s += " "+" ".join(M) + ";\n" else: s += " "+" ".join(M) + "]\n" return s elif t in tv: l=vsip.getlength(m) V=[_fmtfunc(fmt1,fmt2,vsip.get(m,i)) for i in range(l)] return "[" + " ".join(V) + "]\n" else: print('Object not VSIP vector or matrix') def vView(x,o,s,l): """ vView(x,o,s,l) returns the view x with offset, stride and length (o,s,l) . This could also be done with vsiputils using bind(vsip.block(x),(o,s,l)) except that bind will create a new object that will need to be allocated and destroyed. vView will modify the supplied object x. """ t=['vview_f', 'vview_d', 'cvview_f','cvview_d', 'vview_i','vview_si','vview_uc','vview_vi', 'vview_bl','vview_mi'] myT=vsip.getType(x)[1] if myT in t: attr=vsip.getattrib(x) attr.offset=o; attr.stride=s; attr.length=l return vsip.putattrib(x,attr) else: print('type ' + myT + ' not supported by vView') <file_sep>/* Created RJudd */ /* VSIPL Consultant */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cmvprod3_f.c,v 2.1 2006/04/27 01:58:00 judd Exp $ */ #include"vsip.h" #include"vsip_cvviewattributes_f.h" #include"vsip_cmviewattributes_f.h" void (vsip_cmvprod3_f)( const vsip_cmview_f* A, const vsip_cvview_f* b, const vsip_cvview_f* r) { vsip_scalar_f *bp0_r = b->block->R->array + b->offset * b->block->cstride, *rp0_r = r->block->R->array + r->offset * r->block->cstride, *Ap00_r = A->block->R->array + A->offset * A->block->cstride; vsip_scalar_f *bp0_i = b->block->I->array + b->offset * b->block->cstride, *rp0_i = r->block->I->array + r->offset * r->block->cstride, *Ap00_i = A->block->I->array + A->offset * A->block->cstride; vsip_stride rst = r->stride * r->block->cstride, ARst = A->row_stride * A->block->cstride, ACst = A->col_stride * A->block->cstride, bst = b->stride * b->block->cstride; vsip_cscalar_f b0,b1,b2; vsip_cscalar_f a00, a01, a02; vsip_cscalar_f a10, a11, a12; vsip_cscalar_f a20, a21, a22; vsip_scalar_f *Ap10_r = Ap00_r + ACst, *bp1_r = bp0_r + bst, *rp1_r = rp0_r + rst; vsip_scalar_f *Ap20_r = Ap10_r + ACst, *bp2_r = bp1_r + bst, *rp2_r = rp1_r + rst; vsip_scalar_f *Ap10_i = Ap00_i + ACst, *bp1_i = bp0_i + bst, *rp1_i = rp0_i + rst; vsip_scalar_f *Ap20_i = Ap10_i + ACst, *bp2_i = bp1_i + bst, *rp2_i = rp1_i + rst; b0.r = *bp0_r; b1.r = *bp1_r; b2.r = *bp2_r; b0.i = *bp0_i; b1.i = *bp1_i; b2.i = *bp2_i; a00.r = *Ap00_r; a01.r = *(Ap00_r+ARst); a02.r = *(Ap00_r + 2 * ARst); a10.r = *Ap10_r; a11.r = *(Ap10_r+ARst); a12.r = *(Ap10_r + 2 * ARst); a20.r = *Ap20_r; a21.r = *(Ap20_r+ARst); a22.r = *(Ap20_r + 2 * ARst); a00.i = *Ap00_i; a01.i = *(Ap00_i+ARst); a02.i = *(Ap00_i + 2 * ARst); a10.i = *Ap10_i; a11.i = *(Ap10_i+ARst); a12.i = *(Ap10_i + 2 * ARst); a20.i = *Ap20_i; a21.i = *(Ap20_i+ARst); a22.i = *(Ap20_i + 2 * ARst); *rp0_r = (b0.r * a00.r + b1.r * a01.r + b2.r * a02.r) - (b0.i * a00.i + b1.i * a01.i + b2.i * a02.i); *rp1_r = (b0.r * a10.r + b1.r * a11.r + b2.r * a12.r) - (b0.i * a10.i + b1.i * a11.i + b2.i * a12.i); *rp2_r = (b0.r * a20.r + b1.r * a21.r + b2.r * a22.r) - (b0.i * a20.i + b1.i * a21.i + b2.i * a22.i); *rp0_i = b0.r * a00.i + b1.r * a01.i + b2.r * a02.i + b0.i * a00.r + b1.i * a01.r + b2.i * a02.r; *rp1_i = b0.r * a10.i + b1.r * a11.i + b2.r * a12.i + b0.i * a10.r + b1.i * a11.r + b2.i * a12.r; *rp2_i = b0.r * a20.i + b1.r * a21.i + b2.r * a22.i + b0.i * a20.r + b1.i * a21.r + b2.i * a22.r; return; } <file_sep>/* Created R Judd */ /* Copyright (c) 2006 <NAME> */ /* MIT style license, see Copyright notice in top level directory */ /* $Id: llsqsol_d.h,v 1.1 2006/05/16 16:45:18 judd Exp $ */ #include"VU_mprintm_d.include" static int llsqsol_d(void) { vsip_mview_d *A = vsip_mcreate_d(10,6,VSIP_ROW,VSIP_MEM_NONE); vsip_vview_d *ad = vsip_mdiagview_d(A,0); vsip_vview_d *ac = vsip_mcolview_d(A,0); vsip_mview_d *AT = vsip_mtransview_d(A); vsip_mview_d *XB = vsip_mcreate_d(10,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *XBs = vsip_msubview_d(XB,0,0,6,3); vsip_vview_d *xbc = vsip_mcolview_d(XB,0); vsip_mview_d *B = vsip_mcreate_d(10,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *Bs = vsip_msubview_d(B,0,0,6,3); vsip_mview_d *X = vsip_mcreate_d(6,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *ATA = vsip_mcreate_d(6,6,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *ATXB = vsip_mcreate_d(6,3,VSIP_ROW,VSIP_MEM_NONE); int i; vsip_chol_d *chol = vsip_chold_create_d(VSIP_TR_LOW,6); vsip_block_d *ablock = vsip_blockcreate_d(500,VSIP_MEM_NONE); vsip_mview_d *A1 = vsip_mbind_d(ablock,200,-3,10,-31,6); vsip_mview_d *BX1 = vsip_mbind_d(ablock,203,8,10,2,3); vsip_mview_d *BX1s = vsip_msubview_d(BX1,0,0,6,3); vsip_mfill_d(0.0,A); vsip_mfill_d(0.0,XB); printf("********\nTEST covsol_d\n"); printf("\n Test vsip_covsol_d\n"); /* need to make up some data for A */ for(i=0; i<6; i++){ vsip_vputoffset_d(ac,i); vsip_vramp_d(-1.3,1.1,ac); } vsip_vramp_d(3,1.2,ad); /* need to make up some data for XB */ for(i=0; i<3; i++){ vsip_vputoffset_d(xbc,i); vsip_vramp_d(.1,(vsip_scalar_d)i/3.0,xbc); } /* square off A and XB for use with cholesky */ vsip_mprod_d(AT,A,ATA); vsip_mprod_d(AT,XB,ATXB); vsip_mcopy_d_d(ATXB, Bs); /* Copy the original data for use with non-simple matrix */ vsip_mcopy_d_d(XB,BX1); vsip_mcopy_d_d(A,A1); /* check input data */ printf("Input Data \n"); printf("A = ");VU_mprintm_d("4.2",A); printf("\nAT * A = ");VU_mprintm_d("4.2",ATA); printf("\nXB = ");VU_mprintm_d("4.2",XB); printf("\nAT * XB =");VU_mprintm_d("4.2",ATXB); /* slove using Cholesky and ATA matrix and Bs matrix */ printf("\nSolve using cholesky and ATA matrix \n (AT * A) X = B \nfor X"); vsip_chold_d(chol,ATA); vsip_cholsol_d(chol,Bs); printf("\nX = ");VU_mprintm_d("7.5",Bs); /* check */ printf("\ncheck"); /* the following Restores ATA but chol object is no longer correct */ vsip_mprod_d(AT,A,ATA); vsip_mprod_d(ATA,Bs,X); printf("\nATA * X ="); VU_mprintm_d("4.2",X); vsip_msub_d(ATXB,X,X); { float check = (float) vsip_msumval_d(X); if(fabs(check) < .0001) printf("check = %f\ncorrect\n",check); else printf("check = %f\nerror\n",check); } /* slove using llsqsol and A, XB matrix */ printf("\nSolve\n (AT * A) X = B \nfor X"); vsip_llsqsol_d(A,XB); printf("\nXBs = ");VU_mprintm_d("7.5",XBs); vsip_msub_d(Bs,XBs,X); { float check = (float) vsip_msumval_d(X); if(fabs(check) < .0001) printf("check = %f\ncorrect\n",check); else printf("check = %f\nerror\n",check); } /* slove using llsqsol and A1,BX1 inputs */ printf("\nSolve nonstandard stride _d \n (AT * A) X = B \nfor X"); vsip_llsqsol_d(A1,BX1); vsip_mcopy_d_d(BX1s,X); printf("\nX = ");VU_mprintm_d("7.5",X); vsip_msub_d(Bs,BX1s,X); { float check = (float) vsip_msumval_d(X); if(fabs(check) < .0001) printf("check = %f\ncorrect\n",check); else printf("check = %f\nerror\n",check); } vsip_mdestroy_d(A1); vsip_mdestroy_d(BX1); vsip_mdestroy_d(BX1s); vsip_blockdestroy_d(ablock); vsip_vdestroy_d(ad); vsip_vdestroy_d(ac); vsip_vdestroy_d(xbc); vsip_mdestroy_d(AT); vsip_malldestroy_d(A); vsip_mdestroy_d(XBs); vsip_malldestroy_d(XB); vsip_malldestroy_d(X); vsip_mdestroy_d(Bs); vsip_malldestroy_d(B); vsip_malldestroy_d(ATA); vsip_malldestroy_d(ATXB); vsip_chold_destroy_d(chol); return 0; } <file_sep>/* Created RJudd */ /* */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmvprod3_d.h,v 2.1 2006/04/27 01:40:55 judd Exp $ */ #include"VU_cmprintm_d.include" #include"VU_cvprintm_d.include" static void cmvprod3_d(void){ printf("********\nTEST cmvprod3_d\n"); { vsip_scalar_d datav_r[] = {1.0, 2.0, 3.0}; vsip_scalar_d datav_i[] = {5.0, 4.0, 3.0}; vsip_scalar_d datam_r[] = { .1, .2, .3, 1.0, 1.1, 1.2, 2.1, 2.2, 2.3}; vsip_scalar_d datam_i[] = { 1.1, 2.2, 3.3, -1.0, 0.1, 0.2, 1.1, 3.2, 4.3}; vsip_scalar_d ans_data_r[] = { 0.0, 0.0, 0.0 }; vsip_scalar_d ans_data_i[] = { 0.0, 0.0, 0.0 }; vsip_cblock_d *blockv = vsip_cblockbind_d(datav_r,datav_i,3,VSIP_MEM_NONE); vsip_cblock_d *blockm = vsip_cblockbind_d(datam_r,datam_i,9,VSIP_MEM_NONE); vsip_cblock_d *block_ans = vsip_cblockbind_d(ans_data_r,ans_data_i,3,VSIP_MEM_NONE); vsip_cblock_d *block = vsip_cblockcreate_d(70,VSIP_MEM_NONE); vsip_cvview_d *v = vsip_cvbind_d(blockv,0,1,3); vsip_cmview_d *m = vsip_cmbind_d(blockm,0,1,3,3,3); vsip_cvview_d *ans = vsip_cvbind_d(block_ans,0,1,3); vsip_cvview_d *b = vsip_cvbind_d(block,5,-1,3); vsip_cmview_d *a = vsip_cmbind_d(block,50,-2,3,-8,3); vsip_cvview_d *c = vsip_cvbind_d(block,49,-2,3); vsip_cvview_d *chk = vsip_cvcreate_d(3,VSIP_MEM_NONE); vsip_vview_d *chk_i = vsip_vimagview_d(chk); vsip_cblockadmit_d(blockv,VSIP_TRUE); vsip_cblockadmit_d(blockm,VSIP_TRUE); vsip_cblockadmit_d(block_ans,VSIP_TRUE); vsip_cvcopy_d_d(v,b); vsip_cmcopy_d_d(m,a); vsip_cmvprod_d(a,b,ans); vsip_cmvprod3_d(a,b,c); printf("vsip_cmvprod3_d(a,b,c)\n"); printf("m\n"); VU_cmprintm_d("6.4",m); printf("a\n"); VU_cmprintm_d("6.4",a); printf("v\n"); VU_cvprintm_d("6.4",v); printf("b\n"); VU_cvprintm_d("6.4",b); printf("c\n"); VU_cvprintm_d("6.4",c); printf("right answer\n"); VU_cvprintm_d("6.4",ans); vsip_cvsub_d(c,ans,chk); vsip_cvmag_d(chk,chk_i); vsip_vclip_d(chk_i,.0001,.0001,0,1,chk_i); if(vsip_vsumval_d(chk_i) > .5) printf("error\n"); else printf("correct\n"); vsip_cvalldestroy_d(v); vsip_cmalldestroy_d(m); vsip_cvalldestroy_d(ans); vsip_cvdestroy_d(b); vsip_cmdestroy_d(a); vsip_cvalldestroy_d(c); vsip_vdestroy_d(chk_i); vsip_cvalldestroy_d(chk); } return; } <file_sep>/* Created RJudd March 18, 2012 */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"vsip.h" #include"VI_mimagview_d.h" #include"VI_mcopy_d_d.h" void vsip_mimag_d(const vsip_cmview_d* a, const vsip_mview_d* r){ vsip_mview_d R; VI_mimagview_d(a,&R); VI_mcopy_d_d(&R,r); } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: crvdiv_f.h,v 2.0 2003/02/22 15:23:22 judd Exp $ */ #include"VU_vprintm_f.include" #include"VU_cvprintm_f.include" static void crvdiv_f(void){ printf("\n********\nTEST crvdiv_f\n"); { vsip_vview_f *b = vsip_vcreate_f(7,VSIP_MEM_NONE); vsip_cvview_f *a = vsip_cvcreate_f(7,VSIP_MEM_NONE); vsip_cvview_f *c = vsip_cvcreate_f(7,VSIP_MEM_NONE); vsip_vview_f *c_i = vsip_vimagview_f(c); vsip_cvview_f *chk = vsip_cvcreate_f(7,VSIP_MEM_NONE); vsip_vview_f *chk_i = vsip_vimagview_f(chk); vsip_scalar_f data[] = {1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7}; vsip_scalar_f data_r[] ={.1, .2, .3, .4, .5, .6, .7}; vsip_scalar_f data_i[] ={7,6,5,4,3,2,1}; vsip_scalar_f data_ans[] ={ 0.1000, 7.0000, 0.1818, 5.4545, 0.2500, 4.1667, 0.3077, 3.0769, 0.3571, 2.1429, 0.4000 , 1.3333, 0.4375 , 0.6250}; vsip_block_f *block = vsip_blockbind_f(data,7,VSIP_MEM_NONE); vsip_cblock_f *cblock = vsip_cblockbind_f(data_r,data_i,7,VSIP_MEM_NONE); vsip_cblock_f *cblock_ans = vsip_cblockbind_f(data_ans, (vsip_scalar_f*)NULL,7,VSIP_MEM_NONE); vsip_vview_f *u_b = vsip_vbind_f(block,0,1,7); vsip_cvview_f *u_a = vsip_cvbind_f(cblock,0,1,7); vsip_cvview_f *u_ans = vsip_cvbind_f(cblock_ans,0,1,7); vsip_blockadmit_f(block,VSIP_TRUE); vsip_cblockadmit_f(cblock,VSIP_TRUE); vsip_cblockadmit_f(cblock_ans,VSIP_TRUE); vsip_vcopy_f_f(u_b,b); vsip_cvcopy_f_f(u_a,a); printf("call vsip_crvdiv_f(a,b,c)\n"); printf("a =\n");VU_cvprintm_f("8.6",a); printf("b =\n");VU_vprintm_f("8.6",b); printf("test normal out of place\n"); vsip_crvdiv_f(a,b,c); printf("c =\n");VU_cvprintm_f("8.6",c); printf("right answer =\n");VU_cvprintm_f("8.4",u_ans); vsip_cvsub_f(u_ans,c,chk); vsip_cvmag_f(chk,chk_i); vsip_vclip_f(chk_i,.0002,.0002,0,1,chk_i); if(vsip_vsumval_f(chk_i) > .5) printf("error\n"); else printf("correct\n"); printf("test a,c inplace\n"); vsip_crvdiv_f(a,b,a); vsip_cvsub_f(u_ans,a,chk); vsip_cvmag_f(chk,chk_i); vsip_vclip_f(chk_i,.0002,.0002,0,1,chk_i); if(vsip_vsumval_f(chk_i) > .5) printf("error\n"); else printf("correct\n"); printf("test in place b= imaginary(c)\n"); vsip_vcopy_f_f(u_b,c_i); vsip_cvcopy_f_f(u_a,a); vsip_crvdiv_f(a,c_i,c); vsip_cvsub_f(u_ans,c,chk); vsip_cvmag_f(chk,chk_i); vsip_vclip_f(chk_i,.0002,.0002,0,1,chk_i); if(vsip_vsumval_f(chk_i) > .5) printf("error\n"); else printf("correct\n"); vsip_valldestroy_f(b); vsip_cvalldestroy_f(a); vsip_vdestroy_f(c_i); vsip_cvalldestroy_f(c); vsip_vdestroy_f(chk_i); vsip_cvalldestroy_f(chk); vsip_valldestroy_f(u_b); vsip_cvalldestroy_f(u_a); vsip_cvalldestroy_f(u_ans); } return; } <file_sep>// // modulateEx.swift // vsip // // Created by <NAME> on 4/20/17. // Copyright © 2017 JVSIP. All rights reserved. // import Foundation import vsip func modulate_cd(length: vsip_length) { let _ = vsip_init(nil) let vo = vsip_cvcreate_d(length, VSIP_MEM_NONE) let vin = vsip_vcreate_d(length, VSIP_MEM_NONE) let rnd = vsip_randcreate(8, 1, 1, VSIP_PRNG) vsip_vrandn_d(rnd,vin) vsip_vmodulate_d(vin, Double.pi/3.0, Double.pi/10.0, vo) for i in 0..<length { let x = vsip_cvget_d(vo,i) print("\(x.r) + \(x.i)i") } vsip_valldestroy_d(vin) vsip_cvalldestroy_d(vo) vsip_randdestroy(rnd) let _ = vsip_finalize(nil) } <file_sep>/* * svd7_d.h * * Created by <NAME> on 10/03/08. * Copyright 2008 Home. All rights reserved. * */ #include"VU_mprintm_d.include" #include"VU_vprintm_d.include" static void svd7_d(void){ printf("********\nTEST svd7 for double\n"); { vsip_index i; vsip_length M=9, N=9; vsip_scalar_d data[81] = { \ 8.96933746, -2.73806572, 1.43051147e-06, 0, 0, 0, -24.4797363, -0.863142371, 1.43051147e-06,\ -2.73806572, 1.62158346, -1.43051147e-06, 0, 0, 0, 7.47291851, 0.511184692, -1.43051147e-06,\ 1.43051147e-06, -1.43051147e-06, 4, 0, 0, 0, -3.33786011e-06, -4.47034836e-07, 3.90333748,\ 0, 0, 0, 8.96933746, -2.73806572, 1.43051147e-06, 1.85705733, 1.05920994, 1.1920929e-07,\ 0, 0, 0, -2.73806572, 1.62158346, -1.43051147e-06, -0.566903055, -0.627303123, -1.04308128e-07,\ 0, 0, 0, 1.43051147e-06, -1.43051147e-06, 4, 2.98023224e-07, 5.66244125e-07, 0.295684814,\ -24.4797363, 7.47291851, -3.33786011e-06, 1.85705733, -0.566903055, 2.98023224e-07, 67.1962814, 2.57505178, -3.81469727e-06,\ -0.863142371, 0.511184692, -4.47034836e-07, 1.05920994, -0.627303123, 5.66244125e-07, 2.57505178, 0.403814614, -4.17232513e-07,\ 1.43051147e-06, -1.43051147e-06, 3.90333748, 1.1920929e-07, -1.04308128e-07, 0.295684814, -3.81469727e-06, -4.17232513e-07, 3.83086824 }; vsip_vview_d *s = vsip_vcreate_d(((M > N) ? N : M),VSIP_MEM_NONE); vsip_sv_d *svd = vsip_svd_create_d(M,N,VSIP_SVD_UVFULL,VSIP_SVD_UVFULL); vsip_block_d *block = vsip_blockbind_d(data,(M * N),VSIP_MEM_NONE); vsip_mview_d *A0 = vsip_mbind_d(block,0,1,M,M,N); vsip_block_d *vblk = vsip_blockcreate_d(600,VSIP_MEM_NONE); vsip_mview_d *A = vsip_mbind_d(vblk,3,3, M,3*M , N); vsip_mview_d *U = vsip_mcreate_d(M,M,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *V = vsip_mcreate_d(N,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *B = vsip_mcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_d(block,VSIP_TRUE); vsip_mcopy_d_d(A0,A); printf("in = ");VU_mprintm_d("6.3",A); if(vsip_svd_d(svd,A,s)){ printf("svd error\n"); return; } /* create the singular value matrix */ vsip_mfill_d(0.0,B); for(i=0; i<vsip_vgetlength_d(s); i++) vsip_mput_d(B,i,i,vsip_vget_d(s,i)); vsip_svdmatu_d(svd, 0, M-1, U); vsip_svdmatv_d(svd, 0, N-1, V); printf("U = ");VU_mprintm_d("12.10",U); printf("B = ");VU_mprintm_d("12.10",B); printf("V = ");VU_mprintm_d("12.10",V); VU_vprintm_d("12.10",s); { /* check that A0 = U * B * V' */ vsip_scalar_mi mi; vsip_scalar_d chk = 1.0; vsip_scalar_d lim = 5 * FLT_EPSILON * fabs(vsip_mmaxmgval_d(A0,&mi)); vsip_mview_d *dif=vsip_mcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *out = vsip_mcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *Vt = vsip_mtransview_d(V); vsip_mprod_d(U,B,dif); vsip_mprod_d(dif,Vt,out); vsip_msub_d(out,A0,dif); vsip_mmag_d(dif, dif); chk = vsip_msumval_d(dif)/(2 * M * N); printf("%20.18e - %20.18e = %e\n",lim,chk, (lim - chk)); if(chk > lim){ printf("error\n"); } else { printf("correct\n"); } vsip_malldestroy_d(dif); vsip_malldestroy_d(out); vsip_mdestroy_d(Vt); } vsip_svd_destroy_d(svd); vsip_malldestroy_d(A0); vsip_malldestroy_d(A); vsip_valldestroy_d(s); vsip_malldestroy_d(U); vsip_malldestroy_d(B); vsip_malldestroy_d(V); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: ctmisc_view_d.h,v 2.1 2009/09/05 18:01:45 judd Exp $ */ static void ctmisc_view_d(void){ printf("********\nTEST ctmisc_view_d\n"); { vsip_index k,j,i; /* if a problem with tcreate is suspected check both leading and trailing options here */ vsip_scalar_d data_r[4][3][4] = { {{0.0, 0.01, 0.02, 0.03}, \ { 0.1, 0.11, 0.12, 0.13}, \ { 0.2, 0.21, 0.22, 0.23}},{ \ { 1.0, 1.01, 1.02, 1.03}, \ { 1.1, 1.11, 1.12, 1.13}, \ { 1.2, 1.21, 1.22, 1.23}},{ \ { 2.0, 2.01, 2.02, 2.03}, \ { 2.1, 2.11, 2.12, 2.13}, \ { 2.2, 2.21, 2.22, 2.23}},{ \ { 3.0, 3.01, 3.02, 3.03}, \ { 3.1, 3.11, 3.12, 3.13}, \ { 3.2, 3.21, 3.22, 3.23}}}; vsip_scalar_d data_i[4][3][4] = { {{0.0, -0.01, -0.02, -0.03}, \ {-0.1, -0.11, -0.12, -0.13}, \ {-0.2, -0.21, -0.22, -0.23}},{ \ {-1.0, -1.01, -1.02, -1.03}, \ {-1.1, -1.11, -1.12, -1.13}, \ {-1.2, -1.21, -1.22, -1.23}},{ \ {-2.0, -2.01, -2.02, -2.03}, \ {-2.1, -2.11, -2.12, -2.13}, \ {-2.2, -2.21, -2.22, -2.23}},{ \ {-3.0, -3.01, -3.02, -3.03}, \ {-3.1, -3.11, -3.12, -3.13}, {-3.2, -3.21, -3.22, -3.23}}}; vsip_ctview_d *tview_a = vsip_ctcreate_d(12,9,12,VSIP_LEADING,VSIP_MEM_NONE); /* vsip_ctview_d *tview_a = vsip_ctcreate_d(12,9,12,VSIP_TRAILING,VSIP_MEM_NONE); */ vsip_cblock_d *block_a = vsip_ctgetblock_d(tview_a); vsip_ctview_d *tview_b = vsip_ctsubview_d(tview_a,1,2,3,4,3,4); vsip_stride z_a_st = vsip_ctgetzstride_d(tview_a); vsip_stride y_a_st = vsip_ctgetystride_d(tview_a); vsip_stride x_a_st = vsip_ctgetxstride_d(tview_a); vsip_offset b_o_calc = z_a_st + 2 * y_a_st + 3 * x_a_st; vsip_offset b_o_get = vsip_ctgetoffset_d(tview_b); vsip_ctview_d *v = vsip_ctbind_d(block_a,b_o_calc, z_a_st,4, y_a_st,3, x_a_st,4); vsip_cmview_d *mview = (vsip_cmview_d*)NULL; vsip_cvview_d *vview = (vsip_cvview_d*)NULL; vsip_ctview_d *tview = (vsip_ctview_d*)NULL; vsip_cscalar_d a; vsip_scalar_d chk = 0; printf("z_a_st %d; y_a_st %d; x_a_st %d\n",(int)z_a_st,(int)y_a_st,(int)x_a_st); fflush(stdout); printf("b_o_calc %u; b_o_get %u\n",(unsigned)b_o_calc,(unsigned)b_o_get); fflush(stdout); for(k = 0; k < 4; k++){ for(j = 0; j < 3; j++){ for(i = 0; i < 4; i++){ a.r = data_r[k][j][i]; a.i = data_i[k][j][i]; vsip_ctput_d(v,k,j,i,a); } } } printf("test ctmatrixview_d\n"); printf("TMZY\n"); fflush(stdout); for(i = 0; i < 4; i++){ mview = vsip_ctmatrixview_d(v,VSIP_TMZY,i); for(j = 0; j < 3; j++){ for(k = 0; k < 4; k++){ a = vsip_cmget_d(mview,k,j); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } vsip_cmdestroy_d(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TMYX\n"); fflush(stdout); for(k = 0; k < 4; k++){ mview = vsip_ctmatrixview_d(v,VSIP_TMYX,k); for(j = 0; j < 3; j++){ for(i = 0; i < 4; i++){ a = vsip_cmget_d(mview,j,i); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } vsip_cmdestroy_d(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TMZX\n"); fflush(stdout); for(j = 0; j < 3; j++){ mview = vsip_ctmatrixview_d(v,VSIP_TMZX,j); for(k = 0; k < 4; k++){ for(i = 0; i < 4; i++){ a = vsip_cmget_d(mview,k,i); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } vsip_cmdestroy_d(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test ctvectview_d\n"); printf("TVX \n"); fflush(stdout); for(k=0; k<4; k++){ for(j=0; j<3; j++){ vview = vsip_ctvectview_d(v,VSIP_TVX,k,j); for(i=0; i<4; i++){ a = vsip_cvget_d(vview,i); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } vsip_cvdestroy_d(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test ctvectview_d\n"); printf("TVY \n"); fflush(stdout); for(k=0; k<4; k++){ for(i=0; i<4; i++){ vview = vsip_ctvectview_d(v,VSIP_TVY,k,i); for(j=0; j<3; j++){ a = vsip_cvget_d(vview,j); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } vsip_cvdestroy_d(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TVZ \n"); fflush(stdout); for(j=0; j<3; j++){ for(i=0; i<4; i++){ vview = vsip_ctvectview_d(v,VSIP_TVZ,j,i); for(k=0; k<4; k++){ a = vsip_cvget_d(vview,k); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } vsip_cvdestroy_d(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test cttransview_d\n"); fflush(stdout); printf("NOP\n"); fflush(stdout); tview = vsip_cttransview_d(v,VSIP_TTRANS_NOP); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_ctget_d(tview,k,j,i); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } } vsip_ctdestroy_d(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YX\n"); fflush(stdout); tview = vsip_cttransview_d(v,VSIP_TTRANS_YX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_ctget_d(tview,k,i,j); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } } vsip_ctdestroy_d(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("ZY\n"); fflush(stdout); tview = vsip_cttransview_d(v,VSIP_TTRANS_ZY); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_ctget_d(tview,j,k,i); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } } vsip_ctdestroy_d(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("ZX\n"); fflush(stdout); tview = vsip_cttransview_d(v,VSIP_TTRANS_ZX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_ctget_d(tview,i,j,k); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } } vsip_ctdestroy_d(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YXZY\n"); fflush(stdout); tview = vsip_cttransview_d(v,VSIP_TTRANS_YXZY); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_ctget_d(tview,i,k,j); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } } vsip_ctdestroy_d(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YXZX\n"); fflush(stdout); tview = vsip_cttransview_d(v,VSIP_TTRANS_YXZX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_ctget_d(tview,j,i,k); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } } vsip_ctdestroy_d(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; vsip_ctdestroy_d(v); vsip_ctdestroy_d(tview_b); vsip_ctalldestroy_d(tview_a); } return; } <file_sep>// // Block.swift // vsip // // Created by <NAME> on 4/21/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import vsip //MARK: Block Class public class Block { public enum Types: String{ case f case d case cf case cd case si case i case li case uc case vi case mi case bl } fileprivate class Block_f{ var vsip : OpaquePointer? let owner = true let jInit : JVSIP let precision = "f" let depth = "r" init(length : Int){ self.vsip = vsip_blockcreate_f(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_blockdestroy_f(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_f id \(jInit.myId.int32Value)") } } } fileprivate class DBlock_f{ // Derived Block var vsip : OpaquePointer? var parent : Block let owner = false let precision = "f" let depth = "r" let jInit : JVSIP init(block : Block, cVsipDerivedBlock : OpaquePointer){ self.parent = block self.vsip = cVsipDerivedBlock jInit = JVSIP() } deinit{ vsip_blockdestroy_f(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_f (derived) id \(jInit.myId.int32Value)") } } } fileprivate class Block_d{ var vsip : OpaquePointer? let owner = true let jInit : JVSIP let precision = "d" let depth = "r" init(length : Int){ self.vsip = vsip_blockcreate_d(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_blockdestroy_d(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_d id \(jInit.myId.int32Value)") } } } fileprivate class DBlock_d{ var vsip : OpaquePointer? var parent : Block let owner = false let precision = "f" let depth = "r" let jInit : JVSIP init(block : Block, cVsipDerivedBlock : OpaquePointer){ self.parent = block self.vsip = cVsipDerivedBlock jInit = JVSIP() } deinit{ vsip_blockdestroy_d(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_d (derived) id \(jInit.myId.int32Value)") } } } fileprivate class Block_cf{ var vsip : OpaquePointer? let jInit : JVSIP let precision = "f" let depth = "c" init(length : Int){ self.vsip = vsip_cblockcreate_f(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_cblockdestroy_f(self.vsip!) if _isDebugAssertConfiguration(){ print("cblockdestroy_f id \(jInit.myId.int32Value)") } } } fileprivate class Block_cd{ var vsip : OpaquePointer? let jInit : JVSIP let precision = "f" let depth = "r" init(length : Int){ self.vsip = vsip_cblockcreate_d(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_cblockdestroy_d(self.vsip!) if _isDebugAssertConfiguration(){ print("cblockdestroy_d id \(jInit.myId.int32Value)") } } } fileprivate class Block_vi{ var vsip : OpaquePointer? let jInit : JVSIP let precision = "vi" let depth = "r" init(length : Int){ self.vsip = vsip_blockcreate_vi(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_blockdestroy_vi(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_vi id \(jInit.myId.int32Value)") } } } fileprivate class Block_si{ var vsip : OpaquePointer? let jInit : JVSIP let precision = "si" let depth = "r" init(length : Int){ self.vsip = vsip_blockcreate_si(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_blockdestroy_si(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_si id \(jInit.myId.int32Value)") } } } fileprivate class Block_i{ var vsip : OpaquePointer? let jInit : JVSIP let precision = "i" let depth = "r" init(length : Int){ self.vsip = vsip_blockcreate_i(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_blockdestroy_i(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_i id \(jInit.myId.int32Value)") } } } fileprivate class Block_li{ var vsip : OpaquePointer? let jInit : JVSIP let precision = "li" let depth = "r" init(length : Int){ self.vsip = vsip_blockcreate_li(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_blockdestroy_li(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_li id \(jInit.myId.int32Value)") } } } fileprivate class Block_bl{ var vsip : OpaquePointer? let jInit : JVSIP let precision = "bool" let depth = "r" init(length : Int){ self.vsip = vsip_blockcreate_bl(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_blockdestroy_bl(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_bl id \(jInit.myId.int32Value)") } } } fileprivate class Block_uc{ var vsip : OpaquePointer? let jInit : JVSIP let precision = "uc" let depth = "r" init(length : Int){ self.vsip = vsip_blockcreate_uc(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_blockdestroy_uc(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_uc id \(jInit.myId.int32Value)") } } } fileprivate class Block_mi{ var vsip : OpaquePointer? let jInit : JVSIP let precision = "vi" let depth = "m" init(length : Int){ self.vsip = vsip_blockcreate_mi(vsip_length(length), VSIP_MEM_NONE) jInit = JVSIP() } deinit{ vsip_blockdestroy_mi(self.vsip!) if _isDebugAssertConfiguration(){ print("blockdestroy_mi id \(jInit.myId.int32Value)") } } } // MARK: Block Attributes fileprivate(set) public var type: Block.Types fileprivate(set) var jVsip : AnyObject? fileprivate(set) public var length : Int fileprivate var owner = true var myId : NSNumber? // create normal block public init(length : Int, type : Block.Types){ switch type { case .f: let b = Block_f(length : length) jVsip = b self.myId = b.jInit.myId case .d: let b = Block_d(length : length) jVsip = b self.myId = b.jInit.myId case .cf: let b = Block_cf(length : length) jVsip = b self.myId = b.jInit.myId case .cd: let b = Block_cd(length : length) jVsip = b self.myId = b.jInit.myId case .i: let b = Block_i(length : length) jVsip = b self.myId = b.jInit.myId case .li: let b = Block_li(length : length) jVsip = b self.myId = b.jInit.myId case .si: let b = Block_si(length : length) jVsip = b self.myId = b.jInit.myId case .uc: let b = Block_uc(length : length) jVsip = b self.myId = b.jInit.myId case .vi: let b = Block_vi(length : length) jVsip = b self.myId = b.jInit.myId case .mi: let b = Block_mi(length : length) jVsip = b self.myId = b.jInit.myId case .bl: let b = Block_bl(length : length) jVsip = b self.myId = b.jInit.myId } self.length = length self.type = type } // create special block for derived blocks public init(block : Block, cVsipDerivedBlock : OpaquePointer){ self.length = block.length self.owner = false switch block.type{ case .cf: let b = DBlock_f(block: block, cVsipDerivedBlock: cVsipDerivedBlock) jVsip = b type = Block.Types.f myId = b.jInit.myId case .cd: let b = DBlock_d(block: block, cVsipDerivedBlock: cVsipDerivedBlock) jVsip = b type = Block.Types.d myId = b.jInit.myId default: jVsip = nil type = block.type } } // Vector bind returns vsip object (may be null on malloc failure) var vsip: OpaquePointer?{ switch self.type { case .f: let blk = self.jVsip as! Block_f if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } case .d: let blk = self.jVsip as! Block_d if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } case .cf: let blk = self.jVsip as! Block_cf if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } case .cd: let blk = self.jVsip as! Block_cd if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } case .i: let blk = self.jVsip as! Block_i if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } case .li: let blk = self.jVsip as! Block_li if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } case .si: let blk = self.jVsip as! Block_si if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } case .uc: let blk = self.jVsip as! Block_uc if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } case .vi: let blk = self.jVsip as! Block_vi if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } case .mi: let blk = self.jVsip as! Block_mi if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } case .bl: let blk = self.jVsip as! Block_bl if let vsip = blk.vsip { return vsip } else { preconditionFailure("No vsip object in Block") } } } // Return JVSIP Swift View object. Allows block.bind for shape vector public func bind(_ offset : Int, stride : Int, length : Int) -> Vector { return Vector(block: self, offset: offset, stride: stride, length: length) } // Return JVSIP Swift View object. Allows block.bind for shape matrix public func bind(_ offset : Int, columnStride : Int, columnLength : Int, rowStride : Int, rowLength : Int) -> Matrix { return Matrix(block: self, offset: offset, columnStride: columnStride, columnLength: columnLength, rowStride: rowStride, rowLength: rowLength) } public func vector() -> Vector{ return self.bind(0, stride: 1, length: self.length) } } <file_sep>// // View.swift // vsip // // Created by <NAME> on 4/21/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import vsip public class View { public enum Shape: String { case v // vector case m // matrix } let block: Block let shape : Shape var type: Block.Types{ return block.type } let jInit : JVSIP var myId = NSNumber(value: 0 as Int32) // Used to initialize a derived JVSIP View object public init(block: Block, shape: View.Shape){ self.block = block self.shape = shape jInit = JVSIP() myId = jInit.myId } func real(_ vsip: OpaquePointer) -> (Block, OpaquePointer){ let t = (self.type, self.shape) switch t{ case (.cf, .v): if let cRealView = vsip_vrealview_f(vsip) { let blk = vsip_vgetblock_f(cRealView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cRealView) } else { break } case(.cf, .m): if let cRealView = vsip_mrealview_f(vsip){ let blk = vsip_mgetblock_f(cRealView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cRealView) } else { break } case (.cd, .v): if let cRealView = vsip_vrealview_d(vsip){ let blk = vsip_vgetblock_d(cRealView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cRealView) } else { break } case (.cd, .m): if let cRealView = vsip_mrealview_d(vsip){ let blk = vsip_mgetblock_d(cRealView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cRealView) } else { break } default: print("Case not found") break } preconditionFailure("Failure of imag method") } public func imag(_ vsip: OpaquePointer) -> (Block?, OpaquePointer?){ let t = (self.type, self.shape) switch t{ case (.cf, .v): if let cImagView = vsip_vimagview_f(vsip){ let blk = vsip_vgetblock_f(cImagView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cImagView) } else { break } case(.cf, .m): if let cImagView = vsip_mimagview_f(vsip){ let blk = vsip_mgetblock_f(cImagView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cImagView) } else { break } case (.cd, .v): if let cImagView = vsip_vimagview_d(vsip){ let blk = vsip_vgetblock_d(cImagView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cImagView) } else { break } case (.cd, .m): if let cImagView = vsip_mimagview_d(vsip){ let blk = vsip_mgetblock_d(cImagView) return (Block(block: self.block, cVsipDerivedBlock: blk!), cImagView) } else { break } default: print("Case not found") break } preconditionFailure("Failure of imag method") } // MARK: Attribute get/put options public func get(_ vsip:OpaquePointer, index: vsip_index) -> (Block.Types?, NSNumber?, NSNumber?){ let t = self.type switch t{ case .f: return (t, NSNumber(value: vsip_vget_f(vsip, index) as Float), nil) case .d: return (t, NSNumber(value: vsip_vget_d(vsip, index) as Double), nil) case .cf: let ans = vsip_cvget_f(vsip, index) return (t, NSNumber(value: ans.r as Float), NSNumber(value: ans.i as Float)) case .cd: let ans = vsip_cvget_d(vsip,index) return (t, NSNumber(value: ans.r as Double), NSNumber(value: ans.i as Double)) case .vi: return (t, NSNumber(value: vsip_vget_vi(vsip,index) as UInt), nil) case .mi: let ans = vsip_vget_mi(vsip,index) return (t, NSNumber(value: ans.c as UInt), NSNumber(value: ans.r as UInt)) case .li: return (t, NSNumber(value: vsip_vget_li(vsip,index) as Int), nil) case .i: return (t, NSNumber(value: vsip_vget_i(vsip,index) as Int32), nil) case .si: return (t, NSNumber(value: vsip_vget_si(vsip,index) as Int16), nil) case .uc: return (t, NSNumber(value: vsip_vget_uc(vsip,index) as UInt8), nil) default: return (nil, nil, nil) } } public func get(_ vsip:OpaquePointer, rowIndex: vsip_index, columnIndex: vsip_index) -> (Block.Types?, NSNumber?, NSNumber?){ let t = self.type switch t{ case .f: return (t, NSNumber(value: vsip_mget_f(vsip, rowIndex, columnIndex) as Float), nil) case .d: return (t, NSNumber(value: vsip_mget_d(vsip, rowIndex, columnIndex) as Double), nil) case .cf: let ans = vsip_cmget_f(vsip, rowIndex, columnIndex) return (t, NSNumber(value: ans.r as Float), NSNumber(value: ans.i as Float)) case .cd: let ans = vsip_cmget_d(vsip,rowIndex, columnIndex) return (t, NSNumber(value: ans.r as Double), NSNumber(value: ans.i as Double)) case .li: return (t, NSNumber(value: vsip_mget_li(vsip,rowIndex, columnIndex) as Int), nil) case .i: return (t, NSNumber(value: vsip_mget_i(vsip,rowIndex, columnIndex) as Int32), nil) case .si: return (t, NSNumber(value: vsip_mget_si(vsip,rowIndex, columnIndex) as Int16), nil) case .uc: return (t, NSNumber(value: vsip_mget_uc(vsip,rowIndex, columnIndex) as UInt8), nil) default: return (nil, nil, nil) } } public func put(_ vsip:OpaquePointer, index: vsip_index, value: (Block.Types?, NSNumber?, NSNumber?)){ let t = self.type switch t{ case .f: let vsipValue = value.1! vsip_vput_f(vsip, index, vsipValue.floatValue) case .d: let vsipValue = value.1! vsip_vput_d(vsip, index, vsipValue.doubleValue) case .cf: let arg = vsip_cmplx_f(value.1!.floatValue, value.2!.floatValue) vsip_cvput_f(vsip,index,arg) case .cd: let arg = vsip_cmplx_d(value.1!.doubleValue, value.2!.doubleValue) vsip_cvput_d(vsip,index,arg) case .vi: let vsipValue = value.1! vsip_vput_vi(vsip,index,vsipValue.uintValue) case .mi: let arg = vsip_matindex(value.1!.uintValue, value.2!.uintValue) vsip_vput_mi(vsip,index,arg) case .li: let vsipValue = value.1! vsip_vput_li(vsip, index, vsipValue.intValue) case .i: let vsipValue = value.1! vsip_vput_i(vsip,index,vsipValue.int32Value) case .si: let vsipValue = value.1! vsip_vput_si(vsip,index,vsipValue.int16Value) case .uc: let vsipValue = value.1! vsip_vput_uc(vsip,index,vsipValue.uint8Value) default: break } } public func put(_ vsip:OpaquePointer, rowIndex: vsip_index, columnIndex: vsip_index, value: (Block.Types?, NSNumber?, NSNumber?)){ let t = self.type switch t{ case .f: let vsipValue = value.1!.floatValue vsip_mput_f(vsip, rowIndex, columnIndex, vsipValue) case .d: let vsipValue = value.1! vsip_mput_d(vsip, rowIndex, columnIndex, vsipValue.doubleValue) case .cf: let arg = vsip_cmplx_f(value.1!.floatValue, value.2!.floatValue) vsip_cmput_f(vsip, rowIndex, columnIndex,arg) case .cd: let arg = vsip_cmplx_d(value.1!.doubleValue, value.2!.doubleValue) vsip_cmput_d(vsip, rowIndex, columnIndex,arg) case .li: let vsipValue = value.1! vsip_mput_li(vsip, rowIndex, columnIndex, vsipValue.intValue) case .i: let vsipValue = value.1! vsip_mput_i(vsip, rowIndex, columnIndex,vsipValue.int32Value) case .si: let vsipValue = value.1! vsip_mput_si(vsip, rowIndex, columnIndex,vsipValue.int16Value) case .uc: let vsipValue = value.1! vsip_mput_uc(vsip, rowIndex, columnIndex,vsipValue.uint8Value) default: break } } // MARK: Conversion to String and Print public func scalarString(_ format : String, value : (Block.Types?, NSNumber?, NSNumber?)) -> String{ var retval = "" switch value.0! { case .f: let fmt = "%" + format + "f" retval = String(format: fmt, value.1!.floatValue) break case .d: let fmt = "%" + format + "f" retval = String(format: fmt, value.1!.doubleValue) break case .cf: let fmt1 = "%" + format + "f" let fmt2 = "%+" + format + "f" let r = String(format: fmt1, value.1!.floatValue) let i = String(format: fmt2, value.2!.floatValue) retval = r + i + "i" break case .cd: let fmt1 = "%" + format + "f" let fmt2 = "%+" + format + "f" let r = String(format: fmt1, value.1!.doubleValue) let i = String(format: fmt2, value.2!.doubleValue) retval = r + i + "i" break default: let fmt = "%" + format + "d" retval = String(format: fmt, value.1!.intValue) break } return retval } public func formatFmt(_ fmt: String) -> String{ var retval = "" func charCheck(_ char: Character) -> Bool { let validChars = "0123456789." for item in validChars.characters{ if char == item { return true } } return false } for char in fmt.characters{ if charCheck(char){ retval.append(char) } } return retval } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_attrib_i.h,v 2.0 2003/02/22 15:23:33 judd Exp $ */ static void get_put_attrib_i(void){ printf("********\nTEST get_put_attrib_i\n"); { vsip_offset ivo = 3; vsip_stride ivs = 2; vsip_length ivl = 3; vsip_offset jvo = 2; vsip_stride jvs = 3; vsip_length jvl = 5; vsip_stride irs = 1, ics = 3; vsip_length irl = 2, icl = 3; vsip_stride jrs = 5, jcs = 2; vsip_length jrl = 5, jcl = 2; vsip_stride ixs = 2, iys = 4, izs = 14; vsip_length ixl = 2, iyl = 3, izl = 4; vsip_stride jxs = 4, jys = 14, jzs = 2; vsip_length jxl = 3, jyl = 4, jzl = 2; vsip_block_i *b = vsip_blockcreate_i(80,VSIP_MEM_NONE); vsip_vview_i *v = vsip_vbind_i(b,ivo,ivs,ivl); vsip_mview_i *m = vsip_mbind_i(b,ivo,ics,icl,irs,irl); vsip_tview_i *t = vsip_tbind_i(b,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_vattr_i attr; vsip_mattr_i mattr; vsip_tattr_i tattr; printf("test vgetattrib_i\n"); fflush(stdout); { vsip_vgetattrib_i(v,&attr); (attr.offset == ivo) ? printf("offset correct\n") : printf("offset error \n"); (attr.stride == ivs) ? printf("stride correct\n") : printf("stride error \n"); (attr.length == ivl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputattrib_i\n"); fflush(stdout); { attr.offset = jvo; attr.stride = jvs; attr.length = jvl; vsip_vputattrib_i(v,&attr); vsip_vgetattrib_i(v,&attr); (attr.offset == jvo) ? printf("offset correct\n") : printf("offset error \n"); (attr.stride == jvs) ? printf("stride correct\n") : printf("stride error \n"); (attr.length == jvl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /**************************************************************************/ printf("test mgetattrib_i\n"); fflush(stdout); { vsip_mgetattrib_i(m,&mattr); (mattr.offset == ivo) ? printf("offset correct\n") : printf("offset error \n"); (mattr.col_stride == ics) ? printf("col_stride correct\n") : printf("col_stride error \n"); (mattr.row_stride == irs) ? printf("row_stride correct\n") : printf("row_stride error \n"); (mattr.col_length == icl) ? printf("col_length correct\n") : printf("col_length error \n"); (mattr.row_length == irl) ? printf("row_length correct\n") : printf("row_length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputattrib_i\n"); fflush(stdout); { mattr.offset = jvo; mattr.col_stride = jcs; mattr.col_length = jcl; mattr.row_stride = jrs; mattr.row_length = jrl; vsip_mputattrib_i(m,&mattr); vsip_mgetattrib_i(m,&mattr); (mattr.offset == jvo) ? printf("offset correct\n") : printf("offset error \n"); (mattr.col_stride == jcs) ? printf("col_stride correct\n") : printf("col_stride error \n"); (mattr.col_length == jcl) ? printf("col_length correct\n") : printf("col_length error \n"); (mattr.row_stride == jrs) ? printf("row_stride correct\n") : printf("row_stride error \n"); (mattr.row_length == jrl) ? printf("row_length correct\n") : printf("row_length error \n"); fflush(stdout); } /**************************************************************************/ printf("test tgetattrib_i\n"); fflush(stdout); { vsip_tgetattrib_i(t,&tattr); (tattr.offset == ivo) ? printf("offset correct\n") : printf("offset error \n"); (tattr.z_stride == izs) ? printf("z_stride correct\n") : printf("z_stride error \n"); (tattr.z_length == izl) ? printf("z_length correct\n") : printf("z_length error \n"); (tattr.y_stride == iys) ? printf("y_stride correct\n") : printf("y_stride error \n"); (tattr.y_length == iyl) ? printf("y_length correct\n") : printf("y_length error \n"); (tattr.x_stride == ixs) ? printf("x_stride correct\n") : printf("x_stride error \n"); (tattr.x_length == ixl) ? printf("x_length correct\n") : printf("x_length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputattrib_i\n"); fflush(stdout); { tattr.offset = jvo; tattr.z_stride = jzs; tattr.z_length = jzl; tattr.y_stride = jys; tattr.y_length = jyl; tattr.x_stride = jxs; tattr.x_length = jxl; vsip_tputattrib_i(t,&tattr); vsip_tgetattrib_i(t,&tattr); (tattr.offset == jvo) ? printf("offset correct\n") : printf("offset error \n"); (tattr.z_stride == jzs) ? printf("z_stride correct\n") : printf("z_stride error \n"); (tattr.z_length == jzl) ? printf("z_length correct\n") : printf("z_length error \n"); (tattr.y_stride == jys) ? printf("y_stride correct\n") : printf("y_stride error \n"); (tattr.y_length == jyl) ? printf("y_length correct\n") : printf("y_length error \n"); (tattr.x_stride == jxs) ? printf("x_stride correct\n") : printf("x_stride error \n"); (tattr.x_length == jxl) ? printf("x_length correct\n") : printf("x_length error \n"); fflush(stdout); } vsip_vdestroy_i(v); vsip_mdestroy_i(m); vsip_talldestroy_i(t); } return; } <file_sep># About Note that J is the first letter of my last name. The letter V generaly stands for VSIPL (vector signal image processing library); a project I have worked on for years. I am retired and do this as a hobby. The AppleXcode directory is where I keep code specific to Apple. So naming a swift project will generally include the letters V and J and S for swift. This directory predates swift so also includes some efforts not including swift. ## JVSwift.workspace Not everything in the AppleXcode directory falls under this workspace but a lot does. In the begining I tried mightily to create an importable Swift module for C VSIPL. The only way I could figure out how to make this work was to put everything in the same workspace. That way playgrounds and other swift code could find my **vsip** module. ### vsip module The vsip group contains the **vsip** module. Make this first. Be carefull. The **c** source code contained in the **vsip** project is the same source code that is made for the **C VSIPL** library and is also used by the Python code. It resides in the **c_VSIP_src** directory in the root of the **jvsip** project. ### Playgrounds Examples of using the **vsip** module are in **example20, example18, and KOmegaBFEx*. The **PngEx* playground doesn't really have anything to do with VSIPL. Just figuring out how to do a bitmap. Other playgrounds (like **TryIt*) are just for playing while trying to figure things out. ### SJVsip and SwiftVsip These projects are proof of concept for encapsulating **C VSIPL** in an object oriented Swift module. The **SJVsip** project is the newest effort. ### Other projects I have some other projects where I am trying to learn how to use various features of Cocoa and other Xcode technologies. They are not very complete. The directory **jvsipF* is not part of the JVSwift workspace. It contains an earlier effort to build a C VSIPL framework. <file_sep>/* Created By RJudd June 16, 2002 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_fftw_obj.h,v 2.0 2003/02/22 15:18:32 judd Exp $ */ /* object to encapsulate fftwone function for fft's */ #ifndef _VI_FFTW_OBJ_H #define _VI_FFTW_OBJ_H #include<fftw.h> #include"vsip.h" #include"vsip_cvviewattributes_f.h" #include"vsip_cvviewattributes_d.h" #include<VU.h> typedef struct { fftw_complex *in; fftw_complex *out; fftw_plan p; } vsipl_fftw_obj; #ifdef __VSIPL_FFTWOBJ_INIT static vsipl_fftw_obj *vsipl_fftwobj_create(){ return (vsipl_fftw_obj*) malloc(sizeof(vsipl_fftw_obj)); } static int vsipl_fftwobj_init( vsipl_fftw_obj* *obj, fftw_direction dir, /* direction of fft */ int n, /* length of fft */ int flags){ int retval = 0; *obj = vsipl_fftwobj_create(); if(obj != NULL){ #if defined(VSIP_ASSUME_COMPLEX_IS_INTERLEAVED) (*obj)->in = NULL; (*obj)->out = NULL; #else (*obj)->in = (fftw_complex*)malloc(n * sizeof(fftw_complex)); if((*obj)->in == NULL) retval++; (*obj)->out = (fftw_complex*)malloc(n * sizeof(fftw_complex)); if((*obj)->out == NULL) retval++; #endif (*obj)->p = fftw_create_plan(n,dir,flags); if((*obj)->p == NULL) retval++; } else { retval++; } return retval; } #endif #ifdef __VSIPL_FFTWOBJ_FIN static void vsipl_fftwobj_fin( vsipl_fftw_obj *obj) { if(obj != NULL){ if(obj->in != NULL) free(obj->in); if(obj->out != NULL) free(obj->out); if(obj->p != NULL) fftw_destroy_plan(obj->p); free(obj); } return; } #endif #ifdef __VSIPL_CVCOPY_TO_FFTW_F static void vsipl_cvcopy_to_fftw_f( const vsip_cvview_f *v, vsipl_fftw_obj *obj){ vsip_length n = v->length; fftw_complex *ptr = obj->in; vsip_offset offset = v->offset * v->block->R->rstride; vsip_scalar_f *ptr_r = v->block->R->array + offset; vsip_scalar_f *ptr_i = v->block->I->array + offset; vsip_stride str = v->block->R->rstride * v->stride; while(n-- > 0){ (*ptr).re = (fftw_real)*ptr_r; (*ptr).im = (fftw_real)*ptr_i; ptr++; ptr_r += str; ptr_i += str; } } #endif #ifdef __VSIPL_CVCOPY_FROM_FFTW_F static void vsipl_cvcopy_from_fftw_f( vsipl_fftw_obj *obj, const vsip_cvview_f *v){ vsip_length n = v->length; fftw_complex *ptr = obj->out; vsip_offset offset = v->offset * v->block->R->rstride; vsip_scalar_f *ptr_r = v->block->R->array + offset; vsip_scalar_f *ptr_i = v->block->I->array + offset; vsip_stride str = v->block->R->rstride * v->stride; while(n-- > 0){ *ptr_r = (vsip_scalar_f)((*ptr).re); *ptr_i = (vsip_scalar_f)((*ptr).im); ptr++; ptr_r += str; ptr_i += str; } } #endif #ifdef __VSIPL_CVCOPY_TO_FFTW_D static void vsipl_cvcopy_to_fftw_d( const vsip_cvview_d *v, vsipl_fftw_obj *obj){ vsip_length n = v->length; fftw_complex *ptr = obj->in; vsip_offset offset = v->offset * v->block->R->rstride; vsip_scalar_d *ptr_r = v->block->R->array + offset; vsip_scalar_d *ptr_i = v->block->I->array + offset; vsip_stride str = v->block->R->rstride * v->stride; while(n-- > 0){ (*ptr).re = (fftw_real)*ptr_r; (*ptr).im = (fftw_real)*ptr_i; ptr++; ptr_r += str; ptr_i += str; } } #endif #ifdef __VSIPL_CVCOPY_FROM_FFTW_D static void vsipl_cvcopy_from_fftw_d( vsipl_fftw_obj *obj, const vsip_cvview_d *v){ vsip_length n = v->length; fftw_complex *ptr = obj->out; vsip_offset offset = v->offset * v->block->R->rstride; vsip_scalar_d *ptr_r = v->block->R->array + offset; vsip_scalar_d *ptr_i = v->block->I->array + offset; vsip_stride str = v->block->R->rstride * v->stride; while(n-- > 0){ *ptr_r = (vsip_scalar_d)((*ptr).re); *ptr_i = (vsip_scalar_d)((*ptr).im); ptr++; ptr_r += str; ptr_i += str; } } #endif #endif /* _VI_FFTW_OBJ_H */ <file_sep>/* Created RJudd October 3, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_ctsubview_f.c,v 2.0 2003/02/22 15:18:49 judd Exp $ */ #define VI_CTVIEW_F_ #include"VI_support_cpriv_f.h" vsip_ctview_f *vsip_ctsubview_f( const vsip_ctview_f *v, vsip_index z_index, vsip_index y_index, vsip_index x_index, vsip_length P, vsip_length M, vsip_length N) { vsip_ctview_f *ctsubview = VI_ctview_f(); *ctsubview = *v; ctsubview->offset += z_index * v->z_stride + y_index * v->y_stride + x_index * v->x_stride; ctsubview->z_length = P; ctsubview->y_length = M; ctsubview->x_length = N; return ctsubview; } <file_sep>/* Created RJudd */ /* */ #include"VU_mprintm_d.include" static void mfreqswap_d(void){ printf("*********\nTEST vfreqswap_d\n"); { vsip_length M=6,N=5; vsip_mview_d *a = vsip_mcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_vview_d *v = vsip_vbind_d(vsip_mgetblock_d(a),0,1,M*N); vsip_mview_d *ans = vsip_mcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_scalar_d dta[]={ 18.0, 19.0, 20.0, 16.0, 17.0, 23.0, 24.0, 25.0, 21.0, 22.0, 28.0, 29.0, 30.0, 26.0, 27.0, 3.0, 4.0, 5.0, 1.0, 2.0, 8.0, 9.0, 10.0, 6.0, 7.0, 13.0, 14.0, 15.0, 11.0, 12.0}; vsip_mcopyfrom_user_d(dta,VSIP_ROW,ans); vsip_vramp_d (1,1,v); printf("input matrix\n"); VU_mprintm_d("3.1",a); vsip_mfreqswap_d(a); printf("output matrix\n"); VU_mprintm_d("3.1",a); { vsip_msub_d(a,ans,ans); if(fabs(vsip_mmaxval_d(ans,NULL)) > .00001){ printf("error\n"); }else{ printf("correct\n"); } } vsip_vdestroy_d(v); vsip_malldestroy_d(a); vsip_malldestroy_d(ans); } } <file_sep>//: Playground - noun: a place where people can play import Cocoa import vsip let path = Bundle.main.resourcePath var fname = path?.appending("/Cheby_Window") let _ = vsip_init(nil) let ripple = 100 let Nlength = 101 let Cw = vsip_vcreate_cheby_d(vsip_length(Nlength),vsip_scalar_d(ripple),vsip_memory_hint(rawValue: 0)); let fft = vsip_ccfftip_create_d(vsip_length(Nlength),1.0,VSIP_FFT_FWD,0,vsip_alg_hint(rawValue: 0)); let FCW = vsip_cvcreate_d(vsip_length(Nlength),vsip_memory_hint(rawValue: 0)); /*printf("CW = "); VU_vprintm_d("%6.8f ;\n",Cw); */ VU_vfprintyg_d(format: "%6.8f\n",a: Cw!,fname: "/Users/judd/local/sandboxes/Cheby_Window"); for i in 0..<Nlength{ vsip_vget_d(Cw!, vsip_index(i)) } vsip_cvfill_d(vsip_cmplx_d(0,0),FCW); let rv = vsip_vrealview_d(FCW); vsip_vcopy_d_d(Cw,rv); vsip_ccfftip_d(fft,FCW); vsip_vcmagsq_d(FCW,rv); var ind: vsip_index = 0 let max = vsip_vmaxval_d(rv,&ind); let min = max/(10e12); vsip_vclip_d(rv,min,max,min,max,rv); vsip_vlog10_d(rv,rv) vsip_svmul_d(10,rv,rv) VU_vfreqswapIP_d(b: rv!) VU_vfprintyg_d(format: "%6.8f\n",a: rv!,fname: "/Users/judd/local/sandboxes/Cheby_Window_Frequency_Response") for i in 0..<vsip_vgetlength_d(rv!) { vsip_vget_d(rv!, vsip_index(i)) } vsip_vdestroy_d(rv); vsip_fft_destroy_d(fft) vsip_valldestroy_d(Cw) vsip_cvalldestroy_d(FCW) vsip_finalize(nil) <file_sep>/* Created By RJudd June 16, 2002 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_crfftop_create_d_fftw.h,v 2.1 2003/03/08 14:43:33 judd Exp $ */ /* complex to real fft */ #include"VI_fft_building_blocks_d.h" #define __VSIPL_FFTWOBJ_INIT #define __VSIPL_FFTWOBJ_FIN #include"VI_fftw_obj.h" #include"VI_vrealview_d.h" #include"VI_vimagview_d.h" vsip_fft_d* vsip_crfftop_create_d(vsip_length N, vsip_scalar_d scale, unsigned int ntimes, vsip_alg_hint hint) { vsip_fft_d *fft = (vsip_fft_d*) malloc(sizeof(vsip_fft_d)); vsipl_fftw_obj *obj; fftw_direction fftw_dir = FFTW_BACKWARD; int flags = (hint == VSIP_ALG_TIME) ? FFTW_MEASURE : FFTW_ESTIMATE; int init; if(fft == NULL) return (vsip_fft_d*) NULL; fft->N = N/2; fft->scale = scale; fft->d = VSIP_FFT_INV; fft->pn = NULL; fft->p0 = NULL; fft->pF = NULL; fft->wt = (vsip_cvview_d*)NULL; fft->index = (NULL); fft->hint = hint; fft->ntimes = ntimes; fft->type = VSIP_CRFFTOP; fft->temp = vsip_cvcreate_d(fft->N+1,VSIP_MEM_NONE); init = vsipl_fftwobj_init(&obj,fftw_dir,fft->N,flags); /* need some storage to keep from overwriting input */ if(obj->in == NULL){ obj->in = (fftw_complex*)malloc(fft->N * sizeof(fftw_complex)); } if(obj->in == NULL) init++; if((init!=0) || (fft->temp == (vsip_cvview_d*)NULL)){ if(init != 0) vsipl_fftwobj_fin(obj); if(fft->temp != NULL) vsip_cvdestroy_d(fft->temp); free(fft); return (vsip_fft_d*)NULL; } fft->ext_fft_obj = (void*)obj; { vsip_vview_d wt1,wt2; vsip_vview_d *wtR = VI_vrealview_d(fft->temp,&wt1); vsip_vview_d *wtI = VI_vimagview_d(fft->temp,&wt2); vsip_vramp_d((vsip_scalar_d)0, (vsip_scalar_d)VI_ft_d_PI/fft->N,wtR); vsip_vsin_d(wtR,wtI); vsip_vcos_d(wtR,wtR); } return fft; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mgather_d.h,v 2.0 2003/02/22 15:23:24 judd Exp $ */ #include"VU_mprintm_d.include" #include"VU_vprintm_d.include" #include"VU_vprintm_mi.include" void mgather_d(void){ printf("\n******\nTEST mgather_d\n"); { vsip_scalar_d data1[]= {1,.1, 2,.2, 3,.3, 4,-.1, 5,-.3, 6,-.4, 7,.8, 8,.9, 9,-1}; vsip_scalar_vi data_index[] = {0,1 , 1,1 , 2,3 , 3,3 , 2,1}; vsip_scalar_d data_ans[] = { .1, .3, -.4, .9, -.3}; vsip_mview_d *a = vsip_mbind_d( vsip_blockbind_d(data1,18,VSIP_MEM_NONE),0,4,4,1,4); vsip_vview_mi *index = vsip_vbind_mi(/* matrix index is always interleaved */ vsip_blockbind_mi(data_index,5,VSIP_MEM_NONE),0,1,5); vsip_vview_d *ans = vsip_vbind_d( vsip_blockbind_d(data_ans,5,VSIP_MEM_NONE),0,1,5); vsip_vview_d *c = vsip_vcreate_d(5,VSIP_MEM_NONE); vsip_vview_d *chk = vsip_vcreate_d(5,VSIP_MEM_NONE); vsip_blockadmit_d(vsip_mgetblock_d(a),VSIP_TRUE); vsip_blockadmit_mi(vsip_vgetblock_mi(index),VSIP_TRUE); vsip_blockadmit_d(vsip_vgetblock_d(ans),VSIP_TRUE); printf("call vsip_mgather_d(a,index,c) \n"); vsip_mgather_d(a,index,c); printf("a =\n");VU_mprintm_d("8.6",a); printf("index =\n");VU_vprintm_mi("",index); printf("c=\n");VU_vprintm_d("8.6",c); printf("\nright answer =\n"); VU_vprintm_d("6.4",ans); vsip_vsub_d(ans,c,chk); vsip_vmag_d(chk,chk); vsip_vclip_d(chk,0,2 * .0001,0,1,chk); if(fabs(vsip_vsumval_d(chk)) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_d(a); vsip_valldestroy_mi(index); vsip_valldestroy_d(c); vsip_valldestroy_d(chk); } return; } <file_sep>/* Created RJudd */ /* */ #include"VU_vprintm_f.include" static void interpolate_spline_f(void) { printf("*********\nTEST spline for float\n"); { vsip_length N0 = 11; vsip_spline_f *spl = vsip_spline_create_f(N0); vsip_length N = 50; vsip_index index; vsip_vview_f *yf = vsip_vcreate_f(N,VSIP_MEM_NONE); vsip_vview_f *xf = vsip_vcreate_f(N,VSIP_MEM_NONE); vsip_vview_f *xp = vsip_vcreate_f(N0,VSIP_MEM_NONE); vsip_vview_f *yp = vsip_vcreate_f(N0,VSIP_MEM_NONE); vsip_vview_f *yf_ans=vsip_vcreate_f(N,VSIP_MEM_NONE); vsip_vramp_f(0.0,1.0,xp); vsip_vramp_f(0.0,0.204,xf); vsip_svmul_f(2.0/5.0 * M_PI,xp,yp); vsip_svmul_f(2.0/5.0 * M_PI,xf,yf_ans); vsip_vsin_f(yp,yp); vsip_vsin_f(yf_ans,yf_ans); printf("xp = \n");VU_vprintm_f("5.4",xp); printf("yp = \n");VU_vprintm_f("5.4",yp); printf("xf = \n");VU_vprintm_f("5.4",xf); vsip_vinterp_spline_f(xp,yp,spl,xf,yf); printf("spline = \n");VU_vprintm_f("5.4",yf); printf("ans = \n");VU_vprintm_f("5.4",yf_ans); vsip_vsub_f(yf_ans,yf,yf_ans); vsip_vmag_f(yf_ans,yf_ans); if(vsip_vmaxval_f(yf_ans,&index) < .01) printf("correct\n"); else printf("error\n"); vsip_spline_destroy_f(spl); vsip_valldestroy_f(xf); vsip_valldestroy_f(xp); vsip_valldestroy_f(yp); vsip_valldestroy_f(yf); vsip_valldestroy_f(yf_ans); } } <file_sep>/* Created R Judd */ /* Copyright (c) 2006 <NAME> */ /* MIT style license, see Copyright notice in top level directory */ /* $Id: cllsqsol_f.h,v 1.1 2006/05/16 16:45:18 judd Exp $ */ #include"VU_cmprintm_f.include" static int cllsqsol_f(void) { vsip_cmview_f *A = vsip_cmcreate_f(10,6,VSIP_ROW,VSIP_MEM_NONE); vsip_cvview_f *ad = vsip_cmdiagview_f(A,0); vsip_vview_f *ad_r = vsip_vrealview_f(ad); vsip_vview_f *ad_i = vsip_vimagview_f(ad); vsip_cvview_f *ac = vsip_cmcolview_f(A,0); vsip_cmview_f *BX = vsip_cmcreate_f(10,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cvview_f *bxr = vsip_cmrowview_f(BX,0); vsip_cmview_f *B = vsip_cmcreate_f(10,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *Bs = vsip_cmsubview_f(B,0,0,6,3); vsip_cmview_f *X = vsip_cmcreate_f(6,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *Ans = vsip_cmcreate_f(6,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *AHA = vsip_cmcreate_f(6,6,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *AH = vsip_cmcreate_f(6,10,VSIP_ROW,VSIP_MEM_NONE); vsip_cblock_f *ablock = vsip_cblockcreate_f(500,VSIP_MEM_NONE); vsip_cmview_f *A1 = vsip_cmbind_f(ablock,200,-3,10,-31,6); vsip_cmview_f *BX1 = vsip_cmbind_f(ablock,203,8,10,2,3); vsip_cmview_f *BX1s = vsip_cmsubview_f(BX1,0,0,6,3); vsip_cchol_f *chol = vsip_cchold_create_f(VSIP_TR_LOW,6); vsip_cscalar_f a0 = vsip_cmplx_f(0.0,0.0); int i; vsip_cmfill_f(a0,A); vsip_cmfill_f(a0,BX); vsip_cmfill_f(a0,AHA); printf("********\nTEST cllsqsol_f\n"); printf("Test covariance solver vsip_cllsqsol_f\n"); /* need to make up some data */ for(i=0; i<6; i++){ vsip_cvputoffset_f(ac,i); { vsip_vview_f *ac_r = vsip_vrealview_f(ac); vsip_vview_f *ac_i = vsip_vimagview_f(ac); vsip_vramp_f(-1.3,1.1,ac_r); vsip_vramp_f(+1.3,-1.1,ac_i); vsip_vdestroy_f(ac_r); vsip_vdestroy_f(ac_i); } } for(i=0; i<10; i++){ vsip_cvputoffset_f(bxr,i*3); { vsip_vview_f *bxr_r = vsip_vrealview_f(bxr); vsip_vview_f *bxr_i = vsip_vimagview_f(bxr); vsip_vramp_f(.1,(vsip_scalar_f)i/3.0,bxr_r); vsip_vramp_f(.1,(vsip_scalar_f)i/4.0,bxr_i); vsip_vdestroy_f(bxr_r);vsip_vdestroy_f(bxr_i); } } vsip_vramp_f(3,1.2,ad_r); vsip_vramp_f(3,-1.2,ad_i); vsip_cmherm_f(A,AH); vsip_cmprod_f(AH,A,AHA); vsip_cmcopy_f_f(BX,BX1); vsip_cmcopy_f_f(A,A1); /* check input data */ printf("Input data \n"); printf("A = ");VU_cmprintm_f("4.2",A); printf("\nAH * A = ");VU_cmprintm_f("4.2",AHA); printf("\nBX = ");VU_cmprintm_f("4.2",BX); /* solve using Cholesky and AHA matrix */ printf("\nSolve using Cholesky and calculated AHA \n (AH * A) X = B \nfor X"); vsip_cmprod_f(AH,BX,Bs); printf("\nBs = ");VU_cmprintm_f("4.2",Bs); vsip_cmcopy_f_f(Bs,X); vsip_cchold_f(chol,AHA); vsip_ccholsol_f(chol,Bs); vsip_cmcopy_f_f(Bs,Ans); printf("\nBs = ");VU_cmprintm_f("7.5",Bs); /* check */ printf("\ncheck"); vsip_cmprod_f(AH,A,AHA); vsip_cmprod_f(AHA,Ans,Bs); printf("\nAHA * Bs ="); VU_cmprintm_f("4.2",Bs); vsip_cmsub_f(X,Bs,X); { float check = (float) vsip_cmmeansqval_f(X); if(fabs(check) < .0001) printf("\ncheck = %f\ncorrect\n",check); else printf("\ncheck = %f\nerror\n",check); } printf("\nsolve using cqrd_f and cqrsol_f with A matrix\n"); /* solve using cqrsol and A matrix */ { vsip_cqr_f *qr = vsip_cqrd_create_f(vsip_cmgetcollength_f(A),vsip_cmgetrowlength_f(A),VSIP_QRD_SAVEQ); vsip_cmcopy_f_f(BX,B); printf("\nSolve using qr and A\n (AH * A) X = B \nfor X"); vsip_cqrd_f(qr,A1); vsip_cqrsol_f(qr,VSIP_LLS,B); printf("\nBs = ");VU_cmprintm_f("7.5",Bs); /* check */ printf("\ncheck"); vsip_cmsub_f(Ans,Bs,X); { float check = (float) vsip_cmmeansqval_f(X); if(fabs(check) < .0001) printf("\ncheck = %f\ncorrect\n",check); else printf("\ncheck = %f\nerror\n",check); } vsip_cmcopy_f_f(A,A1); vsip_cqrd_destroy_f(qr); } vsip_cmcopy_f_f(BX,B); /* solve using covsol and A matrix*/ printf("Solve using cllsqsol_f and simple input matrix\n"); printf("\nSolve\n (AH * A) X = B \nfor X"); vsip_cllsqsol_f(A,B); printf("\nAHA * X ="); VU_cmprintm_f("7.5",Bs); vsip_cmsub_f(Ans,Bs,X); { float check = (float) vsip_cmmeansqval_f(X); if(fabs(check) < .0001) printf("\ncheck = %f\ncorrect\n",check); else printf("\ncheck = %f\nerror\n",check); } /* solve using covsol and A1,BX1 inputs */ printf("\nSolve using cllsqsol_f and nonstandard stride \n (AH * A) X = B \nfor X"); printf("\nSolving ||AX-B|| (2 norm) for X"); printf("\nA on input");VU_cmprintm_f("7.5",A1); printf("\nB on input");VU_cmprintm_f("7.5",BX1); vsip_cllsqsol_f(A1,BX1); printf("\nX on output");VU_cmprintm_f("7.5",BX1s); printf("\nAHA * X ="); VU_cmprintm_f("7.5",BX1s); vsip_cmsub_f(Ans,BX1s,X); { float check = (float) vsip_cmmeansqval_f(X); if(fabs(check) < .0001) printf("check = %f\ncorrect\n",check); else printf("\ncheck = %f\nerror\n",check); } vsip_cmdestroy_f(A1); vsip_cmdestroy_f(BX1); vsip_cmdestroy_f(BX1s); vsip_cblockdestroy_f(ablock); vsip_cvdestroy_f(ac); vsip_vdestroy_f(ad_i); vsip_vdestroy_f(ad_r); vsip_cvdestroy_f(ad); vsip_cmalldestroy_f(A); vsip_cmalldestroy_f(AH); vsip_cvdestroy_f(bxr); vsip_cmalldestroy_f(BX); vsip_cmalldestroy_f(X); vsip_cmalldestroy_f(Ans); vsip_cmdestroy_f(Bs); vsip_cmalldestroy_f(B); vsip_cmalldestroy_f(AHA); vsip_cchold_destroy_f(chol); return 0; } <file_sep>#include<stdio.h> #include<vsip.h> #include"param.h" #include"ts.h" #include"kw.h" int main(int argc, char** argv){ int retval = 0; int i, Navg; param_obj param; kw_obj kw; ts_obj ts; vsip_mview_f *dtaIn, *gramOut; if(retval += param_read(argv[1],&param)){ printf("Failed to read parameter file\n"); exit(-1); } param_log(&param); kw_init(&kw, &param); ts_init(&ts, &param); /* simulate time series and beamform */ Navg = (int) param.Navg; dtaIn = ts_instance(&ts); gramOut = kw_instance(&kw); kw_zero(&kw); for(i=0; i<Navg; i++){ ts_zero(&ts); ts_sim_noise(&ts); ts_sim_nb(&ts); komega(&kw,dtaIn); } /* beamform done. Gram should be in gramOut */ /*************/ /* Massage gram data and save to file for plotting */ for(i=0; i<vsip_mgetrowlength_f(gramOut); i++) {/* move zero to middle */ vsip_vview_f *v = vsip_mcolview_f(gramOut, i); vsip_vfreqswap_f(v); vsip_vdestroy_f(v); } {/* massage the data for plot*/ vsip_scalar_f max = vsip_mmaxval_f(gramOut, NULL),min; vsip_scalar_f avg = vsip_mmeanval_f(gramOut); vsip_mclip_f(gramOut,0.0, max, avg/100000.0, max, gramOut); vsip_mlog10_f(gramOut,gramOut); min = -vsip_mminval_f(gramOut, NULL); vsip_smadd_f(min, gramOut, gramOut); max = vsip_mmaxval_f(gramOut, NULL); vsip_smmul_f(1.0/max, gramOut, gramOut); } { /* output data and plot with octave */ FILE *fptr = fopen("gramOut","w"); size_t size = vsip_mgetrowlength_f(gramOut) * vsip_mgetcollength_f(gramOut); vsip_scalar_f *out = (vsip_scalar_f*)malloc(size * sizeof(vsip_scalar_f)); vsip_mcopyto_user_f(gramOut, VSIP_COL, out); fwrite(out,size,sizeof(vsip_scalar_f),fptr); fclose(fptr); free(out); } /* cleanup */ kw_fin(&kw); ts_fin(&ts); param_free(&param); return retval; } <file_sep>#ifndef _KW_H #define _KW_H 1 #include<vsip.h> #include"param.h" /* * k-omega object structure * Nfreq => Number of frequencies in cm_freq; * cm_freq => array to hold output of FFT's * rm_freq => real view of cm_freq to hold powers. * data_gram => User data array to hold output data * m_gram => Matrix associated with data_gram * rcfftm => FFT from time to frequency space * ccfftm => FFT across array to direction space * ts_taper => Time series data taper * array_taper => Array data taper */ typedef struct{ vsip_length Nfreq; /* Nts/2 + 1 */ int Navg; /* Scale factor for number of averages */ vsip_cmview_f *cm_freq; /* (Nsens, Nfreq) col maj */ vsip_mview_f *rm_freq; /* (Nsens, Nts) rwo maj */ vsip_mview_f *m_gram; /* (Nsens, Nfreq) col maj */ vsip_fftm_f *rcfftm; /* by row Nsens by Nts */ vsip_fftm_f *ccfftm; /* by col Nsens by Nfreq */ vsip_vview_f *ts_taper; /* of length Nts */ vsip_vview_f *array_taper; /* of length Nsens */ } kw_obj; int kw_init(kw_obj*, param_obj*); void kw_fin(kw_obj*); void komega( kw_obj*, vsip_mview_f*); void kw_zero( kw_obj*); vsip_mview_f *kw_instance(kw_obj*); #endif /* _KW_H */ <file_sep>//: Playground - noun: a place where people can play import Foundation import vsip import SJVsip let zero = Scalar(0.0) let fmt = "4.3" let aMatrix = Matrix(columnLength: 5, rowLength: 4, type: .d, major: VSIP_ROW) aMatrix.randn(8, portable: true) let aMatrixCp = aMatrix.newCopy let (Q,R) = aMatrixCp.qr let chk = aMatrix.empty chk.fill(zero) prod(Q, times: R, resultsIn: chk) aMatrix.mPrint(fmt) chk.mPrint(fmt) <file_sep>/* Created RJudd */ /* */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* */ /* $Id: mprod3_f.h,v 2.1 2006/04/27 01:40:55 judd Exp $ */ #include"VU_mprintm_f.include" static void mprod3_f(void){ printf("********\nTEST mprod4_f\n"); { vsip_scalar_f datal[] = {1.0, 2.0, 4.0, 5.0, 5.0, 0.2, 2.0, 0.0, 1.0}; vsip_scalar_f datar[] = {0.1, 0.2, 0.3, 0.4, 1.0, 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 2.4, -1.1, -1.2, -1.3, -1.4, 2.1, 2.2, 0.3, 3.2, 2.1, 2.2, 1.0, 5.1}; vsip_scalar_f ans_data[] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; vsip_block_f *blockl = vsip_blockbind_f(datal,9,VSIP_MEM_NONE); vsip_block_f *blockr = vsip_blockbind_f(datar,24,VSIP_MEM_NONE); vsip_block_f *block_ans = vsip_blockbind_f(ans_data,24,VSIP_MEM_NONE); vsip_block_f *block = vsip_blockcreate_f(200,VSIP_MEM_NONE); vsip_mview_f *ml = vsip_mbind_f(blockl,0,3,3,1,3); vsip_mview_f *mr = vsip_mbind_f(blockr,0,8,3,1,8); vsip_mview_f *ans = vsip_mbind_f(block_ans,0,8,3,1,8); vsip_mview_f *a = vsip_mbind_f(block,20,-1,3,-4,3); vsip_mview_f *a_cm = vsip_mcreate_f(3,3,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *a_rm = vsip_mcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *b_cm = vsip_mcreate_f(3,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *b_rm = vsip_mcreate_f(3,8,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *c_cm = vsip_mcreate_f(3,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *c_rm = vsip_mcreate_f(3,8,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *b = vsip_mbind_f(block,100,-1,3,-6,8); vsip_mview_f *c = vsip_mbind_f(block,150,-8,3,-1,8); vsip_mview_f *chk = vsip_mcreate_f(3,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *aa = vsip_mcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *bb = vsip_mcreate_f(3,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *cc = vsip_mcreate_f(3,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *c_cc = vsip_cmcreate_f(3,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *c_bb = vsip_cmcreate_f(3,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *i_cc = vsip_mimagview_f(c_cc); vsip_mview_f *r_bb = vsip_mrealview_f(c_bb); vsip_blockadmit_f(blockl,VSIP_TRUE); vsip_blockadmit_f(blockr,VSIP_TRUE); vsip_blockadmit_f(block_ans,VSIP_TRUE); vsip_mcopy_f_f(ml,a); vsip_mcopy_f_f(ml,a_cm); vsip_mcopy_f_f(ml,a_rm); vsip_mcopy_f_f(mr,b); vsip_mcopy_f_f(mr,b_cm); vsip_mcopy_f_f(mr,b_rm); vsip_mcopy_f_f(mr,r_bb); vsip_mcopy_f_f(a,aa); vsip_mcopy_f_f(b,bb); vsip_mprod_f(a,b,ans); vsip_mprod3_f(a,b,c); printf("vsip_mprod3_f(a,b,c)\n"); printf("a\n"); VU_mprintm_f("6.4",a); printf("b\n"); VU_mprintm_f("6.4",b); printf("c\n"); VU_mprintm_f("6.4",c); printf("right answer\n"); VU_mprintm_f("6.4",ans); vsip_msub_f(c,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_mprod3_f(aa,bb,cc); printf("vsip_mprod3_f(aa,bb,cc)\n"); printf("aa\n"); VU_mprintm_f("6.4",aa); printf("bb\n"); VU_mprintm_f("6.4",bb); printf("cc\n"); VU_mprintm_f("6.4",cc); printf("right answer\n"); VU_mprintm_f("6.4",ans); vsip_msub_f(cc,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_mprod3_f(aa,r_bb,i_cc); printf("vsip_mprod3_f(aa,bb,cc)\n"); printf("aa\n"); VU_mprintm_f("6.4",aa); printf("bb\n"); VU_mprintm_f("6.4",r_bb); printf("cc\n"); VU_mprintm_f("6.4",i_cc); printf("right answer\n"); VU_mprintm_f("6.4",ans); vsip_msub_f(i_cc,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check ccc\n"); vsip_mprod3_f(a_cm,b_cm,c_cm); vsip_msub_f(c_cm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check ccr\n"); vsip_mprod3_f(a_cm,b_cm,c_rm); vsip_msub_f(c_rm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check crc\n"); vsip_mprod3_f(a_cm,b_rm,c_cm); vsip_msub_f(c_cm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check crr\n"); vsip_mprod3_f(a_cm,b_rm,c_rm); vsip_msub_f(c_rm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check rcc\n"); vsip_mprod3_f(a_rm,b_cm,c_cm); vsip_msub_f(c_cm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check rcr\n"); vsip_mprod3_f(a_rm,b_cm,c_rm); vsip_msub_f(c_rm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check rrc\n"); vsip_mprod3_f(a_rm,b_rm,c_cm); vsip_msub_f(c_cm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check rrr\n"); vsip_mprod3_f(a_rm,b_rm,c_rm); vsip_msub_f(c_rm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_f(ml); vsip_malldestroy_f(mr); vsip_mdestroy_f(a); vsip_malldestroy_f(aa); vsip_mdestroy_f(b); vsip_malldestroy_f(bb); vsip_malldestroy_f(c); vsip_malldestroy_f(cc); vsip_malldestroy_f(ans); vsip_malldestroy_f(chk); vsip_mdestroy_f(i_cc); vsip_mdestroy_f(r_bb); vsip_cmalldestroy_f(c_cc); vsip_cmalldestroy_f(c_bb); vsip_malldestroy_f(a_cm); vsip_malldestroy_f(a_rm); vsip_malldestroy_f(b_cm); vsip_malldestroy_f(b_rm); vsip_malldestroy_f(c_cm); vsip_malldestroy_f(c_rm); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mcopy_i_f.c,v 2.1 2004/04/03 16:03:08 judd Exp $ */ #include"vsip.h" #include"vsip_mviewattributes_i.h" void (vsip_mcopy_i_f)( const vsip_mview_i* a, const vsip_mview_f* r) { vsip_length n_mj, /* major length */ n_mn; /* minor length */ vsip_stride ast_mj, ast_mn; vsip_scalar_i *ap = (a->block->array) + a->offset; vsip_scalar_i *ap0 = ap; vsip_index i=0,j=0; /* pick direction dependent on input */ if(a->row_stride < a->col_stride){ /* Row Major */ n_mj = a->row_length; n_mn = a->col_length; ast_mj = a->row_stride; ast_mn = a->col_stride; while(n_mn-- > 0){ vsip_length n = n_mj; while(n-- >0){ vsip_mput_f(r,i,j,(vsip_scalar_f) *ap); ap += ast_mj; j++; } ap0 += ast_mn; ap = ap0; i++; j=0; } } else { /* must be Col Major */ n_mn = a->row_length; n_mj = a->col_length; ast_mn = a->row_stride; ast_mj = a->col_stride; while(n_mn-- > 0){ vsip_length n = n_mj; while(n-- >0){ vsip_mput_f(r,i,j,(vsip_scalar_f) *ap); ap += ast_mj; i++; } ap0 += ast_mn; ap = ap0; i=0; j++; } } return; } <file_sep>/* Created RJudd March 18, 2012 */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"vsip.h" #include"vsip_mviewattributes_f.h" #include"vsip_vviewattributes_f.h" #include"vsip_cmviewattributes_f.h" #include"vsip_cvviewattributes_f.h" #include"vsip_scalars.h" #include"VI_mrowview_f.h" #include"VI_mcolview_f.h" #include"VI_cmrowview_f.h" #include"VI_cmcolview_f.h" static void vpolar_f(const vsip_cvview_f* a, const vsip_vview_f* r, const vsip_vview_f* t) { vsip_length n = r->length; vsip_stride cast = a->block->cstride, rrst = r->block->rstride, trst = t->block->rstride; vsip_scalar_f *apr = (vsip_scalar_f*) ((a->block->R->array) + cast * a->offset), *rp = (vsip_scalar_f*) ((r->block->array) + rrst * r->offset), *tp = (vsip_scalar_f*) ((t->block->array) + trst * t->offset); vsip_scalar_f *api = (vsip_scalar_f*) ((a->block->I->array) + cast * a->offset); vsip_scalar_f tmp; vsip_stride ast = (cast * a->stride), rst = rrst * r->stride, tst = trst * t->stride; while(n-- > 0){ tmp = (vsip_scalar_f)atan2(*api,*apr); *rp = (vsip_scalar_f)sqrt(*apr * *apr + *api * *api); *tp = tmp; apr += ast; api += ast; rp += rst; tp += tst; } } void vsip_mpolar_f(const vsip_cmview_f* a, const vsip_mview_f* r, const vsip_mview_f* t){ vsip_index i; vsip_vview_f rv; vsip_vview_f tv; vsip_cvview_f av; if(a->row_stride < a->col_stride){ for(i=0; i < a->col_length; i++){ VI_mrowview_f(r,i,&rv); VI_mrowview_f(t,i,&tv);VI_cmrowview_f(a,i,&av); vpolar_f(&av,&rv,&tv); } } else { for(i=0; i < a->col_length; i++){ VI_mcolview_f(r,i,&rv); VI_mcolview_f(t,i,&tv);VI_cmcolview_f(a,i,&av); vpolar_f(&av,&rv,&tv); } } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mcmaxmgsq_f.h,v 2.0 2003/02/22 15:23:24 judd Exp $ */ #include"VU_mprintm_f.include" #include"VU_cmprintm_f.include" static void mcmaxmgsq_f(void){ printf("\n******\nTEST mcmaxmgsq_f\n"); { vsip_scalar_f data1[]= {1,.1, 2,.2, 3,.3, 4,-.1, 5,-.3, 6,-.4, 7,.8, 8,.9, 9,-1}; vsip_scalar_f data2_r[]= {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9}; vsip_scalar_f data2_i[]= {-1.1, 2.2, -3.3, 4.4, -5.5, 6.6, -7.7, 8.8, -9.9}; vsip_scalar_f ans[] = { 2.42, 38.72, 118.58, 16.01, 60.50, 154.88, 49.64, 87.12, 196.02}; vsip_cmview_f *m1 = vsip_cmbind_f( vsip_cblockbind_f(data1,NDPTR_f,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_cmview_f *m2 = vsip_cmbind_f( vsip_cblockbind_f(data2_r,data2_i,9,VSIP_MEM_NONE),0,1,3,3,3); vsip_mview_f *ma = vsip_mbind_f( vsip_blockbind_f(ans,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_mview_f *m3 = vsip_mcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *chk = vsip_mcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cblockadmit_f(vsip_cmgetblock_f(m1),VSIP_TRUE); vsip_cblockadmit_f(vsip_cmgetblock_f(m2),VSIP_TRUE); vsip_blockadmit_f(vsip_mgetblock_f(ma),VSIP_TRUE); printf("call vsip_mcmaxmgsq_f(a,b,c)\n"); printf("a =\n");VU_cmprintm_f("8.6",m1); printf("b =\n");VU_cmprintm_f("8.6",m2); vsip_mcmaxmgsq_f(m1,m2,m3); printf("c =\n");VU_mprintm_f("8.6",m3); printf("\nright answer =\n"); VU_mprintm_f("6.4",ma); vsip_msub_f(ma,m3,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,0,2 * .0001,0,1,chk); if(fabs(vsip_msumval_f(chk)) > .5) printf("error\n"); else printf("correct\n"); { vsip_cmview_f *a = vsip_cmcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *c= vsip_mrealview_f(a); vsip_cmcopy_f_f(m1,a); printf(" inplace <c> real view of <a> \n"); vsip_mcmaxmgsq_f(a,m2,c); vsip_msub_f(ma,c,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,0,2 * .0001,0,1,chk); if(fabs(vsip_msumval_f(chk)) > .5) printf("error\n"); else printf("correct\n"); vsip_mdestroy_f(c); vsip_cmalldestroy_f(a); } { vsip_cmview_f *b = vsip_cmcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *c= vsip_mimagview_f(b); vsip_cmcopy_f_f(m2,b); printf(" inplace <c> imag view of <b> \n"); vsip_mcmaxmgsq_f(m1,b,c); vsip_msub_f(ma,c,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,0,2 * .0001,0,1,chk); if(fabs(vsip_msumval_f(chk)) > .5) printf("error\n"); else printf("correct\n"); vsip_mdestroy_f(c); vsip_cmalldestroy_f(b); } vsip_cmalldestroy_f(m1); vsip_cmalldestroy_f(m2); vsip_malldestroy_f(m3); vsip_malldestroy_f(ma); vsip_malldestroy_f(chk); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mindexbool.h,v 2.0 2003/02/22 15:23:24 judd Exp $ */ #include"VU_mprintm_f.include" #include"VU_vprintm_mi.include" void mindexbool(void){ printf("\n*******\nTEST mindexbool\n"); { vsip_scalar_bl crct = VSIP_TRUE; vsip_scalar_bl data1[] = {0, 0, 0, 0, 0, 1, 0, 0, 0, 0}; vsip_scalar_vi ans_data1[] = {1,0}; vsip_scalar_bl data2[] = {0, 1, 0, 1, 0, 1, 1, 1, 1, 0}; vsip_scalar_vi ans_data2[] = {0,1 , 0,3 , 1,0 , 1,1 , 1,2 , 1,3}; vsip_scalar_vi ans_data2_1[] = {1,0 , 0,1 , 1,1 , 1,2 , 0,3 , 1,3}; vsip_mview_f *pm = vsip_mcreate_f(2,5,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_bl *m2_0 = vsip_mcreate_bl(4,40,VSIP_COL,VSIP_MEM_NONE); vsip_mview_bl *m2_1 = vsip_msubview_bl(m2_0,1,1,2,5); vsip_vview_mi *index = vsip_vcreate_mi(10,VSIP_MEM_NONE); vsip_mview_bl *m1 = vsip_mbind_bl( vsip_blockbind_bl(data1,10,VSIP_MEM_NONE),0,5,2,1,5); vsip_mview_bl *m2 = vsip_mbind_bl( vsip_blockbind_bl(data2,10,VSIP_MEM_NONE),0,5,2,1,5); vsip_vview_mi *ans1 = vsip_vbind_mi( vsip_blockbind_mi(ans_data1,1,VSIP_MEM_NONE),0,1,1); vsip_vview_mi *ans2 = vsip_vbind_mi( vsip_blockbind_mi(ans_data2,1,VSIP_MEM_NONE),0,1,6); vsip_vview_mi *ans2_1 = vsip_vbind_mi( vsip_blockbind_mi(ans_data2_1,1,VSIP_MEM_NONE),0,1,6); vsip_length check; vsip_scalar_mi c1,c2; int i; vsip_blockadmit_bl(vsip_mgetblock_bl(m1),VSIP_TRUE); vsip_blockadmit_bl(vsip_mgetblock_bl(m2),VSIP_TRUE); vsip_blockadmit_mi(vsip_vgetblock_mi(ans1),VSIP_TRUE); vsip_blockadmit_mi(vsip_vgetblock_mi(ans2),VSIP_TRUE); vsip_blockadmit_mi(vsip_vgetblock_mi(ans2_1),VSIP_TRUE); vsip_mcopy_bl_bl(m2,m2_1); printf("matrix m1\n"); vsip_mcopy_bl_f(m1,pm); VU_mprintm_f("1",pm); printf("vsip_mindexbool(m1,index) returns"); printf(" %ld\n",(check = vsip_mindexbool(m1,index))); if(check != 1){ printf("error: return value incorrect\n"); crct = VSIP_FALSE; } if(check != vsip_vgetlength_mi(index)) { printf("error: return value not equal returned index length\n"); crct = VSIP_FALSE; } printf("index equals \n"); VU_vprintm_mi("1",index); printf("right answer \n"); VU_vprintm_mi("1",ans1); c1 = vsip_vget_mi(index,VSIP_MEM_NONE); c2 = vsip_vget_mi(ans1,VSIP_MEM_NONE); if((vsip_rowindex(c1)-vsip_rowindex(c2))){ printf("row index error\n"); crct = VSIP_FALSE; } if((vsip_colindex(c1)-vsip_colindex(c2))){ printf("column index error\n"); crct = VSIP_FALSE; } vsip_vputlength_mi(index,10); printf("matrix m2 row major\n"); vsip_mcopy_bl_f(m2,pm); VU_mprintm_f("1",pm); printf("vsip_mindexbool(m2,index) returns"); printf(" %ld\n",(check = vsip_mindexbool(m2,index))); if(check != 6){ printf("error: return value incorrect\n"); crct = VSIP_FALSE; } if(check != vsip_vgetlength_mi(index)){ printf("error: return value not equal returned index length\n"); crct = VSIP_FALSE; } printf("index equals \n"); VU_vprintm_mi("1",index); printf("right answer \n"); VU_vprintm_mi("1",ans2); { int ckr=0, ckc=0; for(i=0; i<6; i++){ c1 = vsip_vget_mi(index,i); c2 = vsip_vget_mi(ans2,i); if((vsip_rowindex(c1)-vsip_rowindex(c2))) ckr++; if((vsip_colindex(c1)-vsip_colindex(c2))) ckc++; } if(ckr != 0){ printf("row index error\n"); crct = VSIP_FALSE; } if(ckc != 0){ printf("column index error\n"); crct = VSIP_FALSE; } } printf("matrix m2 column major\n"); vsip_mcopy_bl_f(m2_1,pm); VU_mprintm_f("1",pm); printf("vsip_mindexbool(m2,index) returns"); printf(" %ld\n",(check = vsip_mindexbool(m2_1,index))); if(check != 6){ printf("error: return value incorrect\n"); crct = VSIP_FALSE; } if(check != vsip_vgetlength_mi(index)){ printf("error: return value not equal returned index length\n"); crct = VSIP_FALSE; } printf("index equals \n"); VU_vprintm_mi("1",index); printf("right answer \n"); VU_vprintm_mi("1",ans2_1); { int ckr=0, ckc=0; for(i=0; i<6; i++){ c1 = vsip_vget_mi(index,i); c2 = vsip_vget_mi(ans2_1,i); if((vsip_rowindex(c1)-vsip_rowindex(c2))) ckr++; if((vsip_colindex(c1)-vsip_colindex(c2))) ckc++; } if(ckr != 0){ printf("row index error\n"); crct = VSIP_FALSE; } if(ckc != 0){ printf("column index error\n"); crct = VSIP_FALSE; } } if(crct) printf("correct\n"); vsip_malldestroy_bl(m1); vsip_malldestroy_bl(m2); vsip_valldestroy_mi(ans1); vsip_valldestroy_mi(ans2); vsip_valldestroy_mi(index); vsip_malldestroy_f(pm); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mfill_d.h,v 2.0 2003/02/22 15:23:24 judd Exp $ */ #include"VU_mprintm_d.include" static void mfill_d(void){ printf("\n******\nTEST mfill_d\n"); { vsip_scalar_d alpha = 1.2345; vsip_scalar_d ans[] = {1.2345,1.2345,1.2345,1.2345,1.2345,1.2345,1.2345,1.2345,1.2345}; vsip_mview_d *ma = vsip_mbind_d( vsip_blockbind_d(ans,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_mview_d *chk = vsip_mcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *B = vsip_mcreate_d(9,9,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *b = vsip_msubview_d(B,2,2,3,3); vsip_blockadmit_d(vsip_mgetblock_d(ma),VSIP_TRUE); vsip_mputrowstride_d(b,4); printf("call vsip_mfill_d(alpha,b)\n"); printf("alpha = %f\n",alpha); vsip_mfill_d(alpha,b); printf("b =\n");VU_mprintm_d("8.6",b); printf("\nright answer =\n"); VU_mprintm_d("6.4",ma); vsip_msub_d(ma,b,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,0,.0001,0,1,chk); if(fabs(vsip_msumval_d(chk)) > .5) printf("error\n"); else printf("correct\n"); vsip_mdestroy_d(b); vsip_malldestroy_d(B); vsip_malldestroy_d(ma); vsip_malldestroy_d(chk); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmexpoavg_d.h,v 2.0 2003/02/22 15:23:20 judd Exp $ */ #include"VU_cmprintm_d.include" static void cmexpoavg_d(void){ printf("\n******\nTEST cmexpoavg_d\n"); { vsip_scalar_d alpha = (vsip_scalar_d)(1.0/3.0); vsip_scalar_d data1[]= {1,.1, 2,.2, 3,.3, 4,-.1, 5,-.3, 6,-.4, 7,.8, 8,.9, 9,-1}; vsip_scalar_d data2[]= {2,.1, 3,.2, 4,.3, 6,-.1, 8,-.3, 6,-.6, 7,.7, 8,.5, 1,-1.3}; vsip_scalar_d data3[]= {0,.2, 3,.5, 3,.1, 2,-.1, 5,-.3, 6,-.4, 7,.8, 8,.9, 9,-1.5}; vsip_cmview_d *ans = vsip_cmcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *m1 = vsip_cmbind_d( vsip_cblockbind_d(data1,NDPTR_d,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_cmview_d *m2 = vsip_cmbind_d( vsip_cblockbind_d(data2,NDPTR_d,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_cmview_d *m3 = vsip_cmbind_d( vsip_cblockbind_d(data3,NDPTR_d,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_cmview_d *c = vsip_cmcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *chk = vsip_cmcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *chk_r = vsip_mrealview_d(chk); vsip_cblockadmit_d(vsip_cmgetblock_d(m1),VSIP_TRUE); vsip_cblockadmit_d(vsip_cmgetblock_d(m2),VSIP_TRUE); vsip_cblockadmit_d(vsip_cmgetblock_d(m3),VSIP_TRUE); printf("call vsip_cmexpoavg_d(alpha,b,c) three times\n"); printf("alpha = 1\n"); printf("first call b =\n");VU_cmprintm_d("8.6",m1); printf("alpha = 1/2\n"); printf("second call b =\n");VU_cmprintm_d("8.6",m2); printf("alpha = 1/3\n"); printf("third call b =\n");VU_cmprintm_d("8.6",m3); printf("c initialized to zero\n"); { vsip_mview_d *cr = vsip_mrealview_d(c); vsip_mview_d *ci = vsip_mimagview_d(c); vsip_mfill_d(0,cr); vsip_mfill_d(0,ci); vsip_mdestroy_d(cr); vsip_mdestroy_d(ci); } vsip_cmexpoavg_d(1.0,m1,c); vsip_cmexpoavg_d(.5,m2,c); vsip_cmexpoavg_d(1.0/3.0,m3,c); printf("after third call c =\n");VU_cmprintm_d("8.6",c); vsip_cmadd_d(m1,m2,ans); vsip_cmadd_d(m3,ans,ans); vsip_rscmmul_d(alpha,ans,ans); printf("\nright answer =\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(ans,c,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,0,2 * .0001,0,1,chk_r); if(fabs(vsip_msumval_d(chk_r)) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(m1); vsip_cmalldestroy_d(m2); vsip_cmalldestroy_d(m3); vsip_cmalldestroy_d(ans); vsip_cmalldestroy_d(c); vsip_mdestroy_d(chk_r); vsip_cmalldestroy_d(chk); } return; } <file_sep>#!/Library/Frameworks/Python.framework/Versions/2.7/bin/python # Line above should be changed to be compliant with the desired python from Tkinter import * from tkFileDialog import askdirectory, askopenfilename from subprocess import call, Popen, PIPE from os.path import split, join from os import getcwd master = Tk() mydir = getcwd() def dirFind(aParent,anEntry): aDir=askdirectory(parent=aParent,initialdir=anEntry.get(),title='Please select a directory') anEntry.delete(0,END) anEntry.insert(0,aDir) def fileFind(aParent,dirEntry,anEntry): aFile=split(askopenfilename(parent=aParent,initialdir=dirEntry.get(),title='Please select a file')) if len(aFile[1]): dirEntry.delete(0,END) dirEntry.insert(0,aFile[0]) anEntry.delete(0,END) anEntry.insert(0,aFile[1]) def pathFind(aParent,anEntry): """ pathFind(aParent,anEntry) aParent is a Tkinter frame anEntry resides in anEntry is a Tkinter Entry object Th function opens a finder object. The returned value a string containing the complete path to the selected file. The results are placed in anEntry. The initial contents of anEntry are used as to get the starting directory for the search. """ initPath=split(anEntry.get())[0] if len(initPath): aPath=askopenfilename(parent=aParent,initialdir=initPath,title='Please select a file') if len(aPath): anEntry.delete(0,END) anEntry.insert(0,aPath) else: aPath=aksopenfilename(parent=aParent,title='Please select a file') if len(aPath): anEntry.delete(0,END) anEntry.insert(0,aPath) def testOpen(dirEntry,anEntry): call(['open',join(dirEntry.get(),anEntry.get())]) # define frames for each section here. frame_aTest=Frame(master) frame_aTestDir=Frame(master) frame_aLibrary=Frame(master) frame_aIncludeDir=Frame(master) frame_aButtonPlace=Frame(master) frame_Text=Frame(master) #labels for each directory/file Entry point lbl_aTest = Label(frame_aTest, text="Test Name", width=15,anchor=E) lbl_aTestDir = Label(frame_aTestDir, text="Test Directory",width=15,anchor=E) lbl_aIncludeDir= Label(frame_aIncludeDir, text="Directory for vsip.h", width=15, anchor=E) lbl_aLibrary = Label(frame_aLibrary, text="VSIPL Library",width=15, anchor=E) #Define entry points for directory/files needed to make test aTest = Entry(frame_aTest, width=50) aTestDir = Entry(frame_aTestDir, width=50) aIncludeDir=Entry(frame_aIncludeDir, width=50) aLibrary = Entry(frame_aLibrary, width=50) #Define buttons to call up finder for each entry point aTestButton=Button(frame_aTest, text="find", width=5, command=lambda: fileFind(frame_aTest,aTestDir,aTest)) aTestDirButton=Button(frame_aTestDir,text="find", width=5, command=lambda: dirFind(frame_aTestDir,aTestDir)) aIncludeDirButton=Button(frame_aIncludeDir,text="find", width=5, command=lambda: dirFind(frame_aIncludeDir,aIncludeDir)) aLibraryButton=Button(frame_aLibrary, text="find", width=5, command=lambda: pathFind(frame_aLibrary,aLibrary)) #define text area to display output myScroll=Scrollbar(frame_Text) myText=Text(frame_Text,height=20,width=80,yscrollcommand=myScroll.set) #callback for run test def runTest(): call(['rm','atest']) mytestfile=join(aTestDir.get(),aTest.get()) aFunc=aTest.get().split(".")[0]+"();" mytest="atest.c" aFile=open(mytest,"w") aFile.write("#define NDPTR_f ((vsip_scalar_f*)NULL)\n#define NDPTR_d ((vsip_scalar_d*)NULL)\n") aFile.write("#define NDPTR_i ((vsip_scalar_i*)NULL)\n#define NDPTR_si ((vsip_scalar_si*)NULL)\n") aFile.write("#include<vsip.h>\n#include\""+mytestfile+"\"\n") aFile.write("int main(){\n\tvsip_init((void*)0);\n") aFile.write("\t"+aFunc); aFile.write("\n\tvsip_finalize((void*)0); \n\treturn 0;\n} ") aFile.close() a_gcc_string='gcc -o atest atest.c ' + aLibrary.get() + ' -I'+aIncludeDir.get() + ' -lm' a_gcc_call=a_gcc_string.split() print(a_gcc_string) print(a_gcc_call) aProcess = Popen(a_gcc_call,stdout=PIPE,stderr=PIPE) resultText=aProcess.communicate() if len(resultText[0]): print(resultText[0]) if len(resultText[1]): print("compile error") print(resultText[1]) else: testResult=Popen(['./atest'],stdout=PIPE) resultText=testResult.communicate() if resultText[1]: print(resultText[1]) #print(resultText[0]) myText.delete(1.0,END) myText.insert(END,resultText[0]) # define execution buttons and place in button frame testCompileButton = Button(frame_aButtonPlace, text="Run Test", width=14, command=runTest) testCompileButton.grid(row=0,column=1) testOpenButton=Button(frame_aButtonPlace,text="Open Test", width=14, command=lambda: testOpen(aTestDir,aTest)) testOpenButton.grid(row=0,column=0) #place objects in there frames lbl_aTest.grid(row=0,column=0) aTest.grid(row=0,column=1) aTestButton.grid(row=0,column=2) lbl_aTestDir.grid(row=1,column=0) aTestDir.grid(row=1,column=1) aTestDirButton.grid(row=1,column=2) lbl_aLibrary.grid(row=2,column=0) aLibrary.grid(row=2,column=1) aLibraryButton.grid(row=2,column=2) lbl_aIncludeDir.grid(row=3,column=0) aIncludeDir.grid(row=3,column=1) aIncludeDirButton.grid(row=3,column=2) myText.grid(row=0,column=0) myScroll.grid(row=0,column=1) # Place frames in master and initialize frame_aTest.grid(row=0,column=0) frame_aTestDir.grid(row=1,column=0) aTestDir.insert(0,mydir) frame_aIncludeDir.grid(row=2,column=0) aIncludeDir.insert(0,mydir) frame_aLibrary.grid(row=3,column=0) aLibrary.insert(0,mydir) frame_aButtonPlace.grid(row=4,column=0) frame_Text.grid(row=5,column=0) master.title=('JVSIP Test GUI') #start everything running master.mainloop()<file_sep>/* Created RJudd */ /* VSIPL Consultant */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mvprod3_d.c,v 2.2 2006/04/17 19:38:02 judd Exp $ */ #include"vsip.h" #include"vsip_vviewattributes_d.h" #include"vsip_mviewattributes_d.h" void (vsip_mvprod3_d)( const vsip_mview_d* A, const vsip_vview_d* b, const vsip_vview_d* r) { vsip_scalar_d *bp0 = b->block->array + b->offset * b->block->rstride, *rp0 = r->block->array + r->offset * r->block->rstride, *Ap00 = A->block->array + A->offset * A->block->rstride; vsip_stride rst = r->stride * r->block->rstride, ARst = A->row_stride * A->block->rstride, ACst = A->col_stride * A->block->rstride, bst = b->stride * b->block->rstride; vsip_scalar_d b0,b1,b2; vsip_scalar_d a00, a01, a02; vsip_scalar_d a10, a11, a12; vsip_scalar_d a20, a21, a22; vsip_scalar_d *Ap10 = Ap00 + ACst, *bp1 = bp0 + bst, *rp1 = rp0 + rst; vsip_scalar_d *Ap20 = Ap10 + ACst, *bp2 = bp1 + bst, *rp2 = rp1 + rst; b0 = *bp0; b1 = *bp1; b2 = *bp2; a00 = *Ap00; a01 = *(Ap00+ARst); a02 = *(Ap00 + 2 * ARst); a10 = *Ap10; a11 = *(Ap10+ARst); a12 = *(Ap10 + 2 * ARst); a20 = *Ap20; a21 = *(Ap20+ARst); a22 = *(Ap20 + 2 * ARst); *rp0 = b0 * a00 + b1 * a01 + b2 * a02; *rp1 = b0 * a10 + b1 * a11 + b2 * a12; *rp2 = b0 * a20 + b1 * a21 + b2 * a22; return; } <file_sep>import pyJvsip as pv from exUtils import * import numpy as np import matplotlib.pyplot as plt # define parameters D=1.5 # Sensor Spacing Meters Fs=1000.0 # Sample Frequency (Hz) F0=450.0 # Target Frequency F1=300.0 # Target Frequency F2=150.0 # Target Frequency F3=50.0 # Target Frequency Theta_o=40 # Target Direction Ns=512 # length of sampled time series (samples) Nn=1024 # length of (simulated) noise series Mp=128 # number of sensors in linear array c=1500.0 # Propagation Speed (Meters/Second) # Calculate input data alpha = (D * Fs) / c #Array Constant data = noiseGen('mview_d',alpha,Mp,Nn,Ns) targets=[(F0,Theta_o,1.5),(F1,Theta_o,2.0),(F2,Theta_o,2.0),(F3,Theta_o,3.0)] narrowBandGen(data,alpha,targets,Fs) # beamform data and output in a form sutiable for display ccfftmip = pv.FFT('ccfftmip_d',(Mp,int(Ns/2) + 1,pv.VSIP_FFT_FWD,1,pv.VSIP_COL,0,0)) windowt=pv.create('vview_d',Ns).hanning windowp=pv.create('vview_d',Mp).hanning pv.vmmul(windowt.ROW,data,data) #window to reduce sidelobes pv.vmmul(windowp.COL,data,data) gram_data=data.rcfft ccfftmip.dft(gram_data) gram = scale(gram_data) # save data view_store(gram,'gram_output') fig = plt.figure() ax = fig.add_subplot(111) plt.imshow(gram.list,origin='lower') ax.set_yticks([0,31,63,95,127]) ax.set_xticks([0,51,103,154,206,256]) ax.set_yticklabels([r'$-\kappa$','$-\kappa /2$','$0$','$\kappa /2$','$\kappa$']) ax.set_xticklabels([' 0 ','100','200','300','400','500']) ax.set_title(r'$\vec{\kappa}\omega$ plot') ax.set_xlabel('Frequency (Hz)') ax.set_ylabel(r'$\kappa \cdot \cos(\theta)$') plt.show() <file_sep>def strass(A, B, C): assert 'View' in repr(A) and 'View' in repr(B) and 'View' in repr(C),\ 'Strass works with pyJvsip views' assert 'mview' in A.type,'strass only works with matrix views' assert A.type==B.type and A.type==C.type,'Matrix types must be the same' n=A.rowlength if n % 2 == 1 or n < 129: pjv.prod(A,B,C) else: A00 = A.cloneview; Aij = A.cloneview Ai0 = A.cloneview; A0j = A.cloneview B00 = B.cloneview; Bij = B.cloneview Bi0 = B.cloneview; B0j = B.cloneview C00 = C.cloneview; Cij = C.cloneview Ci0 = C.cloneview; C0j = C.cloneview m = n/2; i = m; j = i P1 = pjv.create(A.type,m,m) P2 = pjv.create(A.type,m,m) P3 = pjv.create(A.type,m,m) P4 = pjv.create(A.type,m,m) P5 = pjv.create(A.type,m,m) P6 = pjv.create(A.type,m,m) P7 = pjv.create(A.type,m,m) mgetsub(A,A00,0,0,1,1,m,m);mgetsub(A,A0j,0,j,1,1,m,m) mgetsub(A,Ai0,i,0,1,1,m,m);mgetsub(A,Aij,i,j,1,1,m,m) mgetsub(B,B00,0,0,1,1,m,m);mgetsub(B,B0j,0,j,1,1,m,m) mgetsub(B,Bi0,i,0,1,1,m,m);mgetsub(B,Bij,i,j,1,1,m,m) mgetsub(C,C00,0,0,1,1,m,m);mgetsub(C,C0j,0,j,1,1,m,m) mgetsub(C,Ci0,i,0,1,1,m,m);mgetsub(C,Cij,i,j,1,1,m,m) pjv.add(A00,Aij,C00); pjv.add(B00,Bij,Cij); strass(C00,Cij,P1) pjv.add(Ai0,Aij,C00);strass(C00,B00,P2) pjv.sub(B0j,Bij,C00); strass(A00,C00,P3) pjv.sub(Bi0,Bij,C00); strass(Aij,C00,P4) pjv.add(A00,A0j,C00); strass(C00,Bij,P5) pjv.sub(Ai0,A00,C00); pjv.add(B00,B0j,Cij); strass(C00,Cij,P6) pjv.sub(A0j,Aij,C00); pjv.add(Bi0,Bij,Cij); strass(C00,Cij,P7) pjv.add(P1,P4,C00);pjv.sub(C00,P5,C00); pjv.add(C00,P7,C00) pjv.add(P3,P5,C0j) pjv.add(P2,P4,Ci0) pjv.add(P1,P3,Cij); pjv.sub(Cij,P2,Cij); pjv.add(Cij,P6,Cij) return C <file_sep>/* Created by RJudd June 10, 2002 */ /* SPAWARSYSCEN code 2857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_ccfftop_f_fftw.h,v 2.0 2003/02/22 15:18:30 judd Exp $ */ /* use fftw for calculation */ #include"vsip.h" #include"vsip_fftattributes_f.h" #include"vsip_cvviewattributes_f.h" #if !defined(VSIP_ASSUME_COMPLEX_IS_INTERLEAVED) #define __VSIPL_CVCOPY_TO_FFTW_F #define __VSIPL_CVCOPY_FROM_FFTW_F #endif #include"VI_fftw_obj.h" /*========================================================*/ void vsip_ccfftop_f(const vsip_fft_f *Offt, const vsip_cvview_f *x, const vsip_cvview_f *y) { vsip_fft_f Nfft = *Offt; vsip_fft_f *fft = &Nfft; vsipl_fftw_obj *obj = (vsipl_fftw_obj*)fft->ext_fft_obj; #if defined(VSIP_ASSUME_COMPLEX_IS_INTERLEAVED) int howmany = 1; int istride = (int)x->stride; int ostride = (int)y->stride; int idist = 1, odist = 1; fftw_complex *in = (fftw_complex*)(x->block->R->array + x->offset * x->block->R->rstride); fftw_complex *out = (fftw_complex*)(y->block->R->array + y->offset * y->block->R->rstride); fftw(obj->p,howmany,in,istride,idist,out,ostride,odist); #else vsipl_cvcopy_to_fftw_f(x,obj); fftw_one(obj->p,obj->in,obj->out); vsipl_cvcopy_from_fftw_f(obj,y); #endif if (fft->scale != 1) vsip_rscvmul_f(fft->scale,y,y); return; } <file_sep>/// Scalar is a structure to allow generalized return of scalars from a view //: To support the SwiftAccelerate framework we need a Scalar type to handle the various //: atomic data types. import Foundation import Accelerate func scalarString(_ format : String, value : Scalar) -> String{ var retval = "" switch value.type{ case .f: let fmt = "%" + format + "f" retval = String(format: fmt, value.realf) case .d: let fmt = "%" + format + "f" retval = String(format: fmt, value.reald) case .cf: let fmt1 = "%" + format + "f" let fmt2 = "%+" + format + "f" let r = String(format: fmt1, value.realf) let i = String(format: fmt2, value.imagf) retval = r + i + "i" case .cd: let fmt1 = "%" + format + "f" let fmt2 = "%+" + format + "f" let r = String(format: fmt1, value.reald) let i = String(format: fmt2, value.imagd) retval = r + i + "i" case .i: let fmt = "%d" retval = String(format: fmt, value.int) case .ui: let fmt = "%d" retval = String(format: fmt, value.int) } return retval } func formatFmt(_ fmt: String) -> String{ var retval = "" func charCheck(_ char: Character) -> Bool { let validChars = "0123456789." for item in validChars{ if char == item { return true } } return false } for char in fmt{ if charCheck(char){ retval.append(char) } } return retval } public struct Scalar { var value: (BlockTypes?, NSNumber?, NSNumber?) public init(_ type: BlockTypes,_ valueOne: NSNumber?,_ valueTwo: NSNumber?){ value.0 = type value.1 = valueOne value.2 = valueTwo } public init(_ value: Double){ self.value.0 = .d self.value.1 = NSNumber(value: value) self.value.2 = nil } public init(_ value: Float){ self.value.0 = .f self.value.1 = NSNumber(value: value) self.value.2 = nil } public init(_ value: Int32){ self.value.0 = .i self.value.1 = NSNumber(value: value) self.value.2 = nil } public init(_ value: UInt32){ self.value.0 = .i self.value.1 = NSNumber(value: value) self.value.2 = nil } public init(_ value: DSPDoubleComplex){ self.value.0 = .cd self.value.1 = NSNumber(value: value.real) self.value.2 = NSNumber(value: value.imag) } public init(_ value: DSPComplex){ self.value.0 = .cf self.value.1 = NSNumber(value: value.real) self.value.2 = NSNumber(value: value.imag) } public var type: BlockTypes { return self.value.0! } public var realf: Float{ return Float((value.1?.floatValue)!) } public var reald: Double{ return Double((value.1?.doubleValue)!) } public var imagf: Float{ if let i = value.2 { return Float(i) } else { return Float(0.0) } } public var imagd: Double{ if let i = value.2 { return Double(i) } else { return Double(0.0) } } public var int: Int32{ return Int32((value.1?.intValue)!) } public var rowIndex: UInt32{ return UInt32((value.1?.intValue)!) } public var colIndex: UInt32{ return UInt32((value.2?.intValue)!) } public var index: UInt32{ return UInt32((value.1?.intValue)!) } public var length: UInt32{ return UInt32((value.1?.intValue)!) } public var offset: UInt32{ return self.length } public var stride: Int32{ return self.int } public var cmplxf: DSPComplex { return DSPComplex(real: self.realf, imag: self.imagf) } public var cmplxd: DSPDoubleComplex{ return DSPDoubleComplex(real: self.reald, imag: self.imagd) } public static func + (left: Scalar, right: Scalar) -> Scalar { switch (left.type, right.type) { case (.i, .i): return Scalar( left.int + right.int) case (.i, .f): return Scalar( left.realf + right.realf) case (.f, .i): return Scalar( left.realf + right.realf) case (.i, .d): return Scalar( left.reald + right.reald) case (.d, .i): return Scalar( left.reald + right.reald) case (.f, .f): return Scalar( left.realf + right.realf) case (.f, .d): return Scalar( left.realf + right.realf) case (.d, .f): return Scalar( left.realf + right.realf) case (.d, .d): return Scalar( left.reald + right.reald) case (.cf, .f): return Scalar(DSPComplex(real: left.realf + right.realf, imag: left.imagf)) case (.cf, .d): return Scalar(DSPComplex(real: left.realf + right.realf, imag: left.imagf)) case (.cd, .f): return Scalar(DSPComplex(real: left.realf + right.realf, imag: left.imagf)) case (.cd, .d): return Scalar(DSPDoubleComplex(real: left.reald + right.reald, imag: left.imagd)) case (.f, .cf): return Scalar(DSPComplex(real: left.realf + right.realf, imag: right.imagf)) case (.d, .cf): return Scalar(DSPComplex(real: left.realf + right.realf, imag: right.imagf)) case (.f, .cd): return Scalar(DSPComplex(real: left.realf + right.realf, imag: right.imagf)) case (.d, .cd): return Scalar(DSPDoubleComplex(real: left.reald + right.reald, imag: right.imagd)) case(.cf, .cf): return Scalar(DSPComplex(real: left.realf + right.realf, imag: left.imagf + right.imagf)) case(.cd, .cd): return Scalar(DSPDoubleComplex(real: left.reald + right.reald, imag: left.imagd + right.imagd)) case (.i, .cd): return Scalar(DSPDoubleComplex(real: left.reald + right.reald, imag: right.imagd)) case (.i, .cf): return Scalar(DSPComplex(real: left.realf + right.realf, imag: right.imagf)) case (.cf, .i): return Scalar(DSPComplex(real: left.realf + right.realf, imag: left.imagf)) case (.cd, .i): return Scalar(DSPDoubleComplex(real: left.reald + right.reald, imag: left.imagd)) case (.ui, .ui): return Scalar(UInt32(left.int + right.int)) case (.i, .ui): return Scalar(Int32(left.int + right.int)) case (.ui, .i): return Scalar(Int32(left.int + right.int)) case (.ui, .f): return Scalar(left.realf + right.realf) case (.f, .ui): return Scalar(left.realf + right.realf) case (.ui, .d): return Scalar(left.reald + right.reald) case (.d, .ui): return Scalar(left.reald + right.reald) default: preconditionFailure("Vsip Scalar types (\(left.type), \(right.type)) not supported for +") } } public static func * (left: Scalar, right: Scalar) -> Scalar { switch (left.type, right.type) { case (.f, .d): return Scalar( left.realf * right.realf) case (.d, .f): return Scalar( left.realf * right.realf) case (.d, .i): return Scalar( left.reald * right.reald) case (.i, .d): return Scalar( left.reald * right.reald) case (.f, .i): return Scalar( left.realf * right.realf) case (.i, .f): return Scalar( left.realf * right.realf) case (.f, .f): return Scalar( left.realf * right.realf) case (.d, .d): return Scalar( left.reald * right.reald) case (.cf, .f): let r = right.realf * left.realf let i = right.realf * left.imagf return Scalar(DSPComplex(real: r, imag: i)) case (.cf, .i): let r = right.realf * left.realf let i = right.realf * left.imagf return Scalar(DSPComplex(real: r, imag: i)) case (.cd, .i): let r = right.reald * left.reald let i = right.reald * left.imagd return Scalar(DSPDoubleComplex(real: r, imag: i)) case (.cd, .f): let r = right.realf * left.realf let i = right.realf * left.imagf return Scalar(DSPComplex(real: r, imag: i)) case (.cd, .d): let r = right.reald * left.reald let i = right.reald * left.imagd return Scalar(DSPDoubleComplex(real: r, imag: i)) case (.f, .cf): let r = left.realf * right.realf let i = left.realf * right.imagf return Scalar(DSPComplex(real: r, imag: i)) case (.f, .cd): let r = left.realf * right.realf let i = left.realf * right.imagf return Scalar(DSPComplex(real: r, imag: i)) case (.i, .cf): let r = left.realf * right.realf let i = left.realf * right.imagf return Scalar(DSPComplex(real: r, imag: i)) case (.i, .cd): let r = left.reald * right.reald let i = left.reald * right.imagd return Scalar(DSPDoubleComplex(real: r, imag: i)) case (.d, .cd): let r = left.reald * right.reald let i = left.reald * right.imagd return Scalar(DSPDoubleComplex(real: r, imag: i)) case(.cf, .cf): return Scalar(DSPComplex(real: left.realf * right.realf - left.imagf * right.imagf, imag: left.realf * left.imagf + left.imagf * right.imagf)) case(.cd, .cd): return Scalar(DSPDoubleComplex(real: left.reald * right.reald - left.imagd * right.imagd, imag: left.reald * left.imagd + left.imagd * right.imagd)) case (.ui, .ui): return Scalar(UInt32(left.int * right.int)) case (.i, .ui): return Scalar(Int32(left.int * right.int)) case (.ui, .i): return Scalar(Int32(left.int * right.int)) case (.ui, .f): return Scalar(left.realf * right.realf) case (.f, .ui): return Scalar(left.realf * right.realf) case (.ui, .d): return Scalar(left.reald * right.reald) case (.d, .ui): return Scalar(left.reald * right.reald) default: preconditionFailure("Vsip Scalar types (\(left.type), \(right.type)) not supported for *") } } public static func - (left: Scalar, right: Scalar) -> Scalar { switch (left.type, right.type) { case (.f, .f): return Scalar( left.realf - right.realf) case (.d, .f): return Scalar( left.realf - right.realf) case (.f, .d): return Scalar( left.realf - right.realf) case (.d, .d): return Scalar( left.reald - right.reald) case (.cf, .f): return Scalar(DSPComplex(real: left.realf - right.realf, imag: left.imagf)) case (.cd, .d): return Scalar(DSPDoubleComplex(real: left.reald - right.reald, imag: left.imagd)) case (.cf, .i): return Scalar(DSPComplex(real: left.realf - right.realf, imag: left.imagf)) case (.cd, .i): return Scalar(DSPDoubleComplex(real: left.reald - right.reald, imag: left.imagd)) case (.f, .cf): return Scalar(DSPComplex(real: left.realf - right.realf, imag: -right.imagf)) case (.d, .cd): return Scalar(DSPDoubleComplex(real: left.reald - right.reald, imag: -right.imagd)) case (.i, .cf): return Scalar(DSPComplex(real: left.realf - right.realf, imag: -right.imagf)) case (.i, .cd): return Scalar(DSPDoubleComplex(real: left.reald - right.reald, imag: -right.imagd)) case(.cf, .cf): return Scalar(DSPComplex(real: left.realf - right.realf, imag: left.imagf - right.imagf)) case(.cd, .cd): return Scalar(DSPDoubleComplex(real: left.reald - right.reald, imag: left.imagd - right.imagd)) case(.f, .i): return Scalar( left.realf - right.realf) case(.i, .f): return Scalar( left.realf - right.realf) case(.d, .i): return Scalar( left.reald - right.reald) case(.i, .d): return Scalar( left.reald - right.reald) case (.i, .i): return Scalar( left.int - right.int) default: preconditionFailure("Vsip Scalar types (\(left.type), \(right.type)) not supported for - ") } } public static func / (left: Scalar, right: Scalar) -> Scalar { return left * right.inverse } public static func cmagd(value: Scalar) -> Scalar { var retval: Double let re = Foundation.fabs(value.reald) let im = Foundation.fabs(value.imagd) if re == 0.0 { retval = im } else if im == 0.0 { retval = re } else if im < re { retval = re * Foundation.sqrt(1.0 + (im/re) * (im/re)) } else { retval = im * Foundation.sqrt(1.0 + (re/im) * (re/im)); } return Scalar(retval) } public static func cmagf(value: Scalar) -> Scalar { var retval: Float let re = Foundation.fabsf(value.realf) let im = Foundation.fabsf(value.imagf) if re == Float(0.0) { retval = im } else if im == Float(0.0) { retval = re } else if im < re { retval = re * Foundation.sqrtf(1.0 + (im/re) * (im/re)) } else { retval = im * Foundation.sqrtf(1.0 + (re/im) * (re/im)); } return Scalar(retval) } public static func csqrtd(value: Scalar) -> Scalar { if value.imagd == 0.0 { if value.reald < 0.0 { return Scalar(DSPDoubleComplex(real: 0.0, imag: Foundation.sqrt(-value.reald))) } else { return Scalar(DSPDoubleComplex(real: Foundation.sqrt(value.reald), imag: 0.0)) } } else if 0.0 == value.reald { // pure imaginary let r = Foundation.sqrt((0.5 * Foundation.fabs(value.imagd))) if value.imagd < 0.0 { return Scalar(DSPDoubleComplex(real:r, imag: -(r))) } else { return Scalar(DSPDoubleComplex(real: r, imag: r)) } } else { let r = Foundation.sqrt(0.5 * (Scalar.cmagd(value: value).reald + Foundation.fabs(value.reald))) let s = value.imagd / (2.0 * r) if value.reald < 0.0 { if value.imagd < 0.0 { return Scalar(DSPDoubleComplex(real: -(s), imag: -(r))) } else { return Scalar(DSPDoubleComplex(real: s, imag: r)) } } else { return Scalar(DSPDoubleComplex(real: r, imag: s)) } } } public static func csqrtf(value: Scalar) -> Scalar { if value.imagf == 0.0 { if value.realf < 0.0 { return Scalar(DSPComplex(real: 0.0, imag: Foundation.sqrt(-value.realf))) } else { return Scalar(DSPComplex(real: Foundation.sqrt(value.realf), imag: 0.0)) } } else if 0.0 == value.realf { // pure imaginary let r = Foundation.sqrt((0.5 * Swift.abs(value.imagf))) if value.imagf < 0.0 { return Scalar(DSPComplex(real:r, imag: -(r))) } else { return Scalar(DSPComplex(real: r, imag: r)) } } else { let r = Foundation.sqrt(0.5 * (Scalar.cmagd(value: value).realf + Foundation.fabs(value.realf))) let s = value.imagf / (2.0 * r) if value.realf < 0.0 { if value.imagf < 0.0 { return Scalar(DSPComplex(real: -(s), imag: -(r))) } else { return Scalar(DSPComplex(real: s, imag: r)) } } else { return Scalar(DSPComplex(real: r, imag: s)) } } } public var conj: Scalar { switch self.type { case .d: return self case .f: return self case .cf: return Scalar(self.type, NSNumber(value: self.realf), NSNumber(value: -self.imagf)) case .cd: return Scalar(self.type, NSNumber(value: self.reald), NSNumber(value: -self.imagd)) case .i: return self case .ui: return self } } public var inverse: Scalar { let mag = Scalar.cmagd(value: self) if mag.reald == 0.0 { preconditionFailure("Cannot take inverse of zero") } let type = self.type switch type { case .f: return Scalar(Float(1.0)/self.realf) case .d: return Scalar(1.0/self.reald) case .cf: return Scalar(DSPComplex(real: self.realf/mag.realf, imag: self.imagf/mag.realf)) case .cd: return Scalar(DSPDoubleComplex(real: self.reald/mag.reald, imag: self.imagd/mag.reald)) case .i: return Scalar(1/self.int) case .ui: return Scalar(1/self.int) } } public var sqrt: Scalar { switch self.type { case .f: return Scalar(sqrtf(self.realf)) case .d: let x = Foundation.sqrt(self.reald) return Scalar(x) case .cf: return Scalar.csqrtf(value: self) case .cd: return Scalar.csqrtd(value: self) default: preconditionFailure("sqrt not supported for type \(self.type)") } } public var mag: Scalar { switch self.type { case .d: return Scalar(Foundation.fabs(self.reald)) case .f: return Scalar(Foundation.fabsf(self.realf)) case .cf: return Scalar.cmagf(value: self) case .cd: return Scalar.cmagd(value: self) case .i: return Scalar((self.int > 0 ? self.int : -self.int)) case .ui: return Scalar(self.int) } } public func string(format fmt: String) -> String { return scalarString(formatFmt(fmt), value:self) } } <file_sep>/* Created RJudd January 15, 2000 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mviewattributes_bl.h,v 2.0 2003/02/22 15:48:15 judd Exp $ */ #ifndef _vsip_mviewattributes_bl_h #define _vsip_mviewattributes_bl_h 1 #include"vsip.h" #include"VI.h" #include"vsip_blockattributes_bl.h" struct vsip_mviewattributes_bl { vsip_block_bl* block; vsip_offset offset; vsip_stride row_stride; vsip_length row_length; vsip_stride col_stride; vsip_length col_length; int markings; /* to indicate valid object */ }; #endif /* _vsip_mviewattributes_bl_h */ <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: lud_d.h,v 2.0 2003/02/22 15:23:14 judd Exp $ */ #include"VU_mprintm_d.include" static void lud_d(void){ printf("********\nTEST lud_d\n"); { vsip_index i,j; /* make up some data space and views */ vsip_block_d *block = vsip_blockcreate_d(500,VSIP_MEM_NONE); vsip_mview_d *AC = vsip_mbind_d(block,0,6,6,1,6); vsip_mview_d *AG = vsip_mbind_d(block,36,2,6,18,6); vsip_mview_d *IC = vsip_mbind_d(block,150,1,6,6,6); vsip_mview_d *IG = vsip_mbind_d(block,200,2,6,14,6); vsip_mview_d *B = vsip_mbind_d(block,300,6,6,1,6); vsip_mview_d *A = vsip_mbind_d(block,350,6,6,1,6); vsip_mview_d *X = vsip_mbind_d(block,400,5,6,1,3); vsip_mview_d *Y = vsip_mbind_d(block,450,3,6,1,3); vsip_lu_d* ludC = vsip_lud_create_d(6); vsip_lu_d* ludG = vsip_lud_create_d(6); vsip_mview_d *AT = vsip_mtransview_d(A); vsip_scalar_d chk; vsip_scalar_d data[6][6] = { \ {0.50, 7.00, 10.00, 12.00, -3.00, 0.00}, \ {2.00, 13.00, 18.00, 6.00, 0.00, 130.00}, \ {3.00, -9.00, 2.00, 3.00, 2.00, -9.00}, \ {4.00, 2.00, 2.00, 4.00, 1.00, 2.00}, \ {0.20, 2.00, 9.00, 4.00, 1.00, 2.00}, \ {0.10, 2.00, 0.30, 4.00, 1.00, 2.00}}; vsip_scalar_d ydata[6][3] = { \ { 77.85, 155.70, 311.40}, \ { 942.00, 1884.00, 3768.00}, \ { 1.00, 2.00, 4.00}, \ { 68.00, 136.00, 272.00}, \ { 85.20, 170.40, 340.80}, \ { 59.00, 118.00, 236.00}}; vsip_scalar_d Ident[6][6] = { \ {1, 0, 0, 0, 0, 0}, \ {0, 1, 0, 0, 0, 0}, \ {0, 0, 1, 0, 0, 0}, \ {0, 0, 0, 1, 0, 0}, \ {0, 0, 0, 0, 1, 0}, \ {0, 0, 0, 0, 0, 1}}; for(i=0; i<6; i++){ for(j=0; j<6; j++){ vsip_mput_d(A, i,j,data[i][j]); vsip_mput_d(AC,i,j,data[i][j]); vsip_mput_d(AG,i,j,data[i][j]); vsip_mput_d(IC,i,j,Ident[i][j]); vsip_mput_d(IG,i,j,Ident[i][j]); } } for(i=0; i<6; i++) for(j=0; j<3; j++) vsip_mput_d(X,i,j,ydata[i][j]); printf("Matrix A = \n");VU_mprintm_d("7.2",A);fflush(stdout); vsip_lud_d(ludC,AC); vsip_lud_d(ludG,AG); printf("vsip_lusol(lud,VSIP_MAT_NTRANS,X)\n"); printf("Solve A X = I \n"); fflush(stdout); vsip_lusol_d(ludC,VSIP_MAT_NTRANS,IC); vsip_lusol_d(ludG,VSIP_MAT_NTRANS,IG); printf("for compact case X = \n");VU_mprintm_d("8.4",IC); fflush(stdout); printf("for general case X = \n");VU_mprintm_d("8.4",IG); fflush(stdout); chk = 0; for(i=0; i<6; i++) for(j=0; j<6; j++) chk += fabs(vsip_mget_d(IC,i,j) - vsip_mget_d(IG,i,j)); (chk > .01) ? printf("error\n") : printf("agree\n"); fflush(stdout); vsip_mprod_d(A,IC,B); chk = 0; for(i=0; i<6; i++) for(j=0; j<6; j++) chk += fabs(vsip_mget_d(B,i,j) - Ident[i][j]); vsip_mprod_d(A,IG,B); for(i=0; i<6; i++) for(j=0; j<6; j++) chk += fabs(vsip_mget_d(B,i,j) - Ident[i][j]); printf("mprod(A,X) = \n"); VU_mprintm_d("8.3",B); fflush(stdout); (chk > .01) ? printf("error\n") : printf("correct\n"); fflush(stdout); /************************************************/ /* check case VSIP_MAT_TRANS */ printf("Matrix Transpose A = \n");VU_mprintm_d("7.2",AT);fflush(stdout); for(i=0; i<6; i++){ for(j=0; j<6; j++){ vsip_mput_d(IC,i,j,Ident[i][j]); vsip_mput_d(IG,i,j,Ident[i][j]); } } printf("vsip_lusol(lud,VSIP_MAT_TRANS,X)\n"); printf("Solve trans(A) X = I \n"); fflush(stdout); vsip_lusol_d(ludC,VSIP_MAT_TRANS,IC); vsip_lusol_d(ludG,VSIP_MAT_TRANS,IG); printf("for compact case X = \n");VU_mprintm_d("8.4",IC); fflush(stdout); printf("for general case X = \n");VU_mprintm_d("8.4",IG); fflush(stdout); chk = 0; for(i=0; i<6; i++) for(j=0; j<6; j++) chk += fabs(vsip_mget_d(IC,i,j) - vsip_mget_d(IG,i,j)); (chk > .01) ? printf("error\n") : printf("agree\n"); fflush(stdout); vsip_mprod_d(AT,IC,B); chk = 0; for(i=0; i<6; i++) for(j=0; j<6; j++) chk += fabs(vsip_mget_d(B,i,j) - Ident[i][j]); vsip_mprod_d(AT,IG,B); for(i=0; i<6; i++) for(j=0; j<6; j++) chk += fabs(vsip_mget_d(B,i,j) - Ident[i][j]); printf("mprod(trans(A),X) = \n"); VU_mprintm_d("8.3",B); fflush(stdout); (chk > .01) ? printf("error\n") : printf("correct\n"); fflush(stdout); /************************************************/ /* check case A X = B for VSIP_MAT_NTRANS */ printf("check A X = Y; VSIP_MAT_NTRANS\n"); printf("Y = \n");VU_mprintm_d("8.4",X); vsip_lusol_d(ludC,VSIP_MAT_NTRANS,X); printf("X = \n"); VU_mprintm_d("8.4",X); vsip_mprod_d(A,X,Y); printf(" Y = A X\n");VU_mprintm_d("8.4",Y); chk = 0; for(i=0; i<6; i++) for(j=0; j<3; j++) chk += fabs(vsip_mget_d(Y,i,j) - ydata[i][j]); (chk > .01) ? printf("error\n") : printf("agree\n"); fflush(stdout); /************************************************/ /* check case trans(A) X = B for VSIP_MAT_TRANS */ for(i=0; i<6; i++) for(j=0; j<3; j++) vsip_mput_d(X,i,j,ydata[i][j]); printf("Y = \n");VU_mprintm_d("8.4",X); vsip_lusol_d(ludG,VSIP_MAT_TRANS,X); vsip_mprod_d(AT,X,Y); printf("X = \n");VU_mprintm_d("8.4",X); printf("Y = trans(A) X\n");VU_mprintm_d("8.4",Y); chk = 0; for(i=0; i<6; i++) for(j=0; j<3; j++) chk += fabs(vsip_mget_d(Y,i,j) - ydata[i][j]); (chk > .01) ? printf("error\n") : printf("agree\n"); fflush(stdout); /***************************************************/ /* destroy stuff */ vsip_mdestroy_d(AC); vsip_mdestroy_d(AG); vsip_mdestroy_d(IC); vsip_mdestroy_d(IG); vsip_mdestroy_d(B); vsip_mdestroy_d(A); vsip_mdestroy_d(X); vsip_mdestroy_d(Y); vsip_malldestroy_d(AT); vsip_lud_destroy_d(ludC); vsip_lud_destroy_d(ludG); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mcloneview_bl.h,v 2.0 2003/02/22 15:23:34 judd Exp $ */ static void mcloneview_bl(void){ printf("********\nTEST mcloneview_bl\n"); { vsip_scalar_bl data[10][4] = {{0, 1, 1, 1}, {0, 1, 0, 0}, {0, 1, 0, 1}, {0, 1, 0, 0}, {1, 0, 0, 0}, {0, 0, 0, 0}, {0, 1, 1, 1}, {0, 1, 1, 0}, {1, 1, 0, 1}, {0, 1, 1, 0}}; vsip_offset o = 4; vsip_stride rs = 2, cs = 8; vsip_length m = 10, n = 4; vsip_block_bl *b = vsip_blockcreate_bl(100,VSIP_MEM_NONE); vsip_mview_bl *v = vsip_mbind_bl(b,o,cs,m,rs,n); vsip_mview_bl *sv = vsip_mcloneview_bl(v); vsip_scalar_bl chk = VSIP_FALSE; int i,j; for(i=0; i< (int)m; i++) for(j=0; j< (int)n; j++) vsip_mput_bl(v,i,j,data[i][j]); for(i=0; i< (int)m; i++){ for(j=0; j< (int)n; j++){ vsip_scalar_bl d = (data[i][j] != 0) ? VSIP_TRUE : VSIP_FALSE; vsip_scalar_bl a = (vsip_mget_bl(sv,i,j) != VSIP_FALSE) ? VSIP_TRUE : VSIP_FALSE; if(a != d) chk = VSIP_TRUE; } } (chk == VSIP_TRUE) ? printf("error \n") : printf("correct \n"); fflush(stdout); vsip_mdestroy_bl(sv); vsip_malldestroy_bl(v); } return; } <file_sep>import Cocoa public func makeRGBImageContext(width: Int, height: Int, buffer: [Double]) -> CGContext { let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue let colorSpace = CGColorSpaceCreateDeviceRGB() let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 4 * width, space: colorSpace, bitmapInfo: bitmapInfo) var pix: [UInt8] = [0,0,0,0] let dta = UnsafeMutablePointer<UInt8>(mutating: context?.data?.assumingMemoryBound(to: UInt8.self))! // Write image data for y in 0..<height { let jmp = 4 * width * y for x in 0..<width { let indxBuf = y * width + x setRGB(ptr: &pix, val: buffer[indxBuf]) let indxPix = 4 * x + jmp dta[indxPix] = pix[0] // red dta[indxPix+1] = pix[1] // green dta[indxPix+2] = pix[2] // blue dta[indxPix+3] = pix[3] // alpha } } return context! } public func makeImage(context: CGContext) -> NSImage { let size = NSSize(width: context.width, height: context.height) return NSImage(cgImage: context.makeImage()!, size: size) } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D881 */ #ifndef _vsip_ccorr1dattributes_f #define _vsip_ccorr1dattributes_f 1 #include"VI.h" struct vsip_ccorr1dattributes_f{ vsip_cvview_f *h; vsip_cvview_f *x; vsip_fft_f *fft; vsip_length n; vsip_length m; vsip_length mn; vsip_length N; vsip_length lag_len; int ntimes; vsip_support_region support; vsip_alg_hint hint; }; #endif /* _vsip_ccorr1dattributes_f */ <file_sep>/* Created RJudd August 30, 2002 */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_ccholsol_d.c,v 2.2 2004/07/30 16:05:12 judd Exp $ */ #include"vsip.h" #include"vsip_blockattributes_d.h" #include"vsip_cblockattributes_d.h" #include"vsip_cmviewattributes_d.h" #include"vsip_cvviewattributes_d.h" #include"vsip_ccholdattributes_d.h" int vsip_ccholsol_d( const vsip_cchol_d *chol, const vsip_cmview_d *XB) { int retval = 0; const vsip_cmview_d *A = chol->matrix; const vsip_cmview_d *B = XB; if(chol->uplo == VSIP_TR_UPP){ { vsip_scalar_d dot_r,dot_i; vsip_length n_A = A->row_length; vsip_length n_B = B->row_length; vsip_index i,j; vsip_stride A_diag_str =(A->row_stride + A->col_stride) * A->block->cstride; vsip_offset off_A = A->offset * A->block->cstride; vsip_scalar_d d0 = *(A->block->R->array + off_A); vsip_length n = n_B; vsip_stride ar_str = A->col_stride * A->block->cstride; /* doing transpose here */ vsip_stride ac_str = A->row_stride * A->block->cstride; /* doing transpose here */ vsip_stride bc_str = B->col_stride * B->block->cstride; vsip_stride br_str = B->row_stride * B->block->cstride; vsip_scalar_d *a_re,*a_im; vsip_offset off_br0 = B->offset * B->block->cstride; vsip_offset off_br = off_br0; vsip_scalar_d *b_re = B->block->R->array + off_br; vsip_scalar_d *b_im = B->block->I->array + off_br; vsip_offset off_b0 = off_br0; vsip_offset off_b; vsip_scalar_d *b; vsip_offset off_a = A->offset * A->block->cstride; if((A->block->cstride == 2) && (B->block->cstride == 2)){ while(n-- >0){ *b_re /= d0; *(b_re + 1) /= d0; b_re += br_str; } for(i=1; i<n_A; i++){ off_A += A_diag_str; d0 = *(A->block->R->array + off_A); off_b0 += bc_str; off_b = off_b0; off_a += ac_str; off_br = off_br0; for(j=0; j<n_B; j++){ n = i; a_re = A->block->R->array + off_a; b_re = B->block->R->array + off_br; dot_r = 0; dot_i = 0; while(n-- > 0){ vsip_scalar_d ar = *a_re, ai = *(a_re + 1); vsip_scalar_d br = *b_re, bi = *(b_re + 1); dot_r += ar * br + ai * bi; dot_i += ar * bi - ai * br; a_re += ar_str; b_re += bc_str; } b = B->block->R->array + off_b; *b = (*b - dot_r)/d0; b++; *b = (*b - dot_i)/d0; off_b += br_str; off_br += br_str; } } } else { while(n-- >0){ *b_re /= d0; *b_im /= d0; b_re += br_str; b_im += br_str; } for(i=1; i<n_A; i++){ off_A += A_diag_str; d0 = *(A->block->R->array + off_A); off_b0 += bc_str; off_b = off_b0; off_a += ac_str; off_br = off_br0; for(j=0; j<n_B; j++){ n = i; a_re = A->block->R->array + off_a; a_im = A->block->I->array + off_a; b_re = B->block->R->array + off_br; b_im = B->block->I->array + off_br; dot_r = 0; dot_i = 0; while(n-- > 0){ dot_r += (*a_re * *b_re + *a_im * *b_im); dot_i += (*a_re * *b_im - *a_im * *b_re); a_re += ar_str; a_im += ar_str; b_re += bc_str; b_im += bc_str; } b = B->block->R->array + off_b; *b = (*b - dot_r)/d0; b = B->block->I->array + off_b; *b = (*b - dot_i)/d0; off_b += br_str; off_br += br_str; } } } } { vsip_scalar_d dot_r,dot_i; vsip_scalar_d *b; vsip_stride ar_str = A->row_stride * A->block->cstride; vsip_length n_A = A->row_length; vsip_length n_A_1 = n_A - 1; vsip_stride A_diag_str = (A->col_stride + A->row_stride); vsip_length n_B = B->row_length; vsip_offset off_A = A->block->cstride * ( A->offset + (n_A_1) * A_diag_str); vsip_offset off_ar = (A->offset + n_A * A_diag_str - A->col_stride) * A->block->cstride; vsip_scalar_d d0 = *(A->block->R->array + off_A); vsip_index i,j; vsip_offset off_br0 = (n_A_1 * B->col_stride + B->offset) * B->block->cstride; vsip_offset off_br = off_br0; vsip_offset off_bc0 = (B->offset + B->col_stride * n_A) * B->block->cstride; vsip_offset off_bc; vsip_stride br_str = B->row_stride * B->block->cstride; vsip_stride bc_str = B->col_stride * B->block->cstride; vsip_scalar_d *b_re = B->block->R->array + off_br; vsip_scalar_d *b_im = B->block->I->array + off_br; vsip_scalar_d *a_re,*a_im; vsip_length n = n_B; if((A->block->cstride == 2) && (B->block->cstride == 2)){ while(n-- >0){ *b_re /= d0; *(b_re + 1) /= d0; b_re += br_str; } A_diag_str *= A->block->cstride; for(i=1; i<n_A; i++){ off_A -= A_diag_str; d0 = *(A->block->R->array + off_A); off_br0 -= bc_str; off_br = off_br0; off_bc0 -= bc_str; off_bc = off_bc0; off_ar -= A_diag_str; for(j=0; j<n_B; j++){ n = i; a_re = A->block->R->array + off_ar; b_re = B->block->R->array + off_bc; dot_r = 0; dot_i = 0; while(n-- > 0){ vsip_scalar_d ar = *a_re, ai = *(a_re + 1); vsip_scalar_d br = *b_re, bi = *(b_re + 1); dot_r += ar * br - ai * bi; dot_i += ar * bi + ai * br; a_re += ar_str; b_re += bc_str; } b = B->block->R->array + off_br; *b = (*b - dot_r)/d0; b++; *b = (*b - dot_i)/d0; off_br += br_str; off_bc += br_str; } } } else { while(n-- >0){ *b_re /= d0; *b_im /= d0; b_re += br_str; b_im += br_str; } A_diag_str *= A->block->cstride; for(i=1; i<n_A; i++){ off_A -= A_diag_str; d0 = *(A->block->R->array + off_A); off_br0 -= bc_str; off_br = off_br0; off_bc0 -= bc_str; off_bc = off_bc0; off_ar -= A_diag_str; for(j=0; j<n_B; j++){ n = i; a_re = A->block->R->array + off_ar; a_im = A->block->I->array + off_ar; b_re = B->block->R->array + off_bc; b_im = B->block->I->array + off_bc; dot_r = 0; dot_i = 0; while(n-- > 0){ dot_r += (*a_re * *b_re - *a_im * *b_im); dot_i += (*a_re * *b_im + *a_im * *b_re); a_re += ar_str; a_im += ar_str; b_re += bc_str; b_im += bc_str; } b = B->block->R->array + off_br; *b = (*b - dot_r)/d0; b = B->block->I->array + off_br; *b = (*b - dot_i)/d0; off_br += br_str; off_bc += br_str; } } } } } else { /* must be VSIP_TR_LOW */ { vsip_scalar_d dot_r,dot_i; vsip_scalar_d *b; vsip_length n_A = A->row_length; vsip_length n_B = B->row_length; vsip_index i,j; vsip_stride A_diag_str = (A->row_stride + A->col_stride) * A->block->cstride; vsip_offset off_A = A->offset * A->block->cstride; vsip_scalar_d d0 = *(A->block->R->array + off_A); vsip_length n = B->row_length; vsip_offset off_br0 = B->offset * B->block->cstride; vsip_offset off_br = off_br0; vsip_offset off_bc0 = B->offset * B->block->cstride; vsip_offset off_bc; vsip_scalar_d *b_re = B->block->R->array + off_br; vsip_scalar_d *b_im = B->block->I->array + off_br; vsip_scalar_d *a_re,*a_im; vsip_stride a_str = A->row_stride * A->block->cstride; vsip_stride bc_str = B->col_stride * B->block->cstride; vsip_stride br_str = B->row_stride * B->block->cstride; vsip_offset off_a = A->offset * A->block->cstride; vsip_stride off_a_str = A->col_stride * A->block->cstride; if((A->block->cstride == 2) && (B->block->cstride == 2)){ while(n-- >0){ *b_re /= d0; *(b_re + 1) /= d0; b_re += br_str; } for(i=1; i<n_A; i++){ off_A += A_diag_str; off_br0 += bc_str; off_br = off_br0; off_bc = off_bc0; d0 = *(A->block->R->array + off_A); off_a += off_a_str; for(j=0; j<n_B; j++){ n = i; a_re = A->block->R->array + off_a; a_im = A->block->I->array + off_a; b_re = B->block->R->array + off_bc; b_im = B->block->I->array + off_bc; dot_r = 0; dot_i = 0; while(n-- > 0){ vsip_scalar_d ar = *a_re, ai = *(a_re + 1); vsip_scalar_d br = *b_re, bi = *(b_re + 1); dot_r += ar * br - ai * bi; dot_i += ar * bi + ai * br; a_re += a_str; a_im += a_str; b_re += bc_str; b_im += bc_str; } b = B->block->R->array + off_br; *b = (*b - dot_r)/d0; b++; *b = (*b - dot_i)/d0; off_br += br_str; off_bc += br_str; } } } else { while(n-- >0){ *b_re /= d0; *b_im /= d0; b_re += br_str; b_im += br_str; } for(i=1; i<n_A; i++){ off_A += A_diag_str; off_br0 += bc_str; off_br = off_br0; off_bc = off_bc0; d0 = *(A->block->R->array + off_A); off_a += off_a_str; for(j=0; j<n_B; j++){ n = i; a_re = A->block->R->array + off_a; a_im = A->block->I->array + off_a; b_re = B->block->R->array + off_bc; b_im = B->block->I->array + off_bc; dot_r = 0; dot_i = 0; while(n-- > 0){ dot_r += (*a_re * *b_re - *a_im * *b_im); dot_i += (*a_re * *b_im + *a_im * *b_re); a_re += a_str; a_im += a_str; b_re += bc_str; b_im += bc_str; } b = B->block->R->array + off_br; *b = (*b - dot_r)/d0; b = B->block->I->array + off_br; *b = (*b - dot_i)/d0; off_br += br_str; off_bc += br_str; } } } } { vsip_scalar_d dot_r,dot_i; vsip_length n_A = A->row_length; vsip_length n_A_1 = n_A - 1; vsip_length n_B = B->row_length; vsip_index i,j; vsip_stride A_diag_str = A->row_stride + A->col_stride; vsip_offset off_Bc0 = (B->offset + B->col_stride * n_A ) * B->block->cstride; vsip_offset off_Bc; vsip_offset off_A = A->block->cstride * (A->offset + (n_A-1)*(A_diag_str)); vsip_offset off_Ar= (A->offset +n_A * A_diag_str - A->row_stride) * A->block->cstride; vsip_stride off_A_str = A->block->cstride * (A->row_stride + A->col_stride); vsip_stride a_str = A->col_stride * A->block->cstride; vsip_scalar_d d0 = *(A->block->R->array + off_A); vsip_length n = n_B; vsip_offset off_Br = (B->offset + n_A_1 * B->col_stride) * B->block->cstride; vsip_offset off_Br0 = off_Br; vsip_stride off_Br_str = B->block->cstride * B->col_stride; /* B row stride */ vsip_stride bc_str = off_Br_str; vsip_stride br_str = B->row_stride * B->block->cstride; vsip_scalar_d *a_re,*a_im, *b; vsip_scalar_d *b_re = B->block->R->array + off_Br; vsip_scalar_d *b_im = B->block->I->array + off_Br; if((A->block->cstride == 2) && (B->block->cstride == 2)){ while(n-- >0){ *b_re /= d0; *(b_re + 1) /= d0; b_re += br_str; } A_diag_str *= A->block->cstride; for(i=1; i<n_A; i++){ off_A -= off_A_str; d0 = *(A->block->R->array + off_A); off_Br0 -= off_Br_str; off_Br = off_Br0; off_Ar -= A_diag_str; off_Bc0 -= bc_str; off_Bc = off_Bc0; for(j=0; j<n_B; j++){ n = i; a_re = A->block->R->array + off_Ar; b_re = B->block->R->array + off_Bc; dot_r = 0; dot_i = 0; while(n-- > 0){ vsip_scalar_d ar = *a_re, ai=*(a_re + 1); vsip_scalar_d br = *b_re, bi=*(b_re + 1); dot_r += (ar * br + ai * bi); dot_i += (ar * bi - ai * br); a_re += a_str; b_re += bc_str; } b = B->block->R->array + off_Br; *b = (*b - dot_r)/d0; b++; *b = (*b - dot_i)/d0; off_Br += br_str; off_Bc += br_str; } } } else { while(n-- >0){ *b_re /= d0; *b_im /= d0; b_re += br_str; b_im += br_str; } A_diag_str *= A->block->cstride; for(i=1; i<n_A; i++){ off_A -= off_A_str; d0 = *(A->block->R->array + off_A); off_Br0 -= off_Br_str; off_Br = off_Br0; off_Ar -= A_diag_str; off_Bc0 -= bc_str; off_Bc = off_Bc0; for(j=0; j<n_B; j++){ n = i; a_re = A->block->R->array + off_Ar; a_im = A->block->I->array + off_Ar; b_re = B->block->R->array + off_Bc; b_im = B->block->I->array + off_Bc; dot_r = 0; dot_i = 0; while(n-- > 0){ dot_r += (*a_re * *b_re + *a_im * *b_im); dot_i += (*a_re * *b_im - *a_im * *b_re); a_re += a_str; a_im += a_str; b_re += bc_str; b_im += bc_str; } b = B->block->R->array + off_Br; *b = (*b - dot_r)/d0; b = B->block->I->array + off_Br; *b = (*b - dot_i)/d0; off_Br += br_str; off_Bc += br_str; } } } } } return retval; } <file_sep>/* Created RJudd March 14, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mvprod_f.c,v 2.0 2003/02/22 15:19:01 judd Exp $ */ /* Modified to vsip_mvpord_f.c */ /* April 21, 1998 1,2 to row,col */ /* Removed Development Mode RJudd Sept 00 */ #include"vsip.h" #include"vsip_vviewattributes_f.h" #include"vsip_mviewattributes_f.h" void (vsip_mvprod_f)( const vsip_mview_f* A, const vsip_vview_f* b, const vsip_vview_f* r) { { vsip_length nx = 0, mx = 0; vsip_scalar_f *bp = b->block->array + b->offset * b->block->rstride, *rp = r->block->array + r->offset * r->block->rstride, *Ayp = A->block->array + A->offset * A->block->rstride, *Axp = Ayp; vsip_stride rst = r->stride * r->block->rstride, ARst = A->row_stride * A->block->rstride, ACst = A->col_stride * A->block->rstride, bst = b->stride * b->block->rstride; while(nx++ < A->col_length){ *rp = 0; mx = 0; while(mx++ < A->row_length){ *rp += *bp * *Axp; bp += bst; Axp += ARst; } bp = b->block->array + b->offset * b->block->rstride; Axp = (Ayp += ACst); rp += rst; } } } <file_sep>from vsip import * import vsiputils as vsip import vsipUser as VU from VI_givens_d import * def testGivens(): A = vsip.create('cmview_d',(10,6,VSIP_ROW,VSIP_MEM_NONE)); czero = vsip_cmplx_d(0.0,0.0); vsip.fill(czero,A); for i in range(vsip.getrowlength(A)): ac = vsip.colview(A,i); ac_r= vsip.realview(ac); ac_i = vsip.imagview(ac); vsip.ramp(-1.3,1.1,ac_r); vsip.ramp(+1.3,-1.1,ac_i); vsip.destroy(ac_r); vsip.destroy(ac_i); vsip.destroy(ac); ad = vsip_cmdiagview_d(A,0); ad_r = vsip_vrealview_d(ad); ad_i = vsip_vimagview_d(ad); vsip.ramp(3,1.2,ad_r); vsip.ramp(3,-1.2,ad_i); vsip.destroy(ad_i); vsip.destroy(ad_r); vsip.destroy(ad); print("Input data \n"); print("A = " + VU.mstring(A,"%6.4f")) VI_cgivens_r_d(A) print("R = " + VU.mstring(A,"%7.4f")) vsip.allDestroy(A); testGivens() <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: rscvdiv_d.h,v 2.0 2003/02/22 15:23:27 judd Exp $ */ #include"VU_cvprintm_d.include" static void rscvdiv_d(void){ printf("\n********\nTEST rscvdiv_d\n"); { vsip_scalar_d alpha = 2.5; vsip_cvview_d *b = vsip_cvcreate_d(7,VSIP_MEM_NONE); vsip_cvview_d *c = vsip_cvcreate_d(7,VSIP_MEM_NONE); vsip_vview_d *c_i = vsip_vimagview_d(c); vsip_cvview_d *chk = vsip_cvcreate_d(7,VSIP_MEM_NONE); vsip_vview_d *chk_i = vsip_vimagview_d(chk); vsip_scalar_d data_r[] ={.1, .2, .3, .4, .5, .6, .7}; vsip_scalar_d data_i[] ={7,6,5,4,3,2,1}; vsip_scalar_d data_ans[] ={.0051,-.3571, .0139,-.4162, .0299,-.4982, .0619,-.6188, .1351,-.8108, .3440,-1.1468, 1.1745,-1.6779}; vsip_cblock_d *cblock = vsip_cblockbind_d(data_r,data_i,7,VSIP_MEM_NONE); vsip_cblock_d *cblock_ans = vsip_cblockbind_d(data_ans, (vsip_scalar_d*)NULL,7,VSIP_MEM_NONE); vsip_cvview_d *u_b = vsip_cvbind_d(cblock,0,1,7); vsip_cvview_d *u_ans = vsip_cvbind_d(cblock_ans,0,1,7); vsip_cblockadmit_d(cblock,VSIP_TRUE); vsip_cblockadmit_d(cblock_ans,VSIP_TRUE); vsip_cvcopy_d_d(u_b,b); printf("call vsip_rscvdiv_d(alpha,b,c)\n"); printf("alpha = %f\n",alpha); printf("b =\n");VU_cvprintm_d("8.6",b); printf("test normal out of place\n"); vsip_rscvdiv_d(alpha,b,c); printf("c =\n");VU_cvprintm_d("8.6",c); printf("right answer =\n");VU_cvprintm_d("8.4",u_ans); vsip_cvsub_d(u_ans,c,chk); vsip_cvmag_d(chk,chk_i); vsip_vclip_d(chk_i,.0002,.0002,0,1,chk_i); if(vsip_vsumval_d(chk_i) > .5) printf("error\n"); else printf("correct\n"); printf("test b,c inplace\n"); vsip_rscvdiv_d(alpha,b,b); vsip_cvsub_d(u_ans,b,chk); vsip_cvmag_d(chk,chk_i); vsip_vclip_d(chk_i,.0002,.0002,0,1,chk_i); if(vsip_vsumval_d(chk_i) > .5) printf("error\n"); else printf("correct\n"); vsip_cvalldestroy_d(b); vsip_vdestroy_d(c_i); vsip_cvalldestroy_d(c); vsip_vdestroy_d(chk_i); vsip_cvalldestroy_d(chk); vsip_cvalldestroy_d(u_b); vsip_cvalldestroy_d(u_ans); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mcloneview_li.c,v 2.0 2003/02/22 15:18:54 judd Exp $ */ #include"vsip.h" #include"vsip_mviewattributes_li.h" vsip_mview_li* vsip_mcloneview_li( const vsip_mview_li* mview_li) { vsip_mview_li* mcloneview_li = (vsip_mview_li*)malloc(sizeof(vsip_mview_li)); if(mcloneview_li != NULL){ *mcloneview_li = *mview_li; } return mcloneview_li; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_stride_vi.h,v 2.1 2007/04/18 17:05:56 judd Exp $ */ static void get_put_stride_vi(void){ printf("********\nTEST get_put_stride_vi\n"); { vsip_offset ivo = 3; vsip_stride ivs = 2; vsip_length ivl = 3; vsip_stride jvs = 3; vsip_block_vi *b = vsip_blockcreate_vi(80,VSIP_MEM_NONE); vsip_vview_vi *v = vsip_vbind_vi(b,ivo,ivs,ivl); vsip_stride s; printf("test vgetstride_vi\n"); fflush(stdout); { s = vsip_vgetstride_vi(v); (s == ivs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputstride_vi\n"); fflush(stdout); { vsip_vputstride_vi(v,jvs); s = vsip_vgetstride_vi(v); (s == jvs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } vsip_valldestroy_vi(v); } return; } <file_sep>#!/usr/bin/env python from distutils.core import setup setup(name='pyJvsip', version='0.3.1', description='pyJvsip is a vector/matrix signal processing module bassed on the VSIPL C Library', author='<NAME>', author_email='<EMAIL>', license='MIT ( http://opensource.org/licenses/MIT )', py_modules=['pyJvsip','vsipElementwiseElementary','vsipElementwiseManipulation',\ 'vsipElementwiseUnary','vsipElementwiseBinary','vsipElementwiseTernary',\ 'vsipElementwiseLogical','vsipElementwiseSelection','vsipElementwiseBandB', 'vsipElementwiseCopy','vsipSignalProcessing','vsipLinearAlgebra','vsipAddendum'], ) <file_sep>/* Created by RJudd July 4, 2002 */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_rcfftmop_d_loop.h,v 2.0 2003/02/22 15:18:33 judd Exp $ */ #ifndef _VI_RCFFTMOP_D_LOOP_H #define _VI_RCFFTMOP_D_LOOP_H 1 /* Use a loop of vsip_rcfftop_d.h to calculate fftm */ /* input matrix x, output matrix y, fftm object fftm */ #include"VI_mrowview_d.h" #include"VI_mcolview_d.h" #include"VI_cmrowview_d.h" #include"VI_cmcolview_d.h" void vsip_rcfftmop_d( const vsip_fftm_d *Offt, const vsip_mview_d *X, const vsip_cmview_d *Z) { vsip_fftm_d Nfft = *Offt; vsip_fftm_d *fftm = &Nfft; vsip_fft_d *fft = (vsip_fft_d*)fftm->ext_fftm_obj; vsip_index k = 0; vsip_vview_d vv; vsip_cvview_d zz; if(fftm->major == VSIP_ROW){ while(k < X->col_length){ vsip_rcfftop_d(fft, VI_mrowview_d(X,k,&vv), VI_cmrowview_d(Z,k,&zz)); k++; } } else { /* must be column */ while(k < X->row_length){ vsip_rcfftop_d(fft, VI_mcolview_d(X,k,&vv), VI_cmcolview_d(Z,k,&zz)); k++; } } } #endif /* _VI_RCFFTMOP_D_LOOP_H */ <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cvcopyfrom_user_d.h,v 1.1 2007/04/18 03:59:06 judd Exp $ */ #include"VU_cvprintm_d.include" static void cvcopyfrom_user_d(void){ int i; printf("********\nTEST cvcopyfrom_user_d\n"); { /* test interleaved */ vsip_cblock_d *block = vsip_cblockcreate_d(200,VSIP_MEM_NONE); vsip_scalar_d input[10]={0,1,2,3,4,5,6,7,8,9}; vsip_cvview_d *view = vsip_cvbind_d(block,100,-2,5); vsip_cvview_d *all = vsip_cvbind_d(block,0,1,200); vsip_scalar_d check = 0; vsip_cvfill_d(vsip_cmplx_d(-1,-1),all); vsip_cvcopyfrom_user_d(input,(vsip_scalar_d*)NULL,view); VU_cvprintm_d("3.2",view); for(i=0; i<5; i++){ vsip_cscalar_d t = vsip_cvget_d(view,(vsip_index)i); check += fabs(input[2*i] - vsip_real_d(t)); check += fabs(input[2*i+1] - vsip_imag_d(t)); } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_cvdestroy_d(all); vsip_cvdestroy_d(view); vsip_cblockdestroy_d(block); } { /* test split */ vsip_cblock_d *block = vsip_cblockcreate_d(200,VSIP_MEM_NONE); vsip_scalar_d input_r[5]={0,2,4,6,8}; vsip_scalar_d input_i[5]={1,3,5,7,9}; vsip_scalar_d check = 0; vsip_cvview_d *view = vsip_cvbind_d(block,100,3,5); vsip_cvview_d *all = vsip_cvbind_d(block,0,1,200); vsip_cvfill_d(vsip_cmplx_d(-1,-1),all); vsip_cvcopyfrom_user_d(input_r,input_i,view); printf("split\n"); VU_cvprintm_d("3.2",view); for(i=0; i<5; i++){ vsip_cscalar_d t = vsip_cvget_d(view,(vsip_index)i); check += fabs(input_r[i] - vsip_real_d(t)); check += fabs(input_i[i] - vsip_imag_d(t)); } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_cvdestroy_d(all); vsip_cvdestroy_d(view); vsip_cblockdestroy_d(block); } return; } <file_sep>// // VectorExplorerControllerWindow.swift // VectorExplorer // // Created by <NAME> on 1/16/17. // Copyright © 2017 JVSIP. All rights reserved. // import Cocoa import SwiftVsip class VectorExplorerControllerWindow: NSWindowController { @IBOutlet weak var block: NSTextField! @IBOutlet weak var offset: NSTextField! @IBOutlet weak var stride: NSTextField! @IBOutlet weak var length: NSTextField! @IBOutlet weak var vectorValues: NSTextView! @IBOutlet weak var blockValues: NSTextView! var blk: Vsip.Block? var vec: Vsip.Vector? override var windowNibName: String? { return "VectorExplorerControllerWindow" } override func windowDidLoad() { super.windowDidLoad() self.block.integerValue = 1 self.offset.integerValue = 0 self.length.integerValue = 1 self.stride.integerValue = 0 // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file. } @IBAction func blockCreate(sender: AnyObject){ let length = block.integerValue self.blk = createBlock(length: length) self.vec = Vsip.Vector(block: self.blk!, offset: 0, stride: 1, length: length) self.offset.integerValue = 0 self.stride.integerValue = 1 self.length.integerValue = length let _ = self.blk?.vector().ramp(Vsip.Scalar(0.0), increment: Vsip.Scalar(1.0)) self.vectorValues.string = (self.vec?.mString("3.0"))! self.blockValues.string = self.blk?.vector().mString("3.0") } fileprivate var toLong: Bool { return (self.vec?.offset)! + (self.vec?.stride)! * (self.vec?.length)! > (self.blk?.length)! } fileprivate var toShort: Bool { return (self.vec?.offset)! + (self.vec?.stride)! * (self.vec?.length)! < 1 } @IBAction func setOffset(sender: AnyObject){ self.vec?.offset = self.offset.integerValue if toLong { self.vectorValues.string = "Too Long" } else if toShort { self.vectorValues.string = "Too Short" } else { self.vectorValues.string = (self.vec?.mString("3.0"))! } } @IBAction func setLength(sender: AnyObject){ self.vec?.length = self.length.integerValue if toLong { self.vectorValues.string = "Too Long" } else if toShort { self.vectorValues.string = "Too Short" } else { self.vectorValues.string = (self.vec?.mString("3.0"))! } } @IBAction func setStride(sender: AnyObject) { self.vec?.stride = self.stride.integerValue if toLong { self.vectorValues.string = "Too Long" } else if toShort { self.vectorValues.string = "Too Short" } else { self.vectorValues.string = (self.vec?.mString("3.0"))! } } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_length_uc.h,v 2.1 2007/04/18 17:05:56 judd Exp $ */ static void get_put_length_uc(void){ printf("********\nTEST get_put_length_uc\n"); { vsip_offset ivo = 3; vsip_stride ivs = 0; vsip_length ivl = 3; vsip_length jvl = 5; vsip_stride irs = 0, ics = 0; vsip_length irl = 2, icl = 3; vsip_length jrl = 5, jcl = 2; vsip_stride ixs = 0, iys = 0, izs = 0; vsip_length ixl = 2, iyl = 3, izl = 4; vsip_length jxl = 3, jyl = 4, jzl = 2; vsip_block_uc *b = vsip_blockcreate_uc(80,VSIP_MEM_NONE); vsip_vview_uc *v = vsip_vbind_uc(b,ivo,ivs,ivl); vsip_mview_uc *m = vsip_mbind_uc(b,ivo,ics,icl,irs,irl); vsip_tview_uc *t = vsip_tbind_uc(b,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_length s; printf("test vgetlength_uc\n"); fflush(stdout); { s = vsip_vgetlength_uc(v); (s == ivl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputlength_uc\n"); fflush(stdout); { vsip_vputlength_uc(v,jvl); s = vsip_vgetlength_uc(v); (s == jvl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /*************************************************************************/ printf("test mgetrowlength_uc\n"); fflush(stdout); { s = vsip_mgetrowlength_uc(m); (s == irl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputrowlength_uc\n"); fflush(stdout); { vsip_mputrowlength_uc(m,jrl); s = vsip_mgetrowlength_uc(m); (s == jrl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test mgetcollength_uc\n"); fflush(stdout); { s = vsip_mgetcollength_uc(m); (s == icl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputcollength_uc\n"); fflush(stdout); { vsip_mputcollength_uc(m,jcl); s = vsip_mgetcollength_uc(m); (s == jcl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /*************************************************************************/ printf("test tgetxlength_uc\n"); fflush(stdout); { s = vsip_tgetxlength_uc(t); (s == ixl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputxlength_uc\n"); fflush(stdout); { vsip_tputxlength_uc(t,jxl); s = vsip_tgetxlength_uc(t); (s == jxl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test tgetylength_uc\n"); fflush(stdout); { s = vsip_tgetylength_uc(t); (s == iyl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputylength_uc\n"); fflush(stdout); { vsip_tputylength_uc(t,jyl); s = vsip_tgetylength_uc(t); (s == jyl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test tgetzlength_uc\n"); fflush(stdout); { s = vsip_tgetzlength_uc(t); (s == izl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputzlength_uc\n"); fflush(stdout); { vsip_tputzlength_uc(t,jzl); s = vsip_tgetzlength_uc(t); (s == jzl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } vsip_vdestroy_uc(v); vsip_mdestroy_uc(m); vsip_talldestroy_uc(t); } return; } <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cmvprod4_f.c,v 2.1 2006/04/27 01:58:00 judd Exp $ */ #include"vsip.h" #include"vsip_cvviewattributes_f.h" #include"vsip_cmviewattributes_f.h" void (vsip_cmvprod4_f)( const vsip_cmview_f* A, const vsip_cvview_f* b, const vsip_cvview_f* r) { vsip_scalar_f *bp0_r = b->block->R->array + b->offset * b->block->cstride, *rp0_r = r->block->R->array + r->offset * r->block->cstride, *Ap00_r = A->block->R->array + A->offset * A->block->cstride; vsip_scalar_f *bp0_i = b->block->I->array + b->offset * b->block->cstride, *rp0_i = r->block->I->array + r->offset * r->block->cstride, *Ap00_i = A->block->I->array + A->offset * A->block->cstride; vsip_stride rst = r->stride * r->block->cstride, ARst = A->row_stride * A->block->cstride, ACst = A->col_stride * A->block->cstride, bst = b->stride * b->block->cstride; vsip_cscalar_f b0, b1, b2, b3; vsip_cscalar_f a00, a01, a02, a03; vsip_cscalar_f a10, a11, a12, a13; vsip_cscalar_f a20, a21, a22, a23; vsip_cscalar_f a30, a31, a32, a33; vsip_scalar_f *Ap10_r = Ap00_r + ACst, *bp1_r = bp0_r + bst, *rp1_r = rp0_r + rst; vsip_scalar_f *Ap20_r = Ap10_r + ACst, *bp2_r = bp1_r + bst, *rp2_r = rp1_r + rst; vsip_scalar_f *Ap30_r = Ap20_r + ACst, *bp3_r = bp2_r + bst, *rp3_r = rp2_r + rst; vsip_scalar_f *Ap10_i = Ap00_i + ACst, *bp1_i = bp0_i + bst, *rp1_i = rp0_i + rst; vsip_scalar_f *Ap20_i = Ap10_i + ACst, *bp2_i = bp1_i + bst, *rp2_i = rp1_i + rst; vsip_scalar_f *Ap30_i = Ap20_i + ACst, *bp3_i = bp2_i + bst, *rp3_i = rp2_i + rst; b0.r = *bp0_r; b1.r = *bp1_r; b2.r = *bp2_r; b3.r = *bp3_r; b0.i = *bp0_i; b1.i = *bp1_i; b2.i = *bp2_i; b3.i = *bp3_i; a00.r = *Ap00_r; a01.r = *(Ap00_r+ARst); a02.r = *(Ap00_r + 2 * ARst); a03.r = *(Ap00_r + 3 * ARst); a10.r = *Ap10_r; a11.r = *(Ap10_r+ARst); a12.r = *(Ap10_r + 2 * ARst); a13.r = *(Ap10_r + 3 * ARst); a20.r = *Ap20_r; a21.r = *(Ap20_r+ARst); a22.r = *(Ap20_r + 2 * ARst); a23.r = *(Ap20_r + 3 * ARst); a30.r = *Ap30_r; a31.r = *(Ap30_r+ARst); a32.r = *(Ap30_r + 2 * ARst); a33.r = *(Ap30_r + 3 * ARst); a00.i = *Ap00_i; a01.i = *(Ap00_i+ARst); a02.i = *(Ap00_i + 2 * ARst); a03.i = *(Ap00_i + 3 * ARst); a10.i = *Ap10_i; a11.i = *(Ap10_i+ARst); a12.i = *(Ap10_i + 2 * ARst); a13.i = *(Ap10_i + 3 * ARst); a20.i = *Ap20_i; a21.i = *(Ap20_i+ARst); a22.i = *(Ap20_i + 2 * ARst); a23.i = *(Ap20_i + 3 * ARst); a30.i = *Ap30_i; a31.i = *(Ap30_i+ARst); a32.i = *(Ap30_i + 2 * ARst); a33.i = *(Ap30_i + 3 * ARst); *rp0_r = (b0.r * a00.r + b1.r * a01.r + b2.r * a02.r + b3.r * a03.r) - (b0.i * a00.i + b1.i * a01.i + b2.i * a02.i + b3.i * a03.i); *rp1_r = (b0.r * a10.r + b1.r * a11.r + b2.r * a12.r + b3.r * a13.r) - (b0.i * a10.i + b1.i * a11.i + b2.i * a12.i + b3.i * a13.i); *rp2_r = (b0.r * a20.r + b1.r * a21.r + b2.r * a22.r + b3.r * a23.r) - (b0.i * a20.i + b1.i * a21.i + b2.i * a22.i + b3.i * a23.i); *rp3_r = (b0.r * a30.r + b1.r * a31.r + b2.r * a32.r + b3.r * a33.r) - (b0.i * a30.i + b1.i * a31.i + b2.i * a32.i + b3.i * a33.i); *rp0_i = b0.r * a00.i + b1.r * a01.i + b2.r * a02.i + b3.r * a03.i + b0.i * a00.r + b1.i * a01.r + b2.i * a02.r + b3.i * a03.r; *rp1_i = b0.r * a10.i + b1.r * a11.i + b2.r * a12.i + b3.r * a13.i + b0.i * a10.r + b1.i * a11.r + b2.i * a12.r + b3.i * a13.r; *rp2_i = b0.r * a20.i + b1.r * a21.i + b2.r * a22.i + b3.r * a23.i + b0.i * a20.r + b1.i * a21.r + b2.i * a22.r + b3.i * a23.r; *rp3_i = b0.r * a30.i + b1.r * a31.i + b2.r * a32.i + b3.r * a33.i + b0.i * a30.r + b1.i * a31.r + b2.i * a32.r + b3.i * a33.r; return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: tmisc_view_d.h,v 2.1 2009/09/05 18:01:45 judd Exp $ */ static void tmisc_view_d(void){ printf("********\nTEST tmisc_view_d\n"); { vsip_index k,j,i; vsip_scalar_d data_r[4][3][4] = {{{0.0, 0.01, 0.02, 0.03}, \ {0.1, 0.11, 0.12, 0.13}, \ {0.2, 0.21, 0.22, 0.23}}, \ {{1.0, 1.01, 1.02, 1.03}, \ {1.1, 1.11, 1.12, 1.13}, \ {1.2, 1.21, 1.22, 1.23}}, \ {{2.0, 2.01, 2.02, 2.03}, \ {2.1, 2.11, 2.12, 2.13}, \ {2.2, 2.21, 2.22, 2.23}}, \ {{3.0, 3.01, 3.02, 3.03}, \ {3.1, 3.11, 3.12, 3.13}, \ {3.2, 3.21, 3.22, 3.23}}}; /* if a problem with tcreate is suspected check both leading and trailing options here */ vsip_tview_d *tview_a = vsip_tcreate_d(12,9,12,VSIP_LEADING,VSIP_MEM_NONE); /* vsip_tview_d *tview_a = vsip_tcreate_d(12,9,12,VSIP_TRAILING,VSIP_MEM_NONE); */ vsip_block_d *block_a = vsip_tgetblock_d(tview_a); vsip_tview_d *tview_b = vsip_tsubview_d(tview_a,1,2,3,4,3,4); vsip_stride z_a_st = vsip_tgetzstride_d(tview_a); vsip_stride y_a_st = vsip_tgetystride_d(tview_a); vsip_stride x_a_st = vsip_tgetxstride_d(tview_a); vsip_offset b_o_calc = z_a_st + 2 * y_a_st + 3 * x_a_st; vsip_offset b_o_get = vsip_tgetoffset_d(tview_b); vsip_tview_d *v = vsip_tbind_d(block_a,b_o_calc, z_a_st,4, y_a_st,3, x_a_st,4); vsip_mview_d *mview = (vsip_mview_d*)NULL; vsip_vview_d *vview = (vsip_vview_d*)NULL; vsip_tview_d *tview = (vsip_tview_d*)NULL; vsip_scalar_d a; vsip_scalar_d chk = 0; printf("z_a_st %d; y_a_st %d; x_a_st %d\n",(int)z_a_st,(int)y_a_st,(int)x_a_st); fflush(stdout); printf("b_o_calc %u; b_o_get %u\n",(unsigned)b_o_calc,(unsigned)b_o_get); fflush(stdout); for(k = 0; k < 4; k++){ for(j = 0; j < 3; j++){ for(i = 0; i < 4; i++){ a = data_r[k][j][i]; vsip_tput_d(v,k,j,i,a); } } } printf("test tmatrixview_d\n"); printf("TMZY\n"); fflush(stdout); for(i = 0; i < 4; i++){ mview = vsip_tmatrixview_d(v,VSIP_TMZY,i); for(j = 0; j < 3; j++){ for(k = 0; k < 4; k++){ a = vsip_mget_d(mview,k,j); a -= data_r[k][j][i]; chk += a * a; } } vsip_mdestroy_d(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TMYX\n"); fflush(stdout); for(k = 0; k < 4; k++){ mview = vsip_tmatrixview_d(v,VSIP_TMYX,k); for(j = 0; j < 3; j++){ for(i = 0; i < 4; i++){ a = vsip_mget_d(mview,j,i); a -= data_r[k][j][i]; chk += a * a; } } vsip_mdestroy_d(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TMZX\n"); fflush(stdout); for(j = 0; j < 3; j++){ mview = vsip_tmatrixview_d(v,VSIP_TMZX,j); for(k = 0; k < 4; k++){ for(i = 0; i < 4; i++){ a = vsip_mget_d(mview,k,i); a -= data_r[k][j][i]; chk += a * a; } } vsip_mdestroy_d(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test tvectview_d\n"); printf("TVX \n"); fflush(stdout); for(k=0; k<4; k++){ for(j=0; j<3; j++){ vview = vsip_tvectview_d(v,VSIP_TVX,k,j); for(i=0; i<4; i++){ a = vsip_vget_d(vview,i); a -= data_r[k][j][i]; chk += a * a; } } vsip_vdestroy_d(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test tvectview_d\n"); printf("TVY \n"); fflush(stdout); for(k=0; k<4; k++){ for(i=0; i<4; i++){ vview = vsip_tvectview_d(v,VSIP_TVY,k,i); for(j=0; j<3; j++){ a = vsip_vget_d(vview,j); a -= data_r[k][j][i]; chk += a * a ; } } vsip_vdestroy_d(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TVZ \n"); fflush(stdout); for(j=0; j<3; j++){ for(i=0; i<4; i++){ vview = vsip_tvectview_d(v,VSIP_TVZ,j,i); for(k=0; k<4; k++){ a = vsip_vget_d(vview,k); a -= data_r[k][j][i]; chk += a * a; } } vsip_vdestroy_d(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test ttransview_d\n"); fflush(stdout); printf("NOP\n"); fflush(stdout); tview = vsip_ttransview_d(v,VSIP_TTRANS_NOP); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_d(tview,k,j,i); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_d(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YX\n"); fflush(stdout); tview = vsip_ttransview_d(v,VSIP_TTRANS_YX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_d(tview,k,i,j); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_d(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("ZY\n"); fflush(stdout); tview = vsip_ttransview_d(v,VSIP_TTRANS_ZY); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_d(tview,j,k,i); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_d(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("ZX\n"); fflush(stdout); tview = vsip_ttransview_d(v,VSIP_TTRANS_ZX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_d(tview,i,j,k); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_d(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YXZY\n"); fflush(stdout); tview = vsip_ttransview_d(v,VSIP_TTRANS_YXZY); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_d(tview,i,k,j); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_d(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YXZX\n"); fflush(stdout); tview = vsip_ttransview_d(v,VSIP_TTRANS_YXZX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_d(tview,j,i,k); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_d(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; vsip_tdestroy_d(v); vsip_tdestroy_d(tview_b); vsip_talldestroy_d(tview_a); } return; } <file_sep>// // jvsipFTests.swift // jvsipFTests // // Created by <NAME> on 10/2/16. // Copyright © 2016 Independent Consultant. All rights reserved. // import XCTest class jvsipFTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } func testAdd(){ let _ = vsip_init(nil) let v = vsip_vcreate_f(10, VSIP_MEM_NONE) vsip_vramp_f(0,1.0,v) vsip_vadd_f(v,v,v) for i in 0..<10{ print(vsip_vget_f(v,vsip_index(i))) } vsip_valldestroy_f(v) vsip_finalize(nil) } func testMul(){ let _ = vsip_init(nil) let v = vsip_vcreate_d(10, VSIP_MEM_NONE) vsip_vramp_d(0.0,1.0,v) vsip_vmul_d(v,v,v) for i in 0..<10{ print(vsip_vget_d(v,vsip_index(i))) } vsip_valldestroy_d(v) vsip_finalize(nil) } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mswap_d.h,v 2.0 2003/02/22 15:23:26 judd Exp $ */ #include"VU_mprintm_d.include" static void mswap_d(void){ printf("\n******\nTEST mswap_d\n"); { vsip_scalar_d data1[]= {1, 2, 3, 4, 5, 6, 7, 8, 9}; vsip_scalar_d data2[]= {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9}; vsip_mview_d *a = vsip_mbind_d( vsip_blockbind_d(data1,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_mview_d *b = vsip_mbind_d( vsip_blockbind_d(data2,9,VSIP_MEM_NONE),0,1,3,3,3); vsip_mview_d *a0 = vsip_mcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *b0 = vsip_mcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *chk = vsip_mcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_d(vsip_mgetblock_d(a),VSIP_TRUE); vsip_blockadmit_d(vsip_mgetblock_d(b),VSIP_TRUE); vsip_mcopy_d_d(a,a0); vsip_mcopy_d_d(b,b0); printf("a =\n");VU_mprintm_d("8.6",a); printf("b =\n");VU_mprintm_d("8.6",b); printf("call vsip_mswap_d(a,b)\n"); vsip_mswap_d(a,b); printf("a =\n");VU_mprintm_d("8.6",a); printf("b =\n");VU_mprintm_d("8.6",b); vsip_msub_d(a,b0,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,0,.0001,0,1,chk); if(fabs(vsip_msumval_d(chk)) > .5) printf("error in <a>\n"); else printf("<a> correct\n"); vsip_msub_d(b,a0,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,0,.0001,0,1,chk); if(fabs(vsip_msumval_d(chk)) > .5) printf("error in <b>\n"); else printf("<b> correct\n"); vsip_malldestroy_d(a); vsip_malldestroy_d(a0); vsip_malldestroy_d(b); vsip_malldestroy_d(b0); vsip_malldestroy_d(chk); } return; } <file_sep>/* Created RJudd */ /********************************************************************** // TASP VSIPL Documentation and Code includes no warranty, / // express or implied, including the warranties of merchantability / // and fitness for a particular purpose. No person or organization / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_splineattributes_d.h,v 2.1 2008/09/14 20:50:30 judd Exp $ */ #include"vsip.h" #include"VI.h" struct vsip_splineattributes_d{ vsip_scalar_d *h,*b,*u,*v,*z; int markings; }; <file_sep>/* Created RJudd */ /********************************************************************** // TASP VSIPL Documentation and Code includes no warranty, / // express or implied, including the warranties of merchantability / // and fitness for a particular purpose. No person or organization / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_spline_create_f.c,v 2.2 2009/09/12 23:15:46 judd Exp $ */ #include"vsip.h" #include"VI.h" #include"vsip_splineattributes_f.h" vsip_spline_f *vsip_spline_create_f(vsip_length N){ vsip_spline_f *spline = (vsip_spline_f*)malloc(sizeof(vsip_spline_f)); if(spline){ spline->h = (vsip_scalar_f*)malloc(sizeof(vsip_scalar_f) * N * 5); spline->markings = VSIP_VALID_STRUCTURE_OBJECT; if(spline->h){ spline->b = spline->h + N; spline->u = spline->b + N; spline->v = spline->u + N; spline->z = spline->v + N; } else { free(spline); spline = NULL; } } return spline; } <file_sep>/* Created RJudd March 18, 2012 */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"vsip.h" #include"vsip_cvviewattributes_f.h" #include"vsip_rcfirattributes_f.h" #include"vsip_vviewattributes_f.h" #include"VI_cvcopy_f_f.h" #include"VI_cvfill_f.h" static vsip_cscalar_f rcvdot_f( const vsip_vview_f* a, const vsip_cvview_f* b) { { vsip_length n = a->length; vsip_stride cbst = b->block->cstride; vsip_scalar_f *apr = (vsip_scalar_f*) ((a->block->array) + a->block->rstride * a->offset), *bpr = (vsip_scalar_f*) ((b->block->R->array) + cbst * b->offset), *bpi = (vsip_scalar_f*) ((b->block->I->array) + cbst * b->offset); vsip_stride ast = (a->block->rstride * a->stride), bst = (cbst * b->stride); vsip_cscalar_f r; r.r = 0; r.i = 0; while(n-- > 0){ r.r += *apr * *bpr; r.i += *apr * *bpi; apr += ast; bpr += bst; bpi += bst; } return r; } } int vsip_rcfirflt_f( vsip_rcfir_f *fir, const vsip_cvview_f *xc, const vsip_cvview_f *yc) { vsip_length nout,k; vsip_cvview_f xx = *(xc), yy = *(yc); vsip_vview_f H1 = *(fir->h), H2 = *(fir->h); vsip_cvview_f *x=&xx,*y=&yy; vsip_vview_f *h1=&H1,*h2=&H2; vsip_offset oinc; oinc = (vsip_offset)((vsip_stride)fir->D * x->stride); /* calculate number of terms in y */ nout = (fir->N - fir->p); nout = ((nout % fir->D) == 0) ? (nout / fir->D ) : (nout / fir->D + 1); /* do overlap section */ k = 0; x->length = fir->p + 1; h1->length = fir->s->length; h2->length = x->length; h2->offset = h1->length; while(x->length < fir->M){ vsip_cscalar_f a = rcvdot_f(h1,fir->s); vsip_cscalar_f b = rcvdot_f(h2,x); vsip_cvput_f(y,k++,vsip_cmplx_f(a.r + b.r,a.i + b.i)); x->length += fir->D; fir->s->length -= fir->D; fir->s->offset += fir->D; h1->length = fir->s->length; h2->length = x->length; h2->offset = h1->length; } x->offset += (x->length - fir->M) * x->stride; x->length = fir->M; while(k < nout){ /* do the rest of the pieces */ vsip_cvput_f(y,k++,rcvdot_f(fir->h,x)); x->offset += oinc; } { vsip_stride temp_p = (fir->p % fir->D) - (fir->N % fir->D); fir->p = ((temp_p < 0) ? (vsip_length)((vsip_stride)fir->D + temp_p) : (vsip_length)temp_p); } fir->s->offset = 0; fir->s->length = (fir->state == VSIP_STATE_SAVE) ? fir->M - 1 - fir->p : fir->M -1; x->length = fir->s->length; /* fix by JMA, 31/01/2000, incorrect offset calculation */ /* x->offset = xc->length - fir->s->length; */ x->offset = xc->offset + (xc->length - fir->s->length) * xc->stride; if((fir->s->length > 0) && (fir->state == VSIP_STATE_SAVE)) VI_cvcopy_f_f(x,fir->s); if(fir->state == VSIP_STATE_NO_SAVE) { VI_cvfill_f(vsip_cmplx_f((vsip_scalar_f)0,(vsip_scalar_f)0),fir->s); fir->p = 0; } return (int) k; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsdiv_d.h,v 2.0 2003/02/22 15:23:30 judd Exp $ */ #include"VU_vprintm_d.include" static void vsdiv_d(void){ printf("\n*******\nTEST vsdiv_d\n\n"); { vsip_scalar_d data[] = {.5, 1.0, 1.5, 2.0, 2.5, 3.0}; vsip_scalar_d beta = 10.5; vsip_scalar_d ans[] = {0.0476, 0.0952, 0.1429, 0.1905, 0.2381, 0.2857}; vsip_block_d *blockn = vsip_blockbind_d(data,6,VSIP_MEM_NONE); vsip_block_d *ans_block = vsip_blockbind_d(ans,6,VSIP_MEM_NONE); vsip_vview_d *a = vsip_vbind_d(blockn,0,1,6); vsip_vview_d *ansv = vsip_vbind_d(ans_block,0,1,6); vsip_vview_d *b = vsip_vcreate_d(18,VSIP_MEM_NONE); vsip_vview_d *c = vsip_vcreate_d(18,VSIP_MEM_NONE); vsip_vview_d *d = vsip_vcreate_d(6,VSIP_MEM_NONE); vsip_vview_d *chk = vsip_vcreate_d(6,VSIP_MEM_NONE); vsip_vputlength_d(b,6); vsip_vputstride_d(b,2); vsip_vputlength_d(c,6); vsip_vputstride_d(c,3); vsip_blockadmit_d(blockn,VSIP_TRUE); vsip_blockadmit_d(ans_block,VSIP_TRUE); vsip_vcopy_d_d(a,b); vsip_vcopy_d_d(a,c); printf("test out of place, compact, user \"a\", vsipl \"b\"\n"); vsip_vsdiv_d(a,beta,d); printf("vsdiv_d(a,beta,b)\n vector a\n");VU_vprintm_d("8.6",a); printf("beta = %f \n",beta); printf("vector b\n");VU_vprintm_d("8.6",d); printf("expected answer to 4 decimal digits\n");VU_vprintm_d("8.4",ansv); vsip_vsub_d(d,ansv,chk); vsip_vmag_d(chk,chk); vsip_vclip_d(chk,.0001,.0001,0,1,chk); if(vsip_vsumval_d(chk) > .5) printf(" vsdiv_d in error\n"); else printf("vsdiv_d correct to 4 decimal digits\n"); printf("\n"); vsip_vsdiv_d(b,beta,b); vsip_vsub_d(b,ansv,chk); vsip_vmag_d(chk,chk); vsip_vclip_d(chk,.0001,.0001,0,1,chk); if(vsip_vsumval_d(chk) > .5) printf(" vsdiv_d in error for in place, stride 2\n"); else printf("vsdiv_d correct to 4 decimal digits for in place, stride 2\n"); printf("\n"); /* check with a stride 1, b stride 3 */ vsip_vfill_d(0,b); vsip_vsdiv_d(c,beta,b); vsip_vsub_d(b,ansv,chk); vsip_vmag_d(chk,chk); vsip_vclip_d(chk,.0001,.0001,0,1,chk); if(vsip_vsumval_d(chk) > .5) printf(" vsdiv_d in error for strdie\n"); else { printf("vsdiv_d correct to 4 decimal digits for\n"); printf("input vsipl vector of stride 2, output vsipl vector of stride 3\n"); } vsip_valldestroy_d(a); vsip_valldestroy_d(b); vsip_valldestroy_d(c); vsip_valldestroy_d(d); vsip_valldestroy_d(chk); vsip_valldestroy_d(ansv); } return; } <file_sep>/* Created <NAME> March 11, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cmprod_d.c,v 2.2 2006/05/07 15:56:02 judd Exp $ */ /* Remove Development Mode RJudd Sept 00 */ #include"vsip.h" #include"VI.h" #include"vsip_cmviewattributes_d.h" #include"vsip_cvviewattributes_d.h" #include"VI_cmfill_d.h" /* note that matrix products may not be done in place */ void (vsip_cmprod_d)( const vsip_cmview_d* a, const vsip_cmview_d* b, const vsip_cmview_d* c) { /* Note that c => column major, r => row major */ /* Below decide input matrix majors ccc => 0 ccr=> 1, crc => 2, etc to rrr => 7 */ /* the resulting method is used to calculate */ unsigned method = (unsigned)(c->row_stride <= c->col_stride) + (unsigned)(b->row_stride <= b->col_stride) * 2 + (unsigned)(a->row_stride <= a->col_stride) * 4; /* get the stride info */ vsip_stride a_st_r = a->row_stride * a->block->cstride, a_st_c = a->col_stride * a->block->cstride, b_st_r = b->row_stride * b->block->cstride, b_st_c = b->col_stride * b->block->cstride, c_st_r = c->row_stride * c->block->cstride, c_st_c = c->col_stride * c->block->cstride; /* get the length info */ vsip_length a_c_l = a->col_length, /* i_size */ c_r_l = c->row_length, /* j_size */ a_r_l = a->row_length; /* k_size */ /* define some scalars used in the calculations below */ vsip_cscalar_d a_scalar, b_scalar, temp = vsip_cmplx_d(0.0f,0.0f); /* get the pointers to the input and output data spaces */ vsip_scalar_d *ap_r = (a->block->R->array) + a->offset * a->block->cstride, *ap_i = (a->block->I->array) + a->offset * a->block->cstride, *bp_r = (b->block->R->array) + b->offset * b->block->cstride, *bp_i = (b->block->I->array) + b->offset * b->block->cstride, *cp_r = (c->block->R->array) + c->offset * c->block->cstride, *cp_i = (c->block->I->array) + c->offset * c->block->cstride; /* some additional pointers to store initial data */ vsip_scalar_d *ap0_r = ap_r, *ap0_i = ap_i, *bp0_r = bp_r, *bp0_i = bp_i, *cp0_r = cp_r, *cp0_i = cp_i; vsip_scalar_d *bp1_r = bp_r, *bp1_i = bp_i; /* initialize output matrix to zero */ VI_cmfill_d(temp,c); /* initilize output matrix to zero */ /* select multiply routine bassed on majors of input matrices */ switch(method){ case 0 : { /* ccc */ vsip_scalar_d *ap_ik_r, *ap_0k_r = ap0_r, *ap_ik_i, *ap_0k_i = ap0_i; vsip_scalar_d *bp_kj_r, *bp_0j_r = bp0_r, *bp_kj_i, *bp_0j_i = bp0_i; vsip_scalar_d *cp_ij_r, *cp_0j_r = cp0_r, *cp_ij_i, *cp_0j_i = cp0_i; while(c_r_l-- > 0){ /* j */ cp_ij_r = cp_0j_r; cp_ij_i = cp_0j_i; bp_kj_r = bp_0j_r; bp_kj_i = bp_0j_i; while(a_r_l-- > 0){ /* k */ b_scalar.r = *bp_kj_r; b_scalar.i = *bp_kj_i; bp_kj_r += b_st_c; bp_kj_i += b_st_c; ap_ik_r = ap_0k_r; ap_ik_i = ap_0k_i; while(a_c_l-- > 0){ /* i */ *cp_ij_r = *ap_ik_r * b_scalar.r - *ap_ik_i * b_scalar.i + *cp_ij_r; *cp_ij_i = *ap_ik_r * b_scalar.i + *ap_ik_i * b_scalar.r + *cp_ij_i; cp_ij_r += c_st_c; cp_ij_i += c_st_c; ap_ik_r += a_st_c; ap_ik_i += a_st_c; } a_c_l = a->col_length; ap_0k_r += a_st_r; ap_0k_i += a_st_r; cp_ij_r = cp_0j_r; cp_ij_i = cp_0j_i; } a_r_l = a->row_length; cp_0j_r += c_st_r; cp_0j_i += c_st_r; bp_0j_r += b_st_r; bp_0j_i += b_st_r; ap_0k_r = ap0_r; ap_0k_i = ap0_i; } } break; case 1 : { /* ccr */ vsip_scalar_d *ap_ik_r, *ap_i0_r = ap0_r, *ap_ik_i, *ap_i0_i = ap0_i; vsip_scalar_d *bp_kj_r, *bp_0j_r, *bp_kj_i, *bp_0j_i; vsip_scalar_d *cp_ij_r, *cp_i0_r = cp0_r, *cp_ij_i, *cp_i0_i = cp0_i; while(a_c_l-- > 0){ /* i */ cp_ij_r = cp_i0_r; cp_ij_i = cp_i0_i; bp_0j_r = bp0_r; bp_0j_i = bp0_i; while(c_r_l-- > 0){ /* j */ ap_ik_r = ap_i0_r; ap_ik_i = ap_i0_i; temp = vsip_cmplx_d(0.0f,0.0f); bp_kj_r = bp_0j_r; bp_kj_i = bp_0j_i; while(a_r_l-- > 0){ /* k */ temp.r += *ap_ik_r * *bp_kj_r - *ap_ik_i * *bp_kj_i; temp.i += *ap_ik_r * *bp_kj_i + *ap_ik_i * *bp_kj_r; ap_ik_r += a_st_r; ap_ik_i += a_st_r; bp_kj_r += b_st_c; bp_kj_i += b_st_c; } a_r_l = a->row_length; *cp_ij_r = temp.r; *cp_ij_i = temp.i; cp_ij_r += c_st_r; cp_ij_i += c_st_r; bp_0j_r += b_st_r; bp_0j_i += b_st_r; } c_r_l = c->row_length; cp_i0_r += c_st_c; cp_i0_i += c_st_c; ap_i0_r += a_st_c; ap_i0_i += a_st_c; } } break; case 2 : { /* crc */ vsip_scalar_d *ap_ik_r, *ap_0k_r = ap0_r, *ap_ik_i, *ap_0k_i = ap0_i; vsip_scalar_d *bp_kj_r, *bp_0j_r = bp0_r, *bp_kj_i, *bp_0j_i = bp0_i; vsip_scalar_d *cp_ij_r, *cp_0j_r = cp0_r, *cp_ij_i, *cp_0j_i = cp0_i; while(c_r_l-- > 0){ /* j */ bp_kj_r = bp_0j_r; bp_kj_i = bp_0j_i; while(a_r_l-- > 0){ /* k */ b_scalar.r = *bp_kj_r; b_scalar.i = *bp_kj_i; ap_ik_r = ap_0k_r; ap_ik_i = ap_0k_i; cp_ij_r = cp_0j_r; cp_ij_i = cp_0j_i; while(a_c_l-- > 0){ /* i */ *cp_ij_r += *ap_ik_r * b_scalar.r - *ap_ik_i * b_scalar.i; *cp_ij_i += *ap_ik_i * b_scalar.r + *ap_ik_r * b_scalar.i; cp_ij_r += c_st_c; cp_ij_i += c_st_c; ap_ik_r += a_st_c; ap_ik_i += a_st_c; } a_c_l = a->col_length; ap_0k_r += a_st_r; ap_0k_i += a_st_r; bp_kj_r += b_st_c; bp_kj_i += b_st_c; } a_r_l = a->row_length; cp_0j_r += c_st_r; cp_0j_i += c_st_r; bp_0j_r += b_st_r; bp_0j_i += b_st_r; ap_0k_r = ap0_r; ap_0k_i = ap0_i; } } break; case 3 : { /* crr */ vsip_scalar_d *ap_ik_r, *ap_i0_r = ap0_r, *ap_ik_i, *ap_i0_i = ap0_i; vsip_scalar_d *bp_kj_r, *bp_k0_r = bp0_r, *bp_kj_i, *bp_k0_i = bp0_i; vsip_scalar_d *cp_ij_r, *cp_i0_r = cp0_r, *cp_ij_i, *cp_i0_i = cp0_i; while(a_c_l-- > 0){ /* i */ ap_ik_r = ap_i0_r; ap_ik_i = ap_i0_i; while(a_r_l-- > 0){ /* k */ a_scalar.r = *ap_ik_r; a_scalar.i = *ap_ik_i; ap_ik_r += a_st_r; ap_ik_i += a_st_r; bp_kj_r = bp_k0_r; bp_kj_i = bp_k0_i; cp_ij_r = cp_i0_r; cp_ij_i = cp_i0_i; while(c_r_l-- > 0){ /* j */ *cp_ij_r = *bp_kj_r * a_scalar.r - *bp_kj_i * a_scalar.i + *cp_ij_r; *cp_ij_i = *bp_kj_i * a_scalar.r + *bp_kj_r * a_scalar.i + *cp_ij_i; cp_ij_r += c_st_r; cp_ij_i += c_st_r; bp_kj_r += b_st_r; bp_kj_i += b_st_r; } c_r_l = c->row_length; bp_k0_r += b_st_c; bp_k0_i += b_st_c; }a_r_l = a->row_length; bp_k0_r = bp0_r; bp_k0_i = bp0_i; cp_i0_r += c_st_c; cp_i0_i += c_st_c; ap_i0_r += a_st_c; ap_i0_i += a_st_c; } } break; case 4 : { /* rcc */ while(a_c_l-- > 0){ while(c_r_l-- > 0){ temp = vsip_cmplx_d(0.0f,0.0f); while(a_r_l-- > 0){ temp.r += *ap_r * *bp_r - *ap_i * *bp_i; temp.i += *ap_r * *bp_i + *ap_i * *bp_r; ap_r += a_st_r; ap_i += a_st_r; bp_r += b_st_c; bp_i += b_st_c; } *cp_r = temp.r; *cp_i = temp.i; cp_r += c_st_r; cp_i += c_st_r; ap_r = ap0_r; ap_i = ap0_i; bp0_r += b_st_r; bp0_i += b_st_r; bp_r = bp0_r; bp_i = bp0_i; a_r_l = a->row_length; } ap0_r += a_st_c; ap0_i += a_st_c; ap_r = ap0_r; ap_i = ap0_i; bp0_r = bp1_r; bp0_i = bp1_i; bp_r = bp0_r; bp_i = bp0_i; cp0_r += c_st_c; cp0_i += c_st_c; cp_r = cp0_r; cp_i = cp0_i; c_r_l = c->row_length; } } break; case 5 : { /* rcr */ while(a_c_l-- > 0){ while(c_r_l-- > 0){ temp = vsip_cmplx_d(0.0f,0.0f); while(a_r_l-- > 0){ temp.r += *ap_r * *bp_r - *ap_i * *bp_i; temp.i += *ap_r * *bp_i + *ap_i * *bp_r; ap_r += a_st_r; ap_i += a_st_r; bp_r += b_st_c; bp_i += b_st_c; } *cp_r = temp.r; *cp_i = temp.i; cp_r += c_st_r; cp_i += c_st_r; ap_r = ap0_r; ap_i = ap0_i; bp0_r += b_st_r; bp_r = bp0_r; bp0_i += b_st_r; bp_i = bp0_i; a_r_l = a->row_length; } ap0_r += a_st_c; ap_r = ap0_r; ap0_i += a_st_c; ap_i = ap0_i; bp0_r = bp1_r; bp_r = bp0_r; bp0_i = bp1_i; bp_i = bp0_i; cp0_r += c_st_c; cp_r = cp0_r; cp0_i += c_st_c; cp_i = cp0_i; c_r_l = c->row_length; } } break; case 6 : { /* rrc */ vsip_scalar_d *ap_ik_r, *ap_i0_r, *ap_ik_i, *ap_i0_i; vsip_scalar_d *bp_kj_r, *bp_0j_r = bp0_r, *bp_kj_i, *bp_0j_i = bp0_i; vsip_scalar_d *cp_ij_r, *cp_0j_r = cp0_r, *cp_ij_i, *cp_0j_i = cp0_i; /* jik */ while(c_r_l-- > 0){ /* j */ cp_ij_r = cp_0j_r; cp_ij_i = cp_0j_i; ap_i0_r = ap0_r; ap_i0_i = ap0_i; while(a_c_l-- > 0){ /* i */ temp = vsip_cmplx_d(0.0f, 0.0f); ap_ik_r = ap_i0_r; ap_ik_i = ap_i0_i; bp_kj_r = bp_0j_r; bp_kj_i = bp_0j_i; while(a_r_l-- > 0){ /* k */ temp.r += *ap_ik_r * *bp_kj_r - *ap_ik_i * *bp_kj_i;; temp.i += *ap_ik_r * *bp_kj_i + *ap_ik_i * *bp_kj_r; ap_ik_r += a_st_r; ap_ik_i += a_st_r; bp_kj_r += b_st_c; bp_kj_i += b_st_c; } a_r_l = a->row_length; *cp_ij_r = temp.r; *cp_ij_i = temp.i; cp_ij_r +=c_st_c; cp_ij_i +=c_st_c; ap_i0_r += a_st_c; ap_i0_i += a_st_c; } a_c_l = a->col_length; cp_0j_r += c_st_r; cp_0j_i += c_st_r; bp_0j_r += b_st_r; bp_0j_i += b_st_r; } } break; case 7 : { /* rrr */ vsip_scalar_d *ap_ik_r, *ap_i0_r = ap0_r, *ap_ik_i, *ap_i0_i = ap0_i; vsip_scalar_d *bp_kj_r, *bp_k0_r = bp0_r, *bp_kj_i, *bp_k0_i = bp0_i; vsip_scalar_d *cp_ij_r, *cp_i0_r = cp0_r, *cp_ij_i, *cp_i0_i = cp0_i; while(a_c_l-- > 0){ /* i */ ap_ik_r = ap_i0_r; ap_ik_i = ap_i0_i; while(a_r_l-- > 0){ /* k */ a_scalar.r = *ap_ik_r; a_scalar.i = *ap_ik_i; ap_ik_r += a_st_r; ap_ik_i += a_st_r; bp_kj_r = bp_k0_r; bp_kj_i = bp_k0_i; cp_ij_r = cp_i0_r; cp_ij_i = cp_i0_i; while(c_r_l-- > 0){ /* j */ *cp_ij_r = *bp_kj_r * a_scalar.r - *bp_kj_i * a_scalar.i + *cp_ij_r; *cp_ij_i = *bp_kj_r * a_scalar.i + *bp_kj_i * a_scalar.r + *cp_ij_i; cp_ij_r += c_st_r; cp_ij_i += c_st_r; bp_kj_r += b_st_r; bp_kj_i += b_st_r; } c_r_l = c->row_length; bp_k0_r += b_st_c; bp_k0_i += b_st_c; }a_r_l = a->row_length; bp_k0_r = bp0_r; bp_k0_i = bp0_i; cp_i0_r += c_st_c; cp_i0_i += c_st_c; ap_i0_r += a_st_c; ap_i0_i += a_st_c; } } } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_attrib_uc.h,v 2.0 2003/02/22 15:23:33 judd Exp $ */ static void get_put_attrib_uc(void){ printf("********\nTEST get_put_attrib_uc\n"); { vsip_offset ivo = 3; vsip_stride ivs = 2; vsip_length ivl = 3; vsip_offset jvo = 2; vsip_stride jvs = 3; vsip_length jvl = 5; vsip_stride irs = 1, ics = 3; vsip_length irl = 2, icl = 3; vsip_stride jrs = 5, jcs = 2; vsip_length jrl = 5, jcl = 2; vsip_stride ixs = 2, iys = 4, izs = 14; vsip_length ixl = 2, iyl = 3, izl = 4; vsip_stride jxs = 4, jys = 14, jzs = 2; vsip_length jxl = 3, jyl = 4, jzl = 2; vsip_block_uc *b = vsip_blockcreate_uc(80,VSIP_MEM_NONE); vsip_vview_uc *v = vsip_vbind_uc(b,ivo,ivs,ivl); vsip_mview_uc *m = vsip_mbind_uc(b,ivo,ics,icl,irs,irl); vsip_tview_uc *t = vsip_tbind_uc(b,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_vattr_uc attr; vsip_mattr_uc mattr; vsip_tattr_uc tattr; printf("test vgetattrib_uc\n"); fflush(stdout); { vsip_vgetattrib_uc(v,&attr); (attr.offset == ivo) ? printf("offset correct\n") : printf("offset error \n"); (attr.stride == ivs) ? printf("stride correct\n") : printf("stride error \n"); (attr.length == ivl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputattrib_uc\n"); fflush(stdout); { attr.offset = jvo; attr.stride = jvs; attr.length = jvl; vsip_vputattrib_uc(v,&attr); vsip_vgetattrib_uc(v,&attr); (attr.offset == jvo) ? printf("offset correct\n") : printf("offset error \n"); (attr.stride == jvs) ? printf("stride correct\n") : printf("stride error \n"); (attr.length == jvl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /**************************************************************************/ printf("test mgetattrib_uc\n"); fflush(stdout); { vsip_mgetattrib_uc(m,&mattr); (mattr.offset == ivo) ? printf("offset correct\n") : printf("offset error \n"); (mattr.col_stride == ics) ? printf("col_stride correct\n") : printf("col_stride error \n"); (mattr.row_stride == irs) ? printf("row_stride correct\n") : printf("row_stride error \n"); (mattr.col_length == icl) ? printf("col_length correct\n") : printf("col_length error \n"); (mattr.row_length == irl) ? printf("row_length correct\n") : printf("row_length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputattrib_uc\n"); fflush(stdout); { mattr.offset = jvo; mattr.col_stride = jcs; mattr.col_length = jcl; mattr.row_stride = jrs; mattr.row_length = jrl; vsip_mputattrib_uc(m,&mattr); vsip_mgetattrib_uc(m,&mattr); (mattr.offset == jvo) ? printf("offset correct\n") : printf("offset error \n"); (mattr.col_stride == jcs) ? printf("col_stride correct\n") : printf("col_stride error \n"); (mattr.col_length == jcl) ? printf("col_length correct\n") : printf("col_length error \n"); (mattr.row_stride == jrs) ? printf("row_stride correct\n") : printf("row_stride error \n"); (mattr.row_length == jrl) ? printf("row_length correct\n") : printf("row_length error \n"); fflush(stdout); } /**************************************************************************/ printf("test tgetattrib_uc\n"); fflush(stdout); { vsip_tgetattrib_uc(t,&tattr); (tattr.offset == ivo) ? printf("offset correct\n") : printf("offset error \n"); (tattr.z_stride == izs) ? printf("z_stride correct\n") : printf("z_stride error \n"); (tattr.z_length == izl) ? printf("z_length correct\n") : printf("z_length error \n"); (tattr.y_stride == iys) ? printf("y_stride correct\n") : printf("y_stride error \n"); (tattr.y_length == iyl) ? printf("y_length correct\n") : printf("y_length error \n"); (tattr.x_stride == ixs) ? printf("x_stride correct\n") : printf("x_stride error \n"); (tattr.x_length == ixl) ? printf("x_length correct\n") : printf("x_length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputattrib_uc\n"); fflush(stdout); { tattr.offset = jvo; tattr.z_stride = jzs; tattr.z_length = jzl; tattr.y_stride = jys; tattr.y_length = jyl; tattr.x_stride = jxs; tattr.x_length = jxl; vsip_tputattrib_uc(t,&tattr); vsip_tgetattrib_uc(t,&tattr); (tattr.offset == jvo) ? printf("offset correct\n") : printf("offset error \n"); (tattr.z_stride == jzs) ? printf("z_stride correct\n") : printf("z_stride error \n"); (tattr.z_length == jzl) ? printf("z_length correct\n") : printf("z_length error \n"); (tattr.y_stride == jys) ? printf("y_stride correct\n") : printf("y_stride error \n"); (tattr.y_length == jyl) ? printf("y_length correct\n") : printf("y_length error \n"); (tattr.x_stride == jxs) ? printf("x_stride correct\n") : printf("x_stride error \n"); (tattr.x_length == jxl) ? printf("x_length correct\n") : printf("x_length error \n"); fflush(stdout); } vsip_vdestroy_uc(v); vsip_mdestroy_uc(m); vsip_talldestroy_uc(t); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vfirst_vi.h,v 2.1 2007/04/18 17:05:54 judd Exp $ */ #include"VU_vprintm_vi.include" #include"VU_vprintm_i.include" static vsip_bool first_test_vi( vsip_scalar_vi a, vsip_scalar_vi b) { if(a>b){ return VSIP_TRUE; } else { return VSIP_FALSE; } } static void vfirst_vi(void){ printf("********\nTEST vfirst_vi\n"); { vsip_scalar_vi data1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9}; vsip_scalar_vi data2[] = { 0, 2, 4, 4, 5, 7, 7, 8, 9}; vsip_scalar_i ans_data[] = {2,2,2,5,5,5,9,9,9}; vsip_block_vi *block_a = vsip_blockbind_vi(data1,9,VSIP_MEM_NONE); vsip_block_vi *block_b = vsip_blockbind_vi(data2,9,VSIP_MEM_NONE); vsip_block_i *block_ans = vsip_blockbind_i(ans_data,9,VSIP_MEM_NONE); vsip_vview_vi *a = vsip_vbind_vi(block_a,0,1,9); vsip_vview_vi *b = vsip_vbind_vi(block_b,0,1,9); vsip_vview_i *ans = vsip_vbind_i(block_ans,0,1,9); vsip_index j=0; vsip_vview_i *r = vsip_vcreate_i(9,VSIP_MEM_NONE); vsip_vview_i *chk = vsip_vcreate_i(9,VSIP_MEM_NONE); vsip_blockadmit_vi(block_a,VSIP_TRUE); vsip_blockadmit_vi(block_b,VSIP_TRUE); vsip_blockadmit_i(block_ans,VSIP_TRUE); printf("vsip_vfirst_vi(index,function*,b,a)"); printf("If index > a,b length then return index\n"); if(vsip_vfirst_vi(10,first_test_vi,b,a) == (vsip_index)10){ printf("correct\n"); fflush(stdout); } else { printf("error \n"); fflush(stdout); } printf("check for correct index, if not true return length \n"); for(j=0; j<9; j++){ vsip_vput_i(r,j,(vsip_scalar_i)vsip_vfirst_vi(j,first_test_vi,b,a)); } printf("vector a\n");VU_vprintm_vi("3",a); printf("vector b\n");VU_vprintm_vi("3",b); printf("vector r\n");VU_vprintm_i("3",r); printf("right answer\n");VU_vprintm_i("3",ans); vsip_vsub_i(r,ans,chk); vsip_vmul_i(chk,chk,chk); /* make sure we don't get zero by mistake */ if(vsip_vsumval_i(chk) > 0) printf("error\n"); else printf("correct\n"); } return; } <file_sep>#include<vsip.h> #include"exUtils.h" /* define parameters */ #define D 1.5 /* Sensor Spacing Meters */ #define Fs 1000.0 /* Sample Frequency (Hz) */ #define F0 450.0 /* Target Frequency */ #define F1 300.0 /* Target Frequency */ #define F2 150.0 /* Target Frequency */ #define F3 50.0 /* Target Frequency */ #define Theta_o 40 /* Target Direction */ #define Ns 512 /* samples in a time series */ #define N 512 /* length of sampled time series (samples) */ #define Nn 1024 /* length of (simulated) noise series */ #define Mp 128 /* number of sensors in linear array */ #define c 1500.0 /* Propagation Speed (Meters/Second) */ /*Calculate input data*/ int main(){ vsip_fftm_d *rcfftmop_obj = vsip_rcfftmop_create_d(Mp,Ns,1,VSIP_ROW,0,0); vsip_fftm_d *ccfftmip_obj = vsip_ccfftmip_create_d(Mp,Ns/2 + 1,VSIP_FFT_FWD,1,VSIP_COL,0,0); vsip_vview_d* windowt = vsip_vcreate_hanning_d(Ns,VSIP_MEM_NONE); vsip_vview_d* windowp = vsip_vcreate_hanning_d(Mp,VSIP_MEM_NONE); vsip_scalar_d alpha = (vsip_scalar_d)(D * Fs) / c ;/*Array Constant*/ vsip_mview_d *data = noiseGen(alpha,Mp,Nn,Ns); vsip_cmview_d *gram_data = vsip_cmcreate_d(Mp,Ns/2 + 1,VSIP_COL,0); vsip_mview_d *gram; void* targets[3]; vsip_vview_d*freq;vsip_vview_vi *bearing;vsip_vview_d *scale; targets[0] = (void*)vsip_vcreate_d(4,VSIP_MEM_NONE);/* freq */ targets[1] = (void*)vsip_vcreate_vi(4,VSIP_MEM_NONE);/* bearng */ targets[2] = (void*)vsip_vcreate_d(4,VSIP_MEM_NONE);/*scalae*/ freq =(vsip_vview_d*)targets[0]; bearing = (vsip_vview_vi*)targets[1]; scale = (vsip_vview_d*)targets[2]; vsip_vfill_vi(Theta_o,bearing); vsip_vput_d(scale,0,1.5);vsip_vput_d(scale,1,2.0);vsip_vput_d(scale,2,2.0);vsip_vput_d(scale,3,3.0); vsip_vput_d(freq,0,F0);vsip_vput_d(freq,1,F1);vsip_vput_d(freq,2,F2);vsip_vput_d(freq,3,F3); narrowBandGen(data,alpha,targets,Fs); /*beamform data and output in a form sutiable for display*/ vsip_vmmul_d(windowt,data,VSIP_ROW,data); vsip_vmmul_d(windowp,data,VSIP_COL,data) ; vsip_rcfftmop_d(rcfftmop_obj,data,gram_data); vsip_ccfftmip_d(ccfftmip_obj,gram_data); gram = cmscale_d(gram_data); /*save data */ mview_store_d(gram,"gram_output"); vsip_malldestroy_d(gram); vsip_cmalldestroy_d(gram_data); vsip_malldestroy_d(data); vsip_valldestroy_d(windowt); vsip_valldestroy_d(windowp); vsip_fftm_destroy_d(rcfftmop_obj); vsip_fftm_destroy_d(ccfftmip_obj); } <file_sep> #include"param.h" /* function to get us to a parameter */ static int scan_achar(FILE* fptr){ int achar = 0; while((achar != EOF) && (achar != '*')) achar = fgetc(fptr); return achar; } /* check to see if we have a good input */ static int check_achar(int achar){ if(achar == EOF){ printf("Premature end of data in parameter file"); exit(13); } return achar; } /* read the parameter file and put the data in the parameter object */ int param_read( char* param_file_name, param_obj *obj) { int retval = 0; int achar; FILE* fptr = fopen(param_file_name,"r"); if(fptr){ /* get the propagation speed */ achar = check_achar(scan_achar(fptr)); /* go to input */ fscanf(fptr,"%lf",&obj->c); /* get the sample rate */ achar = check_achar(scan_achar(fptr)); /* go to input */ fscanf(fptr,"%lf",&obj->Fs); /* get the time series length */ achar = check_achar(scan_achar(fptr)); /* go to input */ fscanf(fptr,"%d",&obj->Nts); /* get the sensor spacing */ achar = check_achar(scan_achar(fptr)); /* go to input */ fscanf(fptr,"%lf",&obj->Dsens); /* get the number of sensors */ achar = check_achar(scan_achar(fptr)); /* go to input */ fscanf(fptr,"%d",&obj->Nsens); /* get the number of averages */ achar = check_achar(scan_achar(fptr)); /* go to input */ fscanf(fptr,"%d",&obj->Navg); /* get the number of narrow band simualted tones */ achar = check_achar(scan_achar(fptr)); /* go to input */ fscanf(fptr,"%d",&obj->Nsim_freqs); obj->sim_freqs = (double*)malloc(2 * obj->Nsim_freqs * sizeof(double)); if(obj->sim_freqs){ int i; obj->sim_bearings = obj->sim_freqs + obj->Nsim_freqs; for(i=0; i<obj->Nsim_freqs; i++){ achar = check_achar(scan_achar(fptr)); /* go to input */ fscanf(fptr,"%lf",&(obj->sim_freqs[i])); } for(i=0; i<obj->Nsim_freqs; i++){ achar = check_achar(scan_achar(fptr)); /* go to input */ fscanf(fptr,"%lf",&(obj->sim_bearings[i])); } } else { printf("Malloc failure\n"); retval = 1; } achar = check_achar(scan_achar(fptr)); /* go to input */ fscanf(fptr,"%d",&obj->Nsim_noise); } else { fprintf(stderr,"File open error in param_read \n"); fflush(stdout); retval = 1; } return retval; } void param_free(param_obj* obj){ if(obj->sim_freqs) free(obj->sim_freqs); } void param_log(param_obj* obj){ int i; printf("c: %f\n",(float)obj->c); printf("Fs: %f\n",(float)obj->Fs); printf("Nts: %d\n",(int)obj->Nts); printf("Dsens: %f\n",(float)obj->Dsens); printf("Nsens: %d\n",(int)obj->Nsens); printf("Navg: %d\n",(int)obj->Navg); printf("Nsim_noise %d\n",(int)obj->Nsim_noise); printf("Nsim_freqs %d\n",(int)obj->Nsim_freqs); for(i=0; i<obj->Nsim_freqs; i++) printf("Narrow Band Signal %d: %fHz at %f deg\n", i,(float)obj->sim_freqs[i],(float)obj->sim_bearings[i]); } <file_sep>/* Created RJudd March 17, 2012 */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #ifndef _vsip_rcfirattributes_f_h #define _vsip_rcfirattributes_f_h #include"VI.h" struct vsip_rcfirattributes_f{ vsip_vview_f *h; vsip_cvview_f *s; vsip_length N; vsip_length M; vsip_length p; vsip_length D; int ntimes; vsip_symmetry symm; vsip_alg_hint hint; vsip_obj_state state; }; #endif /* _vsip_rcfirattributes_f_h */ <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmswap_d.h,v 2.0 2003/02/22 15:23:21 judd Exp $ */ #include"VU_cmprintm_d.include" static void cmswap_d(void){ printf("\n*******\nTEST cmswap_d\n\n"); { vsip_scalar_d data1_r[] = { -1, -2, 3, 4, -5, -6}; vsip_scalar_d data1_i[] = { 1, 2, -3, -4, 5, 6}; vsip_scalar_d data2 [] = { 10,20, 11,21, 12,22, 13,23, 14,24, 15,25}; vsip_cblock_d *block1 = vsip_cblockbind_d(data1_r,data1_i,6,VSIP_MEM_NONE); vsip_cblock_d *block2 = vsip_cblockbind_d(data2,NDPTR_d,6,VSIP_MEM_NONE); vsip_cmview_d *a = vsip_cmbind_d(block1,0,2,3,1,2); vsip_cmview_d *b = vsip_cmbind_d(block2,0,2,3,1,2); vsip_cmview_d *a1 = vsip_cmcreate_d(3,2,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *b1 = vsip_cmcreate_d(3,2,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *chk = vsip_cmcreate_d(3,2,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *chk_r = vsip_mrealview_d(chk); vsip_cblockadmit_d(block1,VSIP_TRUE); vsip_cblockadmit_d(block2,VSIP_TRUE); vsip_cmcopy_d_d(a,a1); vsip_cmcopy_d_d(b,b1); printf("matrix a\n");VU_cmprintm_d("8.6",a); printf("matrix b\n");VU_cmprintm_d("8.6",b); printf("vsip_cmswap_d(a,b)\n"); vsip_cmswap_d(a,b); printf("matrix a\n");VU_cmprintm_d("8.6",a); printf("matrix b\n");VU_cmprintm_d("8.6",b); vsip_cmsub_d(a,b1,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error in matrix <a>\n"); else printf("<a> correct\n"); vsip_cmsub_d(b,a1,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error in matrix <b>\n"); else printf("<b> correct\n"); vsip_cmalldestroy_d(a); vsip_cmalldestroy_d(b); vsip_cmalldestroy_d(a1); vsip_cmalldestroy_d(b1); vsip_mdestroy_d(chk_r); vsip_cmalldestroy_d(chk); } return; } <file_sep>/* Created RJudd September 16, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cblockrelease_f.c,v 2.1 2006/06/08 22:19:26 judd Exp $ */ #include"vsip.h" #include"vsip_cblockattributes_f.h" void (vsip_cblockrelease_f)( vsip_cblock_f* b, vsip_scalar_bl update, vsip_scalar_f* *Rp, vsip_scalar_f* *Ip) { if(b != (vsip_cblock_f*)NULL) b->update = update; #if defined(VSIP_DEFAULT_SPLIT) #include"VI_cblockrelease_f_ds.h" #elif defined(VSIP_ALWAYS_SPLIT) #include"VI_cblockrelease_f_as.h" #elif defined(VSIP_ALWAYS_INTERLEAVED) #include"VI_cblockrelease_f_ai.h" #else #include"VI_cblockrelease_f_di.h" #endif return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mexpoavg_d.h,v 2.0 2003/02/22 15:23:24 judd Exp $ */ #include"VU_mprintm_d.include" static void mexpoavg_d(void){ printf("\n******\nTEST mexpoavg_d\n"); { vsip_scalar_d alpha = (vsip_scalar_d)(1.0/3.0); vsip_scalar_d data1[]= {1,.1, 2,.2, 3,.3, 4,-.1, 5,-.3, 6,-.4, 7,.8, 8,.9, 9,-1}; vsip_scalar_d data2[]= {2,.1, 3,.2, 4,.3, 6,-.1, 8,-.3, 6,-.6, 7,.7, 8,.5, 1,-1.3}; vsip_scalar_d data3[]= {0,.2, 3,.5, 3,.1, 2,-.1, 5,-.3, 6,-.4, 7,.8, 8,.9, 9,-1.5}; vsip_mview_d *ans = vsip_mcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *m1 = vsip_mbind_d( vsip_blockbind_d(data1,18,VSIP_MEM_NONE),0,3,3,1,3); vsip_mview_d *m2 = vsip_mbind_d( vsip_blockbind_d(data2,18,VSIP_MEM_NONE),1,4,3,1,3); vsip_mview_d *m3 = vsip_mbind_d( vsip_blockbind_d(data3,18,VSIP_MEM_NONE),3,1,3,3,3); vsip_mview_d *c = vsip_mcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *chk = vsip_mcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_d(vsip_mgetblock_d(m1),VSIP_TRUE); vsip_blockadmit_d(vsip_mgetblock_d(m2),VSIP_TRUE); vsip_blockadmit_d(vsip_mgetblock_d(m3),VSIP_TRUE); printf("call vsip_mexpoavg_d(alpha,b,c) three times\n"); printf("alpha = 1\n"); printf("first call b =\n");VU_mprintm_d("8.6",m1); printf("alpha = 1/2\n"); printf("second call b =\n");VU_mprintm_d("8.6",m2); printf("alpha = 1/3\n"); printf("third call b =\n");VU_mprintm_d("8.6",m3); printf("c initialized to zero\n"); vsip_mfill_d(0,c); vsip_mexpoavg_d(1.0,m1,c); vsip_mexpoavg_d(.5,m2,c); vsip_mexpoavg_d(1.0/3.0,m3,c); printf("after third call c =\n");VU_mprintm_d("8.6",c); vsip_madd_d(m1,m2,ans); vsip_madd_d(m3,ans,ans); vsip_smmul_d(alpha,ans,ans); printf("\nright answer =\n"); VU_mprintm_d("6.4",ans); vsip_msub_d(ans,c,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,0,2 * .0001,0,1,chk); if(fabs(vsip_msumval_d(chk)) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_d(m1); vsip_malldestroy_d(m2); vsip_malldestroy_d(m3); vsip_malldestroy_d(ans); vsip_malldestroy_d(c); vsip_malldestroy_d(chk); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cvrealimagview_f.h,v 2.0 2003/02/22 15:23:33 judd Exp $ */ static void cvrealimagview_f(void){ printf("********\nTEST cvrealimagview_f\n"); { vsip_scalar_f data_r[10] = { 0, 1, 2, 3, 4, 5, 7, 8, 9}; vsip_scalar_f data_i[10] = { 0, -1, -2, -3, -4, -5, -7, -8, -9}; vsip_offset o = 40; vsip_stride s = -3; vsip_length n = 10; vsip_cblock_f *b = vsip_cblockcreate_f(100,VSIP_MEM_NONE); vsip_cvview_f *v = vsip_cvbind_f(b,o,s,n); vsip_vview_f *rv = vsip_vrealview_f(v); vsip_vview_f *iv = vsip_vimagview_f(v); vsip_scalar_f chk = 0; vsip_cscalar_f a; int i; for(i=0; i< (int)n; i++){ a.r = data_r[i]; a.i = data_i[i]; vsip_cvput_f(v,i,a); } printf("test vrealview_f\n"); fflush(stdout); for(i=0; i< (int)n; i++){ a.r = vsip_vget_f(rv,i); a.r -= data_r[i]; chk += a.r * a.r; } (chk > .0001) ? printf("error \n") : printf("correct \n"); printf("test vimagview_f\n"); fflush(stdout); chk = 0; for(i=0; i< (int)n; i++){ a.i = vsip_vget_f(iv,i); a.i -= data_i[i]; chk += a.i * a.i; } (chk > .0001) ? printf("error \n") : printf("correct \n"); fflush(stdout); vsip_vdestroy_f(rv); vsip_vdestroy_f(iv); vsip_cvalldestroy_f(v); } return; } <file_sep>/* Created RJudd September 18, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_ctcreate_d.c,v 2.1 2004/09/21 02:07:24 judd Exp $ */ #define VI_CTVIEW_D_ #include"VI_support_cpriv_d.h" #include"VI_cblockcreate_d.h" #include"VI_cblockdestroy_d.h" vsip_ctview_d* vsip_ctcreate_d( vsip_length zlength, vsip_length ylength, vsip_length xlength, vsip_tmajor major, vsip_memory_hint hint) { vsip_cblock_d *block; vsip_ctview_d *ctview; block = VI_cblockcreate_d(zlength * ylength * xlength,hint); if(block == NULL) return (vsip_ctview_d*) NULL; ctview = VI_ctview_d(); if(ctview == NULL){ VI_cblockdestroy_d(block); return ctview; } ctview->block = block; ctview->offset = (vsip_offset)0; ctview->x_length = xlength; ctview->y_length = ylength; ctview->z_length = zlength; if(major == VSIP_TRAILING){ ctview->z_stride = xlength * ylength; ctview->y_stride = xlength; ctview->x_stride = 1; } else { /* VSIP_LEADING */ ctview->x_stride = zlength * ylength; ctview->y_stride = zlength; ctview->z_stride = 1; } ctview->markings = vsip_valid_structure_object; return ctview; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_offset_bl.h,v 2.1 2007/04/18 17:05:56 judd Exp $ */ static void get_put_offset_bl(void){ printf("********\nTEST get_put_offset_bl\n"); { vsip_offset ivo = 3; vsip_stride ivs = 0; vsip_length ivl = 3; vsip_offset jvo = 2; vsip_stride irs = 0, ics = 0; vsip_length irl = 2, icl = 3; vsip_block_bl *b = vsip_blockcreate_bl(80,VSIP_MEM_NONE); vsip_vview_bl *v = vsip_vbind_bl(b,ivo,ivs,ivl); vsip_mview_bl *m = vsip_mbind_bl(b,ivo,ics,icl,irs,irl); vsip_offset s; printf("test vgetoffset_bl\n"); fflush(stdout); { s = vsip_vgetoffset_bl(v); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputoffset_bl\n"); fflush(stdout); { vsip_vputoffset_bl(v,jvo); s = vsip_vgetoffset_bl(v); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /*************************************************************************/ printf("test mgetoffset_bl\n"); fflush(stdout); { s = vsip_mgetoffset_bl(m); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputoffset_bl\n"); fflush(stdout); { vsip_mputoffset_bl(m,jvo); s = vsip_mgetoffset_bl(m); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } vsip_vdestroy_bl(v); vsip_malldestroy_bl(m); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: chol_f.h,v 2.2 2006/04/09 20:58:37 judd Exp $ */ #include"VU_mprintm_f.include" static void chol_f(void){ printf("********\nTEST chol_f\n"); { vsip_index i,j; vsip_block_f *ablock = vsip_blockcreate_f(200,VSIP_MEM_NONE); vsip_mview_f *R = vsip_mcreate_f(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *RH = vsip_mcreate_f(4,4,VSIP_ROW,VSIP_MEM_NONE); /* vsip_mview_f *A = vsip_mcreate_f(4,4,VSIP_ROW,VSIP_MEM_NONE); */ vsip_mview_f *A = vsip_mbind_f(ablock,99,-11,4,-2,4); /* vsip_mview_f *B = vsip_mcreate_f(4,3,VSIP_COL,VSIP_MEM_NONE); */ vsip_mview_f *B = vsip_mbind_f(ablock,100,20,4,2,3); vsip_mview_f *ans = vsip_mcreate_f(4,3,VSIP_ROW,VSIP_MEM_NONE); vsip_chol_f *chol = vsip_chold_create_f(VSIP_TR_UPP,4); vsip_scalar_f chk; vsip_scalar_f data_R[4][4] = { { 1.0, -2.0, 3.0, 1.0}, { 0.0, 2.0, 4.0, -1.0}, { 0.0, 0.0, 4.0, 3.0}, { 0.0, 0.0, 0.0, 6.0} }; vsip_scalar_f data_Br[4][3] = { { 1.0, 2.0, 3.0}, { 0.0, 1.0, 2.0}, { 3.0, 0.0, 1.0}, { 3.0, 4.0, 5.0}}; vsip_scalar_f data_ans[4][3] = { { 4.6250, 13.9062, 21.0000}, { 1.3333, 4.1667, 6.3333}, { -0.3750, -1.3438, -2.0000}, { 0.1667, 0.4583, 0.6667}}; for(i=0; i<4; i++) for(j=0; j<4; j++) vsip_mput_f(R,i,j,data_R[i][j]); for(i=0; i<4; i++) { for(j=0; j<3; j++){ vsip_mput_f(B,i,j,data_Br[i][j]); vsip_mput_f(ans,i,j,data_ans[i][j]); } } vsip_mtrans_f(R,RH); vsip_mprod_f(RH,R,A); printf("R = \n");VU_mprintm_f("4.2",R); printf("RH = \n");VU_mprintm_f("4.2",RH); printf("A = R * RH\n");VU_mprintm_f("4.2",A); printf("B \n");VU_mprintm_f("4.2",B); vsip_chold_f(chol,A); printf("A after decomp");VU_mprintm_f("4.2",A); vsip_cholsol_f(chol,B); printf("Solve using cholesky AX = B\n X = \n");VU_mprintm_f("4.2",B); vsip_chold_destroy_f(chol); printf("right answer \n ans = \n");VU_mprintm_f("4.2",ans); vsip_msub_f(ans,B,B); chk = vsip_msumsqval_f(B); if(chk > .001) printf("error\n"); else printf("correct\n"); { vsip_lu_f *lu = vsip_lud_create_f(4); vsip_mview_f *Bans = vsip_mcreate_f(4,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mprod_f(RH,R,A); for(i=0; i<4; i++) for(j=0; j<3; j++) vsip_mput_f(B,i,j,data_Br[i][j]); vsip_lud_f(lu,A); vsip_lusol_f(lu,VSIP_MAT_NTRANS,B); printf("Solve using LUD AX = B\n X = \n");VU_mprintm_f("4.2",B); vsip_lud_destroy_f(lu); vsip_mprod_f(RH,R,A); vsip_mprod_f(A,B,Bans); printf("Bans = A X\n");VU_mprintm_f("4.2",Bans); vsip_msub_f(ans,B,B); chk = vsip_msumsqval_f(B); if(chk > .001) printf("error\n"); else printf("correct\n"); vsip_malldestroy_f(Bans); } vsip_malldestroy_f(R); vsip_malldestroy_f(RH); vsip_mdestroy_f(B); vsip_malldestroy_f(A); } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: manytrue_bl.h,v 2.0 2003/02/22 15:23:24 judd Exp $ */ #include"VU_mprintm_d.include" static void manytrue_bl(void){ printf("\n*******\nTEST manytrue_bl\n"); { vsip_scalar_bl data0[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; vsip_scalar_bl data1[] = {0, 0, 0, 0, 0, 1, 0, 0, 0, 0}; vsip_scalar_bl data2[] = {0, 1, 0, 1, 0, 1, 1, 1, 1, 0}; vsip_scalar_bl data3[] = {0, 1, 1, 1, 1, 1, 1, 1, 1, 1}; vsip_scalar_bl data4[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; vsip_mview_bl *m0 = vsip_mbind_bl( vsip_blockbind_bl(data0,10,VSIP_MEM_NONE),0,5,2,1,5); vsip_mview_bl *m1 = vsip_mbind_bl( vsip_blockbind_bl(data1,10,VSIP_MEM_NONE),0,5,2,1,5); vsip_mview_bl *m2 = vsip_mbind_bl( vsip_blockbind_bl(data2,10,VSIP_MEM_NONE),0,5,2,1,5); vsip_mview_bl *m3 = vsip_mbind_bl( vsip_blockbind_bl(data3,10,VSIP_MEM_NONE),0,5,2,1,5); vsip_mview_bl *m4 = vsip_mbind_bl( vsip_blockbind_bl(data4,10,VSIP_MEM_NONE),0,5,2,1,5); vsip_mview_d *pm = vsip_mcreate_d(2,5,VSIP_COL,VSIP_MEM_NONE); vsip_blockadmit_bl(vsip_mgetblock_bl(m0),VSIP_TRUE); vsip_blockadmit_bl(vsip_mgetblock_bl(m1),VSIP_TRUE); vsip_blockadmit_bl(vsip_mgetblock_bl(m2),VSIP_TRUE); vsip_blockadmit_bl(vsip_mgetblock_bl(m3),VSIP_TRUE); vsip_blockadmit_bl(vsip_mgetblock_bl(m4),VSIP_TRUE); printf("matrix m0\n"); vsip_mcopy_bl_d(m0,pm); VU_mprintm_d("1.0",pm); printf("matrix m1\n"); vsip_mcopy_bl_d(m1,pm); VU_mprintm_d("1.0",pm); printf("matrix m2\n"); vsip_mcopy_bl_d(m2,pm); VU_mprintm_d("1.0",pm); printf("matrix m3\n"); vsip_mcopy_bl_d(m3,pm); VU_mprintm_d("1.0",pm); printf("matrix m4\n"); vsip_mcopy_bl_d(m4,pm); VU_mprintm_d("1.0",pm); printf("check anytrue \n"); printf("vsip_manytrue_bl(m0)"); if(vsip_manytrue_bl(m0)) printf("true: error\n"); else printf("false: correct\n"); printf("vsip_manytrue_bl(m1)"); if(vsip_manytrue_bl(m1)) printf("true: correct\n"); else printf("false: error\n"); printf("vsip_manytrue_bl(m2)"); if(vsip_manytrue_bl(m2)) printf("true: correct\n"); else printf("false: error\n"); printf("vsip_manytrue_bl(m3)"); if(vsip_manytrue_bl(m3)) printf("true: correct\n"); else printf("false: error\n"); printf("vsip_manytrue_bl(m4)"); if(vsip_manytrue_bl(m4)) printf("true: correct\n"); else printf("false: error\n"); vsip_malldestroy_bl(m0); vsip_malldestroy_bl(m1); vsip_malldestroy_bl(m2); vsip_malldestroy_bl(m3); vsip_malldestroy_bl(m4); vsip_malldestroy_d(pm); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_stride_bl.h,v 2.1 2007/04/18 17:05:56 judd Exp $ */ static void get_put_stride_bl(void){ printf("********\nTEST get_put_stride_bl\n"); { vsip_offset ivo = 3; vsip_stride ivs = 2; vsip_length ivl = 3; vsip_stride jvs = 3; vsip_stride irs = 1, ics = 3; vsip_length irl = 2, icl = 3; vsip_stride jrs = 5, jcs = 2; vsip_block_bl *b = vsip_blockcreate_bl(80,VSIP_MEM_NONE); vsip_vview_bl *v = vsip_vbind_bl(b,ivo,ivs,ivl); vsip_mview_bl *m = vsip_mbind_bl(b,ivo,ics,icl,irs,irl); vsip_stride s; printf("test vgetstride_bl\n"); fflush(stdout); { s = vsip_vgetstride_bl(v); (s == ivs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputstride_bl\n"); fflush(stdout); { vsip_vputstride_bl(v,jvs); s = vsip_vgetstride_bl(v); (s == jvs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /*************************************************************************/ printf("test mgetrowstride_bl\n"); fflush(stdout); { s = vsip_mgetrowstride_bl(m); (s == irs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputrowstride_bl\n"); fflush(stdout); { vsip_mputrowstride_bl(m,jrs); s = vsip_mgetrowstride_bl(m); (s == jrs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test mgetcolstride_bl\n"); fflush(stdout); { s = vsip_mgetcolstride_bl(m); (s == ics) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputcolstride_bl\n"); fflush(stdout); { vsip_mputcolstride_bl(m,jcs); s = vsip_mgetcolstride_bl(m); (s == jcs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } vsip_vdestroy_bl(v); vsip_malldestroy_bl(m); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: rcvdiv_f.h,v 2.0 2003/02/22 15:23:27 judd Exp $ */ #include"VU_vprintm_f.include" #include"VU_cvprintm_f.include" static void rcvdiv_f(void){ printf("\n********\nTEST rcvdiv_f\n"); { vsip_vview_f *a = vsip_vcreate_f(7,VSIP_MEM_NONE); vsip_cvview_f *b = vsip_cvcreate_f(7,VSIP_MEM_NONE); vsip_cvview_f *c = vsip_cvcreate_f(7,VSIP_MEM_NONE); vsip_vview_f *c_i = vsip_vimagview_f(c); vsip_cvview_f *chk = vsip_cvcreate_f(7,VSIP_MEM_NONE); vsip_vview_f *chk_i = vsip_vimagview_f(chk); vsip_scalar_f data[] = {1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7}; vsip_scalar_f data_r[] ={.1, .2, .3, .4, .5, .6, .7}; vsip_scalar_f data_i[] ={7,6,5,4,3,2,1}; vsip_scalar_f data_ans[] ={.0020,-.1428, .0061,-.1831, .0143,-.2391, .0322,-.3218, .0757,-.4541, .2064,-.6881, .7517,-1.0738}; vsip_block_f *block = vsip_blockbind_f(data,7,VSIP_MEM_NONE); vsip_cblock_f *cblock = vsip_cblockbind_f(data_r,data_i,7,VSIP_MEM_NONE); vsip_cblock_f *cblock_ans = vsip_cblockbind_f(data_ans, (vsip_scalar_f*)NULL,7,VSIP_MEM_NONE); vsip_vview_f *u_a = vsip_vbind_f(block,0,1,7); vsip_cvview_f *u_b = vsip_cvbind_f(cblock,0,1,7); vsip_cvview_f *u_ans = vsip_cvbind_f(cblock_ans,0,1,7); vsip_blockadmit_f(block,VSIP_TRUE); vsip_cblockadmit_f(cblock,VSIP_TRUE); vsip_cblockadmit_f(cblock_ans,VSIP_TRUE); vsip_vcopy_f_f(u_a,a); vsip_cvcopy_f_f(u_b,b); printf("call vsip_rcvdiv_f(a,b,c)\n"); printf("a =\n");VU_vprintm_f("8.6",a); printf("b =\n");VU_cvprintm_f("8.6",b); printf("test normal out of place\n"); vsip_rcvdiv_f(a,b,c); printf("c =\n");VU_cvprintm_f("8.6",c); printf("right answer =\n");VU_cvprintm_f("8.4",u_ans); vsip_cvsub_f(u_ans,c,chk); vsip_cvmag_f(chk,chk_i); vsip_vclip_f(chk_i,.0002,.0002,0,1,chk_i); if(vsip_vsumval_f(chk_i) > .5) printf("error\n"); else printf("correct\n"); printf("test b,c inplace\n"); vsip_rcvdiv_f(a,b,b); vsip_cvsub_f(u_ans,b,chk); vsip_cvmag_f(chk,chk_i); vsip_vclip_f(chk_i,.0002,.0002,0,1,chk_i); if(vsip_vsumval_f(chk_i) > .5) printf("error\n"); else printf("correct\n"); printf("test in place a= imaginary(c)\n"); vsip_vcopy_f_f(u_a,c_i); vsip_cvcopy_f_f(u_b,b); vsip_rcvdiv_f(c_i,b,c); vsip_cvsub_f(u_ans,c,chk); vsip_cvmag_f(chk,chk_i); vsip_vclip_f(chk_i,.0002,.0002,0,1,chk_i); if(vsip_vsumval_f(chk_i) > .5) printf("error\n"); else printf("correct\n"); vsip_valldestroy_f(a); vsip_cvalldestroy_f(b); vsip_vdestroy_f(c_i); vsip_cvalldestroy_f(c); vsip_vdestroy_f(chk_i); vsip_cvalldestroy_f(chk); vsip_valldestroy_f(u_a); vsip_cvalldestroy_f(u_b); vsip_cvalldestroy_f(u_ans); } return; } <file_sep>MAKE=make CFLAGS=-O3 DFLAGS= LIBS= -lvsip -lm CC=clang HEADERS = kw.h ts.h SOURCE = param.m kw.m ts.m beamformer_ex.m all:beamformer beamformer:$(SOURCE) $(HEADERS) $(CC) -o beamformer_ex $(SOURCE) $(CFLAGS) -framework jvsipF -framework Foundation clean: rm -f *.o beamformer_ex gramOut <file_sep>/* Created RJudd January 10, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vcreate_blackman_f.c,v 2.1 2003/04/22 02:19:59 judd Exp $ */ /* Removed Development Mode RJudd Sept 00 */ #include"vsip.h" #include"vsip_vviewattributes_f.h" #include"vsip_scalars.h" #include"VI_vcreate_f.h" #define twoPI ((vsip_scalar_f)6.2831853071796) vsip_vview_f* (vsip_vcreate_blackman_f)( vsip_length N, vsip_memory_hint h) { vsip_vview_f *a; a = VI_vcreate_f(N,h); if(a == NULL) return (vsip_vview_f*)NULL; { /*define variables*/ vsip_length n = 0; vsip_scalar_f *ap = (a->block->array) + a->offset, temp1 = twoPI / (N - 1), temp2 = 2 * temp1; /*end define*/ /* Note this is always unit stride */ while(n < N){ *ap++ = (vsip_scalar_f)0.42 - (vsip_scalar_f)0.5 * (vsip_scalar_f)VSIP_COS_F(temp1 * (vsip_scalar_f) n) + (vsip_scalar_f)0.08 * (vsip_scalar_f)VSIP_COS_F(temp2 * (vsip_scalar_f) n); n++; } } return a; } <file_sep>/* Created RJudd */ /* private attributes for permute */ /* $Id: vsip_permuteattributes.h,v 2.1 2008/08/17 17:52:11 judd Exp $ */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #ifndef _vsip_permute_h #define _vsip_permtue_h 1 #include"vsip.h" struct vsip_permuteattributes{ vsip_scalar_vi *in; /* copy of raw input vector */ vsip_scalar_vi *b; vsip_length n_vi; /* length of in[ ], true, ordered */ vsip_major major; /* VSIP_ROW if A(:,v); VSIP_COL if A(v,:) */ }; #endif /*_vsip_permute_h */ <file_sep>/* Created RJudd March 18, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cmherm_f.c,v 2.0 2003/02/22 15:18:43 judd Exp $ */ /* Modified to produce vsip_cmherm_f.c */ /* April 20, 1998 RJudd Modified 1,2 to row,col */ /* Remove Development Mode RJudd Sept 00 */ #include"vsip.h" #include"vsip_cmviewattributes_f.h" void (vsip_cmherm_f)( const vsip_cmview_f* A, const vsip_cmview_f* R) { /* transpose matrix */ { vsip_length lx = A->row_length, ly = A->col_length; vsip_stride cAst = A->block->cstride; vsip_stride cRst = R->block->cstride; vsip_scalar_f tmp; vsip_scalar_f *a_p_r = (vsip_scalar_f*)(A->block->R->array + cAst * A->offset), *a_p_i = (vsip_scalar_f*)(A->block->I->array + cAst * A->offset), *r_p_r = (vsip_scalar_f*)(R->block->R->array + cRst * R->offset), *r_p_i; vsip_length i, j; vsip_stride stAx = cAst * A->row_stride, stAy = cAst *A->col_stride; vsip_stride stRx = cRst * R->row_stride, stRy = cRst *R->col_stride; if((lx == ly) && (a_p_r == r_p_r)){ for(i=1; i<lx; i++){ *(a_p_i + (i-1) * (stAy + stAx)) = - *(a_p_i + (i-1) * (stAx + stAy)); for(j=0; j<i; j++){ tmp = *(a_p_r + j * stAy + i * stAx); *(a_p_r + j * stAy + i * stAx) = *(a_p_r + j * stAx + i * stAy); *(a_p_r + j * stAx + i * stAy) = tmp; tmp = - *(a_p_i + j * stAy + i * stAx); *(a_p_i + j * stAy + i * stAx) = - *(a_p_i + j * stAx + i * stAy); *(a_p_i + j * stAx + i * stAy) = tmp; } } *(a_p_i + (i-1) * (stAy + stAx)) = - *(a_p_i + (i-1) * (stAx + stAy)); } else { for(i=0; i<ly; i++){ r_p_r = (vsip_scalar_f*)(R->block->R->array + cRst * R->offset + i * stRx); r_p_i = (vsip_scalar_f*)(R->block->I->array + cRst * R->offset + i * stRx); a_p_r = (vsip_scalar_f*)(A->block->R->array + cAst * A->offset + i * stAy); a_p_i = (vsip_scalar_f*)(A->block->I->array + cAst * A->offset + i * stAy); for(j=0; j<lx; j++){ *r_p_r = *a_p_r; *r_p_i = - *a_p_i; r_p_r += stRy; a_p_r += stAx; r_p_i += stRy; a_p_i += stAx; } } } } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmmeanval_f.h,v 2.0 2003/02/22 15:23:21 judd Exp $ */ #include"VU_cmprintm_f.include" static void cmmeanval_f(void){ printf("\n*******\nTEST cmmeanval_f\n\n"); { vsip_scalar_f data_r[] = {M_PI/8.0, M_PI/4.0, M_PI/3.0, M_PI/1.5, 1.25 * M_PI, 1.75 * M_PI}; vsip_scalar_f data_i[] = { 1, 2, -3, -4, 5, 6}; vsip_cscalar_f ans = vsip_cmplx_f(2.29074,1.16667); vsip_cscalar_f val; vsip_cblock_f *block = vsip_cblockbind_f(data_r,data_i,6,VSIP_MEM_NONE); vsip_cmview_f *a = vsip_cmbind_f(block,0,2,3,1,2); vsip_cblockadmit_f(block,VSIP_TRUE); val = vsip_cmmeanval_f(a); printf("val = vsip_cmmeanval_f(a)\n matrix a\n");VU_cmprintm_f("8.6",a); printf("val = %f %+fi\n",vsip_real_f(val),vsip_imag_f(val)); printf("right answer = %f %+fi\n",vsip_real_f(ans),vsip_imag_f(ans)); if(((vsip_real_f(val)-vsip_real_f(ans)) > .0001) || ((vsip_imag_f(val)-vsip_imag_f(ans)) > .0001)) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: ctmisc_view_f.h,v 2.1 2009/09/05 18:01:45 judd Exp $ */ static void ctmisc_view_f(void){ printf("********\nTEST ctmisc_view_f\n"); { vsip_index k,j,i; vsip_scalar_f data_r[4][3][4] = { {{0.0, 0.01, 0.02, 0.03}, \ { 0.1, 0.11, 0.12, 0.13}, \ { 0.2, 0.21, 0.22, 0.23}},{ \ { 1.0, 1.01, 1.02, 1.03}, \ { 1.1, 1.11, 1.12, 1.13}, \ { 1.2, 1.21, 1.22, 1.23}},{ \ { 2.0, 2.01, 2.02, 2.03}, \ { 2.1, 2.11, 2.12, 2.13}, \ { 2.2, 2.21, 2.22, 2.23}},{ \ { 3.0, 3.01, 3.02, 3.03}, \ { 3.1, 3.11, 3.12, 3.13}, \ { 3.2, 3.21, 3.22, 3.23}}}; vsip_scalar_f data_i[4][3][4] = { {{0.0, -0.01, -0.02, -0.03}, \ {-0.1, -0.11, -0.12, -0.13}, \ {-0.2, -0.21, -0.22, -0.23}},{ \ {-1.0, -1.01, -1.02, -1.03}, \ {-1.1, -1.11, -1.12, -1.13}, \ {-1.2, -1.21, -1.22, -1.23}},{ \ {-2.0, -2.01, -2.02, -2.03}, \ {-2.1, -2.11, -2.12, -2.13}, \ {-2.2, -2.21, -2.22, -2.23}},{ \ {-3.0, -3.01, -3.02, -3.03}, \ {-3.1, -3.11, -3.12, -3.13}, \ {-3.2, -3.21, -3.22, -3.23}}}; /* if a problem with tcreate is suspected check both leading and trailing options here */ vsip_ctview_f *tview_a = vsip_ctcreate_f(12,9,12,VSIP_LEADING,VSIP_MEM_NONE); /* vsip_ctview_f *tview_a = vsip_ctcreate_f(12,9,12,VSIP_TRAILING,VSIP_MEM_NONE); */ vsip_cblock_f *block_a = vsip_ctgetblock_f(tview_a); vsip_ctview_f *tview_b = vsip_ctsubview_f(tview_a,1,2,3,4,3,4); vsip_stride z_a_st = vsip_ctgetzstride_f(tview_a); vsip_stride y_a_st = vsip_ctgetystride_f(tview_a); vsip_stride x_a_st = vsip_ctgetxstride_f(tview_a); vsip_offset b_o_calc = z_a_st + 2 * y_a_st + 3 * x_a_st; vsip_offset b_o_get = vsip_ctgetoffset_f(tview_b); vsip_ctview_f *v = vsip_ctbind_f(block_a,b_o_calc, z_a_st,4, y_a_st,3, x_a_st,4); vsip_cmview_f *mview = (vsip_cmview_f*)NULL; vsip_cvview_f *vview = (vsip_cvview_f*)NULL; vsip_ctview_f *tview = (vsip_ctview_f*)NULL; vsip_cscalar_f a; vsip_scalar_f chk = 0; printf("z_a_st %d; y_a_st %d; x_a_st %d\n",(int)z_a_st,(int)y_a_st,(int)x_a_st); fflush(stdout); printf("b_o_calc %u; b_o_get %u\n",(unsigned)b_o_calc,(unsigned)b_o_get); fflush(stdout); for(k = 0; k < 4; k++){ for(j = 0; j < 3; j++){ for(i = 0; i < 4; i++){ a.r = data_r[k][j][i]; a.i = data_i[k][j][i]; vsip_ctput_f(v,k,j,i,a); } } } printf("test ctmatrixview_f\n"); printf("TMZY\n"); fflush(stdout); for(i = 0; i < 4; i++){ mview = vsip_ctmatrixview_f(v,VSIP_TMZY,i); for(j = 0; j < 3; j++){ for(k = 0; k < 4; k++){ a = vsip_cmget_f(mview,k,j); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } vsip_cmdestroy_f(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TMYX\n"); fflush(stdout); for(k = 0; k < 4; k++){ mview = vsip_ctmatrixview_f(v,VSIP_TMYX,k); for(j = 0; j < 3; j++){ for(i = 0; i < 4; i++){ a = vsip_cmget_f(mview,j,i); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } vsip_cmdestroy_f(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TMZX\n"); fflush(stdout); for(j = 0; j < 3; j++){ mview = vsip_ctmatrixview_f(v,VSIP_TMZX,j); for(k = 0; k < 4; k++){ for(i = 0; i < 4; i++){ a = vsip_cmget_f(mview,k,i); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } vsip_cmdestroy_f(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test ctvectview_f\n"); printf("TVX \n"); fflush(stdout); for(k=0; k<4; k++){ for(j=0; j<3; j++){ vview = vsip_ctvectview_f(v,VSIP_TVX,k,j); for(i=0; i<4; i++){ a = vsip_cvget_f(vview,i); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } vsip_cvdestroy_f(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test ctvectview_f\n"); printf("TVY \n"); fflush(stdout); for(k=0; k<4; k++){ for(i=0; i<4; i++){ vview = vsip_ctvectview_f(v,VSIP_TVY,k,i); for(j=0; j<3; j++){ a = vsip_cvget_f(vview,j); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } vsip_cvdestroy_f(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TVZ \n"); fflush(stdout); for(j=0; j<3; j++){ for(i=0; i<4; i++){ vview = vsip_ctvectview_f(v,VSIP_TVZ,j,i); for(k=0; k<4; k++){ a = vsip_cvget_f(vview,k); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } vsip_cvdestroy_f(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test cttransview_f\n"); fflush(stdout); printf("NOP\n"); fflush(stdout); tview = vsip_cttransview_f(v,VSIP_TTRANS_NOP); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_ctget_f(tview,k,j,i); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } } vsip_ctdestroy_f(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YX\n"); fflush(stdout); tview = vsip_cttransview_f(v,VSIP_TTRANS_YX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_ctget_f(tview,k,i,j); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } } vsip_ctdestroy_f(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("ZY\n"); fflush(stdout); tview = vsip_cttransview_f(v,VSIP_TTRANS_ZY); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_ctget_f(tview,j,k,i); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } } vsip_ctdestroy_f(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("ZX\n"); fflush(stdout); tview = vsip_cttransview_f(v,VSIP_TTRANS_ZX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_ctget_f(tview,i,j,k); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } } vsip_ctdestroy_f(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YXZY\n"); fflush(stdout); tview = vsip_cttransview_f(v,VSIP_TTRANS_YXZY); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_ctget_f(tview,i,k,j); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } } vsip_ctdestroy_f(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YXZX\n"); fflush(stdout); tview = vsip_cttransview_f(v,VSIP_TTRANS_YXZX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_ctget_f(tview,j,i,k); a.r -= data_r[k][j][i]; a.i -= data_i[k][j][i]; chk += a.r * a.r + a.i * a.i; } } } vsip_ctdestroy_f(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; vsip_ctdestroy_f(v); vsip_ctdestroy_f(tview_b); vsip_ctalldestroy_f(tview_a); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mcminmgsq_d.h,v 2.0 2003/02/22 15:23:24 judd Exp $ */ #include"VU_cmprintm_d.include" #include"VU_mprintm_d.include" static void mcminmgsq_d(void){ printf("\n******\nTEST mcminmgsq_d\n"); { vsip_scalar_d data1[]= {1,.1, 2,.2, 3,.3, 4,-.1, 5,-.3, 6,-.4, 7,.8, 8,.9, 9,-1}; vsip_scalar_d data2_r[]= {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9}; vsip_scalar_d data2_i[]= {-1.1, 2.2, -3.3, 4.4, -5.5, 6.6, -7.7, 8.8, -9.9}; vsip_scalar_d ans[] = { 1.01, 4.04, 9.09, 9.68, 25.09, 36.16, 21.78, 64.81, 82.00}; vsip_cmview_d *m1 = vsip_cmbind_d( vsip_cblockbind_d(data1,NDPTR_d,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_cmview_d *m2 = vsip_cmbind_d( vsip_cblockbind_d(data2_r,data2_i,9,VSIP_MEM_NONE),0,1,3,3,3); vsip_mview_d *ma = vsip_mbind_d( vsip_blockbind_d(ans,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_mview_d *m3 = vsip_mcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *chk = vsip_mcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cblockadmit_d(vsip_cmgetblock_d(m1),VSIP_TRUE); vsip_cblockadmit_d(vsip_cmgetblock_d(m2),VSIP_TRUE); vsip_blockadmit_d(vsip_mgetblock_d(ma),VSIP_TRUE); printf("call vsip_mcminmgsq_d(a,b,c)\n"); printf("a =\n");VU_cmprintm_d("8.6",m1); printf("b =\n");VU_cmprintm_d("8.6",m2); vsip_mcminmgsq_d(m1,m2,m3); printf("c =\n");VU_mprintm_d("8.6",m3); printf("\nright answer =\n"); VU_mprintm_d("6.4",ma); vsip_msub_d(ma,m3,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,0,2 * .0001,0,1,chk); if(fabs(vsip_msumval_d(chk)) > .5) printf("error\n"); else printf("correct\n"); { vsip_cmview_d *a = vsip_cmcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *c= vsip_mrealview_d(a); vsip_cmcopy_d_d(m1,a); printf(" inplace <c> real view of <a> \n"); vsip_mcminmgsq_d(a,m2,c); vsip_msub_d(ma,c,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,0,2 * .0001,0,1,chk); if(fabs(vsip_msumval_d(chk)) > .5) printf("error\n"); else printf("correct\n"); vsip_mdestroy_d(c); vsip_cmalldestroy_d(a); } { vsip_cmview_d *b = vsip_cmcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *c= vsip_mimagview_d(b); vsip_cmcopy_d_d(m2,b); printf(" inplace <c> imag view of <b> \n"); vsip_mcminmgsq_d(m1,b,c); vsip_msub_d(ma,c,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,0,2 * .0001,0,1,chk); if(fabs(vsip_msumval_d(chk)) > .5) printf("error\n"); else printf("correct\n"); vsip_mdestroy_d(c); vsip_cmalldestroy_d(b); } vsip_cmalldestroy_d(m1); vsip_cmalldestroy_d(m2); vsip_malldestroy_d(m3); vsip_malldestroy_d(ma); vsip_malldestroy_d(chk); } return; } <file_sep>/* Created RJudd */ /* */ #include"VU_vprintm_d.include" static void vfreqswap_d(void){ printf("*********\nTEST vfreqswap_d\n"); { vsip_length M=8,N=9; vsip_vview_d *even = vsip_vcreate_d(M,VSIP_MEM_NONE); vsip_vview_d *ans_even=vsip_vcreate_d(M,VSIP_MEM_NONE); vsip_vview_d *odd = vsip_vcreate_d(N,VSIP_MEM_NONE); vsip_vview_d *ans_odd=vsip_vcreate_d(N,VSIP_MEM_NONE); vsip_scalar_d even_ans[] = {4, 5, 6, 7, 0, 1, 2, 3}; vsip_scalar_d odd_ans[] = {4, 5, 6, 7, 8, 0, 1, 2, 3}; vsip_vcopyfrom_user_d(even_ans, ans_even); vsip_vcopyfrom_user_d(odd_ans, ans_odd); vsip_vramp_d(0,1,even); vsip_vramp_d(0,1,odd); vsip_vfreqswap_d(even); printf("For even expect\n");VU_vprintm_d("2.1",ans_even); printf("for even result\n");VU_vprintm_d("2.1",even); { vsip_vsub_d(even,ans_even,ans_even); if(fabs(vsip_vmaxval_d(ans_even,NULL)) > .00001){ printf("error\n"); }else{ printf("correct\n"); } } vsip_vfreqswap_d(odd); printf("For odd expect\n");VU_vprintm_d("2.1",ans_odd); printf("for odd result\n");VU_vprintm_d("2.1",odd); { vsip_vsub_d(odd,ans_odd,ans_odd); if(fabs(vsip_vmaxval_d(ans_odd,NULL)) > .00001){ printf("error\n"); }else{ printf("correct\n"); } } vsip_valldestroy_d(even); vsip_valldestroy_d(odd); } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vget_put_i.h,v 2.0 2003/02/22 15:23:36 judd Exp $ */ static void vget_put_i(void){ printf("********\nTEST vget_put_i\n"); { vsip_scalar_i data_a[] = { 0, 1, 1, 0, 1, 0}; vsip_scalar_i ans[] = { 0, 1, 1, 0, 1, 0}; vsip_block_i *block_a = vsip_blockbind_i(data_a,6,VSIP_MEM_NONE); vsip_vview_i *a = vsip_vbind_i(block_a,0,1,6); vsip_block_i *block_b = vsip_blockcreate_i(50,VSIP_MEM_NONE); vsip_vview_i *b = vsip_vbind_i(block_b, 35,-2,6); vsip_index i; vsip_blockadmit_i(block_a,VSIP_TRUE); /* copy <a> into <b> */ for(i=0; i<6; i++) vsip_vput_i(b,i,vsip_vget_i(a,i)); /* check <a> against ans */ printf("check unit stride compact view\n"); for(i=0; i<6; i++){ vsip_scalar_i chk = (ans[i] - vsip_vget_i(a,i)); (chk == 0) ? printf("correct\n") : printf("error\n"); fflush(stdout); } printf("check general stride view\n"); for(i=0; i<6; i++){ vsip_scalar_i chk = (ans[i] - vsip_vget_i(a,i)); (chk == 0) ? printf("correct\n") : printf("error\n"); fflush(stdout); } vsip_valldestroy_i(a); vsip_valldestroy_i(b); } return; } <file_sep>#include<stdio.h> #include<vsip.h> #define N 6 /* the length of the vector */ void VU_vprint_f(vsip_vview_f* a){ vsip_length i; for(i=0; i<vsip_vgetlength_f(a); i++) printf("%+.2f ",vsip_vget_f(a,i)); printf("\n"); return; } int main(){vsip_init((void*)0); { vsip_vview_f *A = vsip_vcreate_f(N,0), *B = vsip_vcreate_f(N,0), *C = vsip_vcreate_f(N,0); vsip_randstate *rndm=\ vsip_randcreate(7,1,1,VSIP_PRNG); vsip_vrandn_f(rndm,A); printf("A = ");VU_vprint_f(A); vsip_vfill_f(5,B); printf("B = ");VU_vprint_f(B); vsip_vadd_f(A,B,C); printf("C = A+B\n"); printf("C = ");VU_vprint_f(C); vsip_valldestroy_f(A); vsip_valldestroy_f(B); vsip_valldestroy_f(C); vsip_randdestroy(rndm); } vsip_finalize((void*)0); return 1; } /* output */ /* A = -0.05 +0.59 +0.73 -0.37 -0.21 -0.83 B = +5.00 +5.00 +5.00 +5.00 +5.00 +5.00 C = A+B C = +4.95 +5.59 +5.73 +4.63 +4.79 +4.17 */ <file_sep>import pyJvsip as pv from math import pi, ceil, log, pow, floor from localmax import localmax from frefine import frefine from firfbe import firfbe from matplotlib.pyplot import figure,plot,axis,xlabel,ylabel,title,clf def firebp(n,w1,w2,Del): """[h,rs,be] = firebp(n,w1,w2,Del); Bandpass linear phase FIR filter design with specified ripple sizes. - the derivative of the frequency response amplitude at w1 is set equal to the negative derivative of the amplitude at w2 - author : <NAME>, Rice University, Dec 94 parameters h : filter of length 2*n+1 rs : reference set upon convergence be : band edges of h w1 : first half-magnitude frequency w2 : second half-magnitude frequency w1 < w2, w1,w2 should be in the interval (0,pi) Del : [ripple size in first stopband, passband, second stopband] subprograms needed localmax, frefine, firfbe EXAMPLE n = 23; w1 = 0.14 * 2*pi; w2 = 0.34 * 2*pi; Del = [0.01 0.03 0.01]; [h,rs,be] = firebp(n,w1,w2,Del); """ def rem(a,b): return a % b try: log2 except: def log2(a): return log(a,2) def mp(t,lngth): #minus_plus vector [-1 1 -1 ... (-1)^lngth] assert isinstance(lngth,int),'Length argument to mp must be an integer. ' assert isinstance(t,str) and t in ['vview_d','vview_f'],\ "type argument must be 'vview_d' or 'vview_f'" retview = create(t,lngth).fill(1.0) retview[:lngth:2].fill(-1.0) return retview def diff(a): assert 'pyJvsip' in repr(a),'diff only works with pyJvsip views' assert 'vview' in a.type, 'diff only works with vector views' if a.length > 1: retview = a[1:a.length] - a[:a.length - 1] return retview else: return None def srmp(t,s,e): assert isinstance(e,int) and isinstance(s,int),'start and end must be intergers' assert e > s, 'simple ramps alwasy go up; end > start ' return pv.create(t,e-s+1).ramp(s,1) def coscoef(rs,n,V,Y): f={'vview_d':'mview_d','vview_f':'mview_f'} m=rs.length + 1 y=pv.create(Y.type,m) y[:Y.length]=Y;y[m-1]=0.0 A=pv.create(f[y.type],m,y.length) a=A[:rs.length,:n+1] a=pv.outer(1,rs,pv.create(rs.type,n+1).ramp(0,1),a).cos at=A.rowview(m-1) A.rowview(m-1)[:]=V[:] return A.luSolve(y) # ------------------ initialize constants --------------------------- assert 'pyJvsip' in repr(Del) and Del.type in ['vview_f','vview_d'],\ "last argument is a vector view of type 'vview_f' or 'vview_d'" t=Del.type L = int(pow(2,int(ceil(log2(10*n))))) w = pv.create(t,L+1).ramp(0,pi/float(L)) # frequency axis N = n - 2 # number of _non-specified interpolation points SN = 1e-8 # Small Number (stopping criterion) H0 = pv.create(t,2*(L+1-n)+2*n-2).fill(0.0) V = pv.create(t,n+1).ramp(0,1);V *= V.empty.ramp(0,w1).sin + V.empty.ramp(0,w2).sin ideal = Del.empty.fill(0.0); ideal[1]=1.0 up = ideal + Del lo = ideal - Del D1 = 0.5 # half-magnitude value at w1 D2 = 0.5 # half-magnitude value at w2 PF = False # PF : flag : Plot Figures # ------------------ initialize reference set ---------------------------- # n1 : number of reference frequencies in first stopband # n2 : number of reference frequencies in passband # n3 : number of reference frequencies in second stopband n2 = int(round(N*(w2-w1)/pi)) if rem(n2,2) == 0: n2 = n2 - 1 n1 = int(floor((N-n2)*w1/(pi-(w2-w1)))) n3 = N-n2-n1 rs = pv.create(t,n1+n2+n3+2) R1 = rs[0:n1].ramp(0,1); R1 *= w1/float(n1) R2 = rs[n1+1:n1+1+n2].ramp(1,1);R2 *= (w2-w1)/float(n2+1);R2 += w1 R3 = rs[n1+n2+2:n1+n2+2+n3].ramp(1,1);R3 *= (pi-w2)/float(n3);R3 += w2 rs[n1]=w1; rs[n1+1+n2]=w2 # ------------------ initialize interpolation values --------------------- Y=pv.create(t,n1+n2+n3+2).fill(0.0) if n1 % 2 == 0: Y[0:n1:2].fill(up[0]);Y[1:n1:2].fill(lo[0]) else: Y[0:n1:2].fill(lo[0]);Y[1:n1:2].fill(up[0]) Y[n1]=D1;o=n1+1;l=n1+1+n2 Y[o:l:2].fill(up[1]);Y[o+1:l:2].fill(lo[1]) Y[l]=D2;o=l+1;l=o+n3 Y[o:l:2].fill(lo[2]);Y[o+1:l:2].fill(up[2]) # begin looping Err = 1 while Err > SN: # --------------- calculate cosine coefficients ----------------------- a = coscoef(rs,n,V,Y) # --------------- calculate frequency response ------------------------ #H = real(fft([a(1);a(2:n+1)/2;Z;a(n+1:-1:2)/2])); H = H(1:L+1); attr=a.attrib; ot=attr['offset'];lt=attr['length'];st=attr['stride']; ot+=(lt-1)*st; st=-st;attr['offset']=ot; attr['stride']=st a_rev=a.cloneview;a_rev.putattrib(attr) H0.fill(0.0);H0[0]=a[0];H0[1:lt]=a[1:]*0.5; H0[H0.length-n:]=a_rev[:lt-1]*0.5 Hc=H0.rcfft H=Hc.realview[:L+1].copy # --------------- determine local max and min ------------------------- v1 = localmax(H) v2 = localmax(H.copy.neg) if v1[0] < v2[0]: s = 0; else: s = 1; #ri = sortip([v1; v2]); ri=pv.create(H.type,v1.length+v2.length) ri[:v1.length]=v1;ri[v1.length:]=v2 ri.sortip() rs = (ri)*(pi/L) rs = frefine(a,rs) n1 = rs.llt(w1).sumval n2 = pv.bb_and(rs.lgt(w1), rs.llt(w2), pv.create('vview_bl',rs.length)).sumval n3 = rs.lgt(w2).sumval # --------------- calculate frequency response at local max and min --- Hr = rs.outer(srmp(rs.type,0,n)).cos.prod(a) Id=pv.create(Del.type,n1+n2+n3);Dr=Id.empty Id[:n1].fill(ideal[0]);Id[n1:n1+n2].fill(ideal[1]);Id[n1+n2:].fill(ideal[2]) Dr[:n1].fill(Del[0]);Dr[n1:n1+n2].fill(Del[1]);Dr[n1+n2:].fill(Del[2]) Er = (Hr - Id)*Dr.recip # Plot Figures if PF is True if PF: figure(1) plot((w*(1./pi)).list,H.list) plot((rs*(1.0/pi)).list,Hr.list,'o') axis([0, 1, -.2, 1.2]) figure(2) plot(Er.list) plot(Er.list,'o'), pause(0.05) # --------------- calculate new interpolation points ----------------- Y=Id.empty if n1 % 2 == 0: Y[0:n1:2].fill(up[0]);Y[1:n1:2].fill(lo[0]) else: Y[0:n1:2].fill(lo[0]);Y[1:n1:2].fill(up[0]) Y[n1+1:n1+n2:2].fill(lo[1]);Y[n1:n1+n2:2].fill(up[1]) Y[n1+n2+1::2].fill(up[2]);Y[n1+n2::2].fill(lo[2]) # --------------- slim down the set of local max and min -------------- # --------------- to obtain new reference set of correct size --------- if (rs.length-N) == 1: # remove one frequency from the reference set if abs(Er[0]-Er[1]) < abs(Er[rs.length-1]-Er[rs.length-2]): I = 1; s = s + 1; else: I = rs.length; del rs[I-1]; del Y[I-1]; del Er[I-1] elif (rs.length-N) == 2: # remove two frequencies # remove either the two endpoints or remove two adjacent points in the ref. set k = (diff(Er)*(mp(Er.type,rs.length-1)+s)).minvalindex+1; if (k == 1) | (k == (rs.length-1)): if k == 1: I = 1; s = s + 1 else: I = rs.length del rs[I-1]; del Y[I-1]; del Er[I-1] if abs(Er[0]-Er[1]) < abs(Er[rs.length-1]-Er[rs.length-2]): I = 1; s = s + 1; else: I = rs.length; del rs[I-1]; del Y[I-1]; del Er[I-1] else: I = k; del rs[I-1]; del Y[I-1]; del Er[I-1] del rs[I-1]; del Y[I-1]; del Er[I-1] elif (rs.length-N) == 3: # remove three frequencies # just use the code for (rs.length-N)==1, followed by the code for (rs.length-N)==2 if abs(Er[0]-Er[1]) < abs(Er[rs.length-1]-Er[rs.length-2]): I = 1; s = s + 1 else: I = rs.length del rs[I-1]; del Y[I-1]; del Er[I-1] k = (diff(Er)*(mp(Er.type,rs.length-1)+s)).minvalindex+1 if (k == 1) or (k == (rs.length-1)): if k == 1: I = 1; s = s + 1 else: I = rs.length; del rs[I-1]; del Y[I-1]; del Er[I-1] if abs(Er[0]-Er[1]) < abs(Er[rs.length-1]-Er[rs.length-2]): I = 1; s = s + 1 else: I = rs.length; del rs[I-1]; del Y[I-1]; del Er[I-1] else: I = k; del rs[I-1]; del Y[I-1]; del Er[I-1] del rs[I-1]; del Y[I-1]; del Er[I-1] # END IF # calculate error Err = Er.maxmgval-1 #max(abs(Er))-1 print(' Err = %20.15f\n'%Err) if Err > SN: # --------------- update new interpolation points --------------------- n1 = rs.llt(w1).sumval n2 = pv.bb_and(rs.lgt(w1), rs.llt(w2), pv.create('vview_bl',rs.length)).sumval n3 = rs.lgt(w2).sumval Y1 = Y[0:n1].copy Y2 = Y[n1:n1+n2].copy Y3 = Y[n1+n2:].copy Y = pv.create(Y1.type,n1+n2+n3+2) Y[0:n1]=Y1;Y[n1]=D1;Y[n1+1:n1+n2+1]=Y2;Y[n1+n2+1]=D2;Y[n1+n2+2:]=Y3 # --------------- update new reference set ---------------------------- #rs = [rs(1:n1); w1; rs(n1+1:n1+n2); w2; rs(n1+n2+1:n1+n2+n3)] rst1=rs[0:n1].copy;rst2=rs[n1:n1+n2].copy;rst3=rs[n1+n2:].copy rs=pv.create(rst1.type,rs.length+2) rs[:n1]=rst1;rs[n1]=w1;rs[n1+1:n1+n2+1]=rst2;rs[n1+n2+1]=w2;rs[n1+n2+2:]=rst3 #end while # ------------------ calculate band edges ---------------------------- be = firfbe(a,pv.listToJv(Del.type,[w1,w1,w2,w2]),pv.listToJv(Del.type,[up[0],lo[1],lo[1],up[2]])) # ------------------ calcuate filter coefficients ---------------------------- #h = [a(n+1:-1:2)/2; a(1); a(2:n+1)/2] a[1:]*=0.5 atr=a[1:].attrib h=pv.create(Del.type,2*a.length-1) h[a.length-1]=a[0] h[a.length:]=a[1:] atr=a[1:].attrib;atr['offset']=atr['length'];atr['stride']*=-1 a.putattrib(atr);h[:a.length]=a figure(1); clf(); plot((w*(1.0/pi)).list,H.list); plot((rs*(1.0/pi)).list,Y.list,'x') axis([0, 1, -.2, 1.2]) xlabel('w'); ylabel('H'); title('Frequency Response Amplitude') return(h,rs,be) <file_sep>/* Created <NAME> 2013*/ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /********************************************************************* // The MIT License (see copyright for jvsip in top level directory) // http://opensource.org/licenses/MIT **********************************************************************/ #include<vsip.h> typedef struct {vsip_mview_f* L;vsip_vview_f* d;vsip_vview_f* f;vsip_mview_f* R;vsip_scalar_f eps0;int init;} svdObj_f; typedef struct {vsip_mview_d* L;vsip_vview_d* d;vsip_vview_d* f;vsip_mview_d* R;vsip_scalar_d eps0;int init;} svdObj_d; typedef struct {vsip_cmview_f* L;vsip_vview_f* d;vsip_vview_f* f;vsip_cmview_f* R;vsip_scalar_f eps0;int init;} csvdObj_f; typedef struct {vsip_cmview_d* L;vsip_vview_d* d;vsip_vview_d* f;vsip_cmview_d* R;vsip_scalar_d eps0;int init;} csvdObj_d; typedef struct {vsip_scalar_f c; vsip_scalar_f s; vsip_scalar_f r;}givensObj_f ; typedef struct {vsip_scalar_d c; vsip_scalar_d s; vsip_scalar_d r;}givensObj_d; typedef struct {vsip_index i; vsip_index j;} svdCorner; svdObj_f svd_f(vsip_mview_f*); csvdObj_f csvd_f(vsip_cmview_f*); svdObj_d svd_d(vsip_mview_d*); csvdObj_d csvd_d(vsip_cmview_d*); <file_sep>// // gen.h // jvsip_pp0 // // Created by <NAME> on 1/28/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #ifndef jvsip_pp0_gen_h #define jvsip_pp0_gen_h #include "support.h" namespace vsip { vsip_vview_vi * fill(vsip_scalar_vi x0, vsip_length l){ vsip_vview_vi *v;create(&v,l); vsip_vfill_vi(x0,v); return v; } vsip_vview_vi * fill(vsip_scalar_vi x0, vsip_vview_vi *v){ vsip_vfill_vi(x0,v); return v; } vsip_vview_i * fill(vsip_scalar_i x0, vsip_length l){ vsip_vview_i *v;create(&v,l); vsip_vfill_i(x0,v); return v; } vsip_vview_i * fill(vsip_scalar_i x0, vsip_vview_i *v){ vsip_vfill_i(x0,v); return v; } vsip_vview_f * fill(vsip_scalar_f x0, vsip_length l){ vsip_vview_f *v;create(&v,l); vsip_vfill_f(x0,v); return v; } vsip_vview_f * fill(vsip_scalar_f x0, vsip_vview_f *v){ vsip_vfill_f(x0,v); return v; } vsip_mview_f * fill(vsip_scalar_f x0, vsip_length cl, vsip_length rl){ vsip_mview_f *v;create(&v,cl,rl); vsip_mfill_f(x0,v); return v; } vsip_mview_f * fill(vsip_scalar_f x0, vsip_mview_f *v){ vsip_mfill_f(x0,v); return v; } vsip_vview_d * fill(vsip_scalar_d x0, vsip_length l){ vsip_vview_d *v;create(&v,l); vsip_vfill_d(x0,v); return v; } vsip_vview_d * fill(vsip_scalar_d x0, vsip_vview_d *v){ vsip_vfill_d(x0,v); return v; } vsip_mview_d * fill(vsip_scalar_d x0, vsip_length cl, vsip_length rl){ vsip_mview_d *v;create(&v,cl,rl); vsip_mfill_d(x0,v); return v; } vsip_mview_d * fill(vsip_scalar_d x0, vsip_mview_d *v){ vsip_mfill_d(x0,v); return v; } vsip_vview_f * ramp(vsip_scalar_f x0, vsip_scalar_f xinc, vsip_length l){ vsip_vview_f *v;create(&v,l); vsip_vramp_f(x0,xinc,v); return v; } vsip_vview_f * ramp(vsip_scalar_f x0, vsip_scalar_f xinc, vsip_vview_f *v){ vsip_vramp_f(x0,xinc,v); return v; } vsip_cvview_f *ramp(vsip_scalar_f x0, vsip_scalar_f xinc, vsip_cvview_f *cv){ vsip_vview_f *v; fill((float)0.0,imagview(&v, cv)); return cv; } vsip_vview_d * ramp(vsip_scalar_d x0, vsip_scalar_d xinc, vsip_length l){ vsip_vview_d *v;create(&v,l); vsip_vramp_d(x0,xinc,v); return v; } vsip_vview_d * ramp(vsip_scalar_d x0, vsip_scalar_d xinc, vsip_vview_d *v){ vsip_vramp_d(x0,xinc,v); return v; } vsip_cvview_d *ramp(vsip_scalar_d x0, vsip_scalar_d xinc, vsip_cvview_d *cv){ vsip_vview_d *v; fill((float)0.0,imagview(&v, cv)); return cv; } vsip_vview_i * ramp(vsip_scalar_i x0, vsip_scalar_i xinc, vsip_length l){ vsip_vview_i *v;create(&v,l); vsip_vramp_i(x0,xinc,v); return v; } vsip_vview_vi * ramp(vsip_scalar_vi x0, vsip_scalar_vi xinc, vsip_length l){ vsip_vview_vi *v;create(&v,l); vsip_vramp_vi(x0,xinc,v); return v; } vsip_vview_i * ramp(vsip_scalar_i x0, vsip_scalar_i xinc, vsip_vview_i *v){ vsip_vramp_i(x0,xinc,v); return v; } vsip_vview_vi * ramp(vsip_scalar_vi x0, vsip_scalar_vi xinc, vsip_vview_vi *v){ vsip_vramp_vi(x0,xinc,v); return v; } } #endif <file_sep># Elementary Math functions from vsip import * def __iscompatible(a,b): """ """ chk = True msg='None' if ('pyJvsip' not in repr(a)) or ('pyJvsip' not in repr(b)): chk = False msg='Input must be a pyJvsip View' elif a.type != b.type: chk = False msg = 'Inputs must be the same type' elif 'mview' in a.type: if (a.rowlength != b.rowlength) or (a.collength != b.collength): chk = False msg = 'Inputs must be the same size' else: if a.length != b.length: chk = False msg = 'Inputs must be the same size' return (chk,msg) def acos(a,b): vf={'vview_f':vsip_vacos_f,'vview_d':vsip_vacos_d} mf={'mview_f':vsip_macos_f,'mview_d':vsip_macos_d} chk , msg = __iscompatible(a,b) if chk: if a.type in vf: vf[a.type](a.vsip,b.vsip) elif a.type in mf: mf[a.type](a.vsip,b.vsip) else: print('Type <:'+a.type+':> not supported for acos') return return b else: print(msg + ' for acos') return def asin(a,b): vf={'vview_f':vsip_vasin_f,'vview_d':vsip_vasin_d} mf={'mview_f':vsip_masin_f,'mview_d':vsip_masin_d} chk, msg = __iscompatible(a,b) if chk: if a.type in vf: vf[a.type](a.vsip,b.vsip) elif a.type in mf: mf[a.type](a.vsip,b.vsip) else: print('Type <:'+a.type+':> not supported for asin') return return b else: print(msg + ' for asin') return def atan(a,b): vf={'vview_f':vsip_vatan_f,'vview_d':vsip_vatan_d} mf={'mview_f':vsip_matan_f,'mview_d':vsip_matan_d} chk, msg = __iscompatible(a,b) if chk: if a.type in vf: vf[a.type](a.vsip,b.vsip) elif a.type in mf: mf[a.type](a.vsip,b.vsip) else: print('Type <:'+a.type+':> not supported for atan') return return b else: print(msg + ' for atan') return def atan2(a,b,c): vf={'vview_f':vsip_vatan2_f,'vview_d':vsip_vatan2_d} mf={'mview_f':vsip_matan2_f,'mview_d':vsip_matan2_d} chk, msg = __iscompatible(a,b) if chk: chk, msg =__iscompatible(a,c) if chk: if a.type in vf: vf[a.type](a.vsip,b.vsip,c.vsip) elif a.type in mf: mf[a.type](a.vsip,b.vsip,c.vsip) else: print('Type <:'+a.type+':> not supported for atan2') return return c else: print(msg + ' for atan2') return def cos(a,b): vf={'vview_f':vsip_vcos_f,'vview_d':vsip_vcos_d} mf={'mview_f':vsip_mcos_f,'mview_d':vsip_mcos_d} chk , msg = __iscompatible(a,b) if chk: if a.type in vf: vf[a.type](a.vsip,b.vsip) elif a.type in mf: mf[a.type](a.vsip,b.vsip) else: print('Type <:'+a.type+':> not supported for cos') return return b else: print(msg + ' for cos') return def cosh(a,b): vf={'vview_f':vsip_vcosh_f,'vview_d':vsip_vcosh_d} mf={'mview_f':vsip_mcosh_f,'mview_d':vsip_mcosh_d} chk, msg = __iscompatible(a,b) if chk: if a.type in vf: vf[a.type](a.vsip,b.vsip) elif a.type in mf: mf[a.type](a.vsip,b.vsip) else: print('Type <:'+a.type+':> not supported for cosh') return return b else: print(msg + ' for cosh') return def exp(a,b): vf={'vview_f':vsip_vexp_f,'vview_d':vsip_vexp_d,\ 'cvview_f':vsip_cvexp_f,'cvview_d':vsip_cvexp_d} mf={'mview_f':vsip_mexp_f,'mview_d':vsip_mexp_d,\ 'cmview_f':vsip_cmexp_f,'cmview_d':vsip_cmexp_d} chk, msg = __iscompatible(a,b) if chk: if a.type in vf: vf[a.type](a.vsip,b.vsip) elif a.type in mf: mf[a.type](a.vsip,b.vsip) else: print('Type <:'+a.type+':> not supported for exp') return return b else: print(msg + ' for exp') return def exp10(a,b): vf={'vview_f':vsip_vexp10_f,'vview_d':vsip_vexp10_d} mf={'mview_f':vsip_mexp10_f,'mview_d':vsip_mexp10_d} chk, msg = __iscompatible(a,b) if chk: if a.type in vf: vf[a.type](a.vsip,b.vsip) elif a.type in mf: mf[a.type](a.vsip,b.vsip) else: print('Type <:'+a.type+':> not supported for exp10') return return b else: print(msg + ' for exp10') return def log(a,b): vf={'vview_f':vsip_vlog_f,'vview_d':vsip_vlog_d,\ 'cvview_f':vsip_cvlog_f,'cvview_d':vsip_cvlog_d} mf={'mview_f':vsip_mlog_f,'mview_d':vsip_mlog_d,\ 'cmview_f':vsip_cmlog_f,'cmview_d':vsip_cmlog_d} chk, msg = __iscompatible(a,b) if chk: if a.type in vf: vf[a.type](a.vsip,b.vsip) elif a.type in mf: mf[a.type](a.vsip,b.vsip) else: print('Type <:'+a.type+':> not supported for log') return return b else: print(msg + ' for log') return def log10(a,b): vf={'vview_f':vsip_vlog10_f,'vview_d':vsip_vlog10_d} mf={'mview_f':vsip_mlog10_f,'mview_d':vsip_mlog10_d} chk, msg = __iscompatible(a,b) if chk: if a.type in vf: vf[a.type](a.vsip,b.vsip) elif a.type in mf: mf[a.type](a.vsip,b.vsip) else: print('Type <:'+a.type+':> not supported for log10') return return b else: print(msg + ' for log10') return def sin(a,b): vf={'vview_f':vsip_vsin_f,'vview_d':vsip_vsin_d} mf={'mview_f':vsip_msin_f,'mview_d':vsip_msin_d} chk, msg = __iscompatible(a,b) if chk: if a.type in vf: vf[a.type](a.vsip,b.vsip) elif a.type in mf: mf[a.type](a.vsip,b.vsip) else: print('Type <:'+a.type+':> not supported for sin') return return b else: print(msg + ' for sin') return def sinh(a,b): vf={'vview_f':vsip_vsinh_f,'vview_d':vsip_vsinh_d} mf={'mview_f':vsip_msinh_f,'mview_d':vsip_msinh_d} chk, msg = __iscompatible(a,b) if chk: if a.type in vf: vf[a.type](a.vsip,b.vsip) elif a.type in mf: mf[a.type](a.vsip,b.vsip) else: print('Type <:'+a.type+':> not supported for sinh') return return b else: print(msg + ' for sinh') return def sqrt(a,b): f={'cmview_dcmview_d':vsip_cmsqrt_d, 'cmview_fcmview_f':vsip_cmsqrt_f, 'cvview_dcvview_d':vsip_cvsqrt_d, 'cvview_fcvview_f':vsip_cvsqrt_f, 'mview_dmview_d':vsip_msqrt_d, 'mview_fmview_f':vsip_msqrt_f, 'vview_dvview_d':vsip_vsqrt_d, 'vview_fvview_f':vsip_vsqrt_f} chk, msg = __iscompatible(a,b) if chk: t=a.type+b.type if t in f: f[t](a.vsip,b.vsip) else: print('Type <:'+t+':> not supported for sinh') return return b else: print(msg + ' for sqrt') return def tan(a,b): vf={'vview_f':vsip_vtan_f,'vview_d':vsip_vtan_d} mf={'mview_f':vsip_mtan_f,'mview_d':vsip_mtan_d} chk, msg = __iscompatible(a,b) if chk: if a.type in vf: vf[a.type](a.vsip,b.vsip) elif a.type in mf: mf[a.type](a.vsip,b.vsip) else: print('Type <:'+a.type+':> not supported for tan') return return b else: print(msg + ' for tan') return def tanh(a,b): vf={'vview_f':vsip_vtanh_f,'vview_d':vsip_vtanh_d} mf={'mview_f':vsip_mtanh_f,'mview_d':vsip_mtanh_d} chk, msg = __iscompatible(a,b) if chk: if a.type in vf: vf[a.type](a.vsip,b.vsip) elif a.type in mf: mf[a.type](a.vsip,b.vsip) else: print('Type <:'+a.type+':> not supported for tanh') return return b else: print(msg + ' for tanh') return <file_sep>/* Created RJudd */ /********************************************************************** // TASP VSIPL Documentation and Code includes no warranty, / // express or implied, including the warranties of merchantability / // and fitness for a particular purpose. No person or organization / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_spline_create_d.c,v 2.2 2009/09/12 23:15:46 judd Exp $ */ #include"vsip.h" #include"VI.h" #include"vsip_splineattributes_d.h" vsip_spline_d *vsip_spline_create_d(vsip_length N){ vsip_spline_d *spline = (vsip_spline_d*)malloc(sizeof(vsip_spline_d)); if(spline){ spline->h = (vsip_scalar_d*)malloc(sizeof(vsip_scalar_d) * N * 5); spline->markings = VSIP_VALID_STRUCTURE_OBJECT; if(spline->h){ spline->b = spline->h + N; spline->u = spline->b + N; spline->v = spline->u + N; spline->z = spline->v + N; } else { free(spline); spline = NULL; } } return spline; } <file_sep># Python vsip module This directory lets one build a python compatible vsip module from the C VSIP library. ## Quick Start From command line > python setup.py build_ext install --user ## Additional information Designed to build for JVSIP with libraries in the standard locations as built with the makefile in the JVSIP home directory. Extension parmaeters listing should be self explanatory for library and include directory expected locations. To build use from the command line > python setup.py build_ext to build and install use from the command line > python setup.py build_ext install --user ### Installation There seem to be continual changes to python and it's environment which have caused problems. I have changed the install so the module goes to a user folder which seems to cause fewer problems. Distutils seems to be deprecated but still around and how to replace it is not clear. I removed the line "language=['c']" from setup.py because it was causing an error in the build process. It still builds OK without that line. I have more trouble on my apple devices. I also build and test on a raspberry pi which seems to be less sensitive. The code works. Getting it installed may require the use of a python knowledgable person. ### Note To use another vsip implementation you need to edit **vsip.i** to include the proper **vsip.h** and to list the functionality available (or desired) with the other implementation. Edit Extension and setup calls as needed ### Requirements * C Compiler * Python installation and distribution utilities module * [SWIG](http://www.swig.org) program installed * Need to have built the JVSIP vsip library (libvsip.a) ### Hints * I use an Apple platform; for linux or microsoft there may be problems I am not aware of. * I use [Homebrew](https://brew.sh) to install and keep up-to-date various packages including SWIG and Python. * On my current configuration I get the Apple installed python if I type **python** or the brew installed python if I type **python2** or **python3**. When calling python be aware of which one you are using when installing. * I still use Homebrew but Apple seems to be installing the latest Python3. To avoid conflicts I use Apples version. Python knowledgable people may want to go some other way. <file_sep>#ifndef _py_jdot_cpy #define _py_jdot_cpy 1 #include<vsip.h> #include<vsip_vviewattributes_f.h> #include<vsip_vviewattributes_d.h> #include<vsip_cvviewattributes_f.h> #include<vsip_cvviewattributes_d.h> vsip_cscalar_f py_rcvjdot_f( const vsip_vview_f* a, const vsip_cvview_f* b) { vsip_length n = a->length; vsip_stride rast = a->block->rstride; vsip_stride cbst = b->block->cstride; vsip_scalar_f *apr = (vsip_scalar_f*) ((a->block->array) + rast * a->offset), *bpr = (vsip_scalar_f*) ((b->block->R->array) + cbst * b->offset); vsip_scalar_f *bpi = (vsip_scalar_f*) ((b->block->I->array) + cbst * b->offset); vsip_stride ast = rast * a->stride, bst = cbst * b->stride; vsip_cscalar_f r; r.r = 0; r.i = 0; while(n-- > 0){ r.r += (*apr * *bpr); r.i -= (*apr * *bpi); apr += ast; bpr += bst; bpi += bst; } return r; } vsip_cscalar_f py_crvjdot_f( const vsip_cvview_f* a, const vsip_vview_f* b) { vsip_length n = a->length; vsip_stride cast = a->block->cstride; vsip_stride rbst = b->block->rstride; vsip_scalar_f *apr = (vsip_scalar_f*) ((a->block->R->array) + cast * a->offset), *bpr = (vsip_scalar_f*) ((b->block->array) + rbst * b->offset); vsip_scalar_f *api = (vsip_scalar_f*) ((a->block->I->array) + cast * a->offset); vsip_stride ast = cast * a->stride, bst = rbst * b->stride; vsip_cscalar_f r; r.r = 0; r.i = 0; while(n-- > 0){ r.r += (*apr * *bpr); r.i += (*api * *bpr); apr += ast; api += ast; bpr += bst; } return r; } vsip_cscalar_d py_rcvjdot_d( const vsip_vview_d* a, const vsip_cvview_d* b) { vsip_length n = a->length; vsip_stride rast = a->block->rstride; vsip_stride cbst = b->block->cstride; vsip_scalar_d *apr = (vsip_scalar_d*) ((a->block->array) + rast * a->offset), *bpr = (vsip_scalar_d*) ((b->block->R->array) + cbst * b->offset); vsip_scalar_d *bpi = (vsip_scalar_d*) ((b->block->I->array) + cbst * b->offset); vsip_stride ast = rast * a->stride, bst = cbst * b->stride; vsip_cscalar_d r; r.r = 0; r.i = 0; while(n-- > 0){ r.r += (*apr * *bpr); r.i -= (*apr * *bpi); apr += ast; bpr += bst; bpi += bst; } return r; } vsip_cscalar_d py_crvjdot_d( const vsip_cvview_d* a, const vsip_vview_d* b) { vsip_length n = a->length; vsip_stride cast = a->block->cstride; vsip_stride rbst = b->block->rstride; vsip_scalar_d *apr = (vsip_scalar_d*) ((a->block->R->array) + cast * a->offset), *bpr = (vsip_scalar_d*) ((b->block->array) + rbst * b->offset); vsip_scalar_d *api = (vsip_scalar_d*) ((a->block->I->array) + cast * a->offset); vsip_stride ast = cast * a->stride, bst = rbst * b->stride; vsip_cscalar_d r; r.r = 0; r.i = 0; while(n-- > 0){ r.r += (*apr * *bpr); r.i += (*api * *bpr); apr += ast; api += ast; bpr += bst; } return r; } #endif <file_sep>// // LUD.swift // SJVsip // // Created by <NAME> on 11/11/17. // Copyright © 2017 JVSIP. All rights reserved. // import Foundation import vsip // MARK: - LU public class LUD { var type: Scalar.Types { return (jVsip?.type)! } fileprivate class lu { var tryVsip : OpaquePointer? var vsip: OpaquePointer { get { return tryVsip! } } let jInit : JVSIP var type : Scalar.Types? init(){ jInit = JVSIP() } } fileprivate class lu_f: lu{ init(_ size: Int){ super.init() type = .f if let lud = vsip_lud_create_f(vsip_length(size)){ self.tryVsip = lud } else { preconditionFailure("Failed to create vsip svd object") } } deinit{ /*if _isDebugAssertConfiguration(){ print("vsip_lud_destroy_f \(jInit.myId.int32Value)") }*/ vsip_lud_destroy_f(self.vsip) } } fileprivate class lu_d: lu{ init(_ size: Int){ super.init() type = .d if let lud = vsip_lud_create_d(vsip_length(size)){ self.tryVsip = lud } else { preconditionFailure("Failed to create vsip svd object") } } deinit{ /*if _isDebugAssertConfiguration(){ print("vsip_lud_destroy_d \(jInit.myId.int32Value)") }*/ vsip_lud_destroy_d(self.vsip) } } fileprivate class clu_f: lu{ init(_ size: Int){ super.init() type = .cf if let lud = vsip_clud_create_f(vsip_length(size)){ self.tryVsip = lud } else { preconditionFailure("Failed to create vsip svd object") } } deinit{ /*if _isDebugAssertConfiguration(){ print("vsip_clud_destroy_f \(jInit.myId.int32Value)") }*/ vsip_clud_destroy_f(self.vsip) } } fileprivate class clu_d: lu{ init(_ size: Int){ super.init() type = .cd if let lud = vsip_clud_create_d(vsip_length(size)){ self.tryVsip = lud } else { preconditionFailure("Failed to create vsip svd object") } } deinit{ /*if _isDebugAssertConfiguration(){ print("vsip_clud_destroy_d \(jInit.myId.int32Value)") }*/ vsip_clud_destroy_d(self.vsip) } } fileprivate let jVsip : lu? fileprivate var vsip: OpaquePointer { get { return (jVsip?.vsip)! } } public init(type: Scalar.Types, size: Int) { switch type { case .f: jVsip = lu_f(size) case .d: jVsip = lu_d(size) case .cf: jVsip = clu_f(size) case .cd: jVsip = clu_d(size) default: preconditionFailure("Type \(type) not supported") } } public func decompose(_ A: Matrix) -> Int{ let t = (self.type, A.type) switch t{ case (.f, .f): return Int(vsip_lud_f(self.vsip, A.vsip)) case (.d, .d): return Int(vsip_lud_d(self.vsip, A.vsip)) case (.cf, .cf): return Int(vsip_clud_f(self.vsip, A.vsip)) case (.cd, .cd): return Int(vsip_clud_d(self.vsip, A.vsip)) default: preconditionFailure("Type \(t) not found for lud decompose") } } public func solve(matOp: vsip_mat_op, _ XB: Matrix) -> Int{ let t = (matOp, self.type, XB.type) switch t { case (VSIP_MAT_NTRANS,.f,.f): return Int(vsip_lusol_f(self.vsip, VSIP_MAT_NTRANS, XB.vsip)) case (VSIP_MAT_NTRANS,.d,.d): return Int(vsip_lusol_d(self.vsip, VSIP_MAT_NTRANS, XB.vsip)) case (VSIP_MAT_NTRANS,.cf,.cf): return Int(vsip_clusol_f(self.vsip, VSIP_MAT_NTRANS, XB.vsip)) case (VSIP_MAT_NTRANS,.cd,.cd): return Int(vsip_clusol_d(self.vsip, VSIP_MAT_NTRANS, XB.vsip)) case (VSIP_MAT_TRANS,.f,.f): return Int(vsip_lusol_f(self.vsip, VSIP_MAT_TRANS, XB.vsip)) case (VSIP_MAT_TRANS,.d,.d): return Int(vsip_lusol_d(self.vsip, VSIP_MAT_TRANS, XB.vsip)) case (VSIP_MAT_HERM,.cf,.cf): return Int(vsip_clusol_f(self.vsip, VSIP_MAT_HERM, XB.vsip)) case (VSIP_MAT_HERM,.cd,.cd): return Int(vsip_clusol_d(self.vsip, VSIP_MAT_HERM, XB.vsip)) default: preconditionFailure("Type \(t) not found for lud solve") } } } <file_sep>//: Using a Dictionary to hold a list of function pointers import Cocoa import vsip import SwiftVsip var unaryVectorOperation: Dictionary<String, (_: Vsip.Vector, _: Vsip.Vector) -> Void > = [:] var binaryVectorOperation: Dictionary<String,(_: Vsip.Vector, _: Vsip.Vector, _: Vsip.Vector) -> Void > = [:] unaryVectorOperation["sin"] = Vsip.sin unaryVectorOperation["cos"] = Vsip.cos unaryVectorOperation["tan"] = Vsip.tan unaryVectorOperation["acos"] = Vsip.acos unaryVectorOperation["asin"] = Vsip.asin binaryVectorOperation["add"] = Vsip.add binaryVectorOperation["sub"] = Vsip.sub binaryVectorOperation["mul"] = Vsip.mul binaryVectorOperation["div"] = Vsip.add //{(x: Vsip.Vector, y: Vsip.Vector) -> Void in Vsip.sin(x, resultsIn: y)} let x = Vsip.Vector(length: 1000, type: .d) let y = x.empty x.ramp(Vsip.Scalar(0.0), increment: Vsip.Scalar(Double.pi/200.0)) unaryVectorOperation["cos"]!(x, y) for i in 0..<x.length { x[i].reald y[i].reald } let z = y.empty unaryVectorOperation["acos"]!(y,z) for i in 0..<y.length { z[i].reald } binaryVectorOperation["div"]!(x,y,z) for item in z { item.reald }<file_sep>/* Created RJudd March 12, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vouter_f.c,v 2.0 2003/02/22 15:19:16 judd Exp $ */ /* April 21, 1998 1,2 to row,col */ /* Modified RJudd Feb 14, 1999 */ /* to fix cmbind */ /* Removed Development Mode RJudd Sept 00 */ #include"vsip.h" #include"vsip_mviewattributes_f.h" #include"vsip_vviewattributes_f.h" void (vsip_vouter_f)( vsip_scalar_f alpha, const vsip_vview_f* a, const vsip_vview_f* b, const vsip_mview_f* R) { /* R_ij = a_i*b_j */ { /* register */ vsip_length n = a->length, m = b->length; vsip_scalar_f *a_p = a->block->array + a->offset * a->block->rstride; vsip_length i,j; vsip_stride Rrst = R->row_stride * R->block->rstride, bst = b->stride * b->block->rstride, ast = a->stride * a->block->rstride; vsip_offset bo = b->offset * b->block->rstride, Ro = R->offset * R->block->rstride, Rco = R->col_stride * R->block->rstride; for(i=0; i<n; i++){ vsip_scalar_f *R_p = R->block->array + Ro + i * Rco, *b_p = b->block->array + bo; vsip_scalar_f temp = *a_p * alpha; for(j=0; j<m; j++){ *R_p = temp * *b_p; R_p += Rrst; b_p += bst; } a_p += ast; } } return; } <file_sep>/* Created by RJudd August 3, 2002 */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_ccfftip_d.h,v 2.2 2007/04/16 16:22:25 judd Exp $ */ #ifndef VI_CCFFTIP_D_H #define VI_CCFFTIP_D_H /******************************************************************/ /* init fft to x */ static void init_fft_d(void *tx,void* tfft){ vsip_cvview_d *x = (vsip_cvview_d*) tx; vsip_fft_d *fft = (vsip_fft_d*) tfft; fft->x = x; fft->stage =0; return; } /* Using an already created temp data space */ /* and index vector sort an FFT output */ /* VI_sort_copy_d.c */ /*========================================================*/ static void VI_sort_copy_d(void* tfft){ vsip_fft_d* fft = (vsip_fft_d*) tfft; vsip_scalar_vi *x = fft->index; vsip_cvview_d *a = fft->x; vsip_cvview_d *r = fft->temp; vsip_length n = fft->N; vsip_stride cast = a->block->cstride; vsip_stride ast = cast * a->stride; vsip_stride rst = r->block->cstride; vsip_scalar_d *apr = (vsip_scalar_d*) ((a->block->R->array) + cast * a->offset), *rpr = (vsip_scalar_d*) r->block->R->array ; vsip_scalar_d *api = (vsip_scalar_d*) ((a->block->I->array) + cast * a->offset), *rpi = (vsip_scalar_d*) r->block->I->array; vsip_scalar_d *apr2 = apr, *rpr2 = rpr; vsip_scalar_d *api2 = api, *rpi2 = rpi; vsip_stride xinc = 0; while(n-- >0){ xinc = *x * ast; *rpr = *(apr + xinc); *rpi = *(api + xinc); rpr += rst; rpi += rst; x++; } n = fft->N; while(n-- >0){ *apr2 = *rpr2; *api2 = *rpi2; apr2 += ast; api2 += ast; rpr2 += rst; rpi2 += rst; } return; } static void VI_ccfftip_d(const vsip_fft_d* fft, const vsip_cvview_d *x) { void *x_v = (void*) x; void* fft_v = (void*)fft; init_fft_d(x_v,fft_v); if(fft->dft == 1){ VI_dft_d(fft_v); }else{ VI_p0pF_d(fft_v); VI_sort_copy_d(fft_v); } if (fft->scale != 1) vsip_rscvmul_d(fft->scale,x,x); return; } #endif <file_sep>import pyJvsip as pjv from math import pi as pi n=1000 x=pjv.create('vview_d',n).ramp(0,2*pi/float(n)) c=pjv.cos(x,x.empty) cinvClip=pjv.invclip(c,-.6,0.0,.6,-.7,.7,c.empty) <file_sep>/* Created RJudd September 16, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_blockcreate_d.c,v 2.1 2006/06/08 22:19:26 judd Exp $ */ #include"vsip.h" #include"vsip_blockattributes_d.h" vsip_block_d* (vsip_blockcreate_d)( vsip_length N, vsip_memory_hint h) { vsip_block_d* b = (vsip_block_d*)malloc(sizeof(vsip_block_d)); if(b != NULL){ b->array = (vsip_scalar_d*)malloc(N * sizeof(vsip_scalar_d)); if(NULL == b->array){ free((void*)b); b = (vsip_block_d*)NULL; } else { b->kind = VSIP_VSIPL_BLOCK; b->admit = VSIP_ADMITTED_BLOCK; b->markings = VSIP_VALID_STRUCTURE_OBJECT; b->size = N; b->rstride = 1; b->bindings = 0; b->hint = h; b->parent = (vsip_cblock_d*)NULL; } } return b; } <file_sep>#* Created RJudd */ #* pyJvsip version of c_VSIP_example example1 import pyJvsip as pv N=8 A = pv.create('vview_f',N).ramp(0,1) B = A.empty.fill(5.0) C = A.empty.fill(0.0) print('A = ');A.mprint('%2.0f') print('B = ');B.mprint('%2.0f') pv.add(A,B,C) print('C = A+B'); print('C = ');C.mprint('%2.0f') <file_sep>// // utility.swift // SJVsip // // Created by <NAME> on 11/4/17. // Copyright © 2017 JVSIP. All rights reserved. // import Foundation import vsip public func scalarString(_ format : String, value : Scalar) -> String{ var retval = "" switch value.type{ case .f: let fmt = "%" + format + "f" retval = String(format: fmt, value.realf) case .d: let fmt = "%" + format + "f" retval = String(format: fmt, value.reald) case .cf: let fmt1 = "%" + format + "f" let fmt2 = "%+" + format + "f" let r = String(format: fmt1, value.realf) let i = String(format: fmt2, value.imagf) retval = r + i + "i" case .cd: let fmt1 = "%" + format + "f" let fmt2 = "%+" + format + "f" let r = String(format: fmt1, value.reald) let i = String(format: fmt2, value.imagd) retval = r + i + "i" case .mi: let fmt1 = "(%d," let fmt2 = " %d)" let r = String(format: fmt1, value.row) let c = String(format: fmt2, value.col) retval = r + c default: let fmt = "%d" retval = String(format: fmt, value.int) } return retval } public func formatFmt(_ fmt: String) -> String{ var retval = "" func charCheck(_ char: Character) -> Bool { let validChars = "0123456789." for item in validChars { if char == item { return true } } return false } for char in fmt{ if charCheck(char){ retval.append(char) } } return retval } public class SJvsip { public static func normFro(view: Vector) -> Scalar { switch view.type { case .f: return sumsqval(view).sqrt case .d: return sumsqval(view).sqrt case.cf: return (sumsqval(view.real) + sumsqval(view.imag)).sqrt case.cd: return (sumsqval(view.real) + sumsqval(view.imag)).sqrt default: preconditionFailure("normFro not supported for this view") } } public static func normFro(view: Matrix) -> Scalar { switch view.type { case .f: return sumsqval(view).sqrt case .d: return sumsqval(view).sqrt case.cf: return (sumsqval(view.real) + sumsqval(view.imag)).sqrt case.cd: return (sumsqval(view.real) + sumsqval(view.imag)).sqrt default: preconditionFailure("normFro not supported for this view") } } } <file_sep>import pyJvsip as pv from matplotlib import pyplot as plt # Convert data to decibel def VU_vfrdB(a,rng): N_len=int(a.length) ca=a.otherEmpty.fill(0.0) fftType={'cvview_d':'ccfftip_d','cvview_f':'ccfftip_f'}[ca.type] fft = pv.FFT(fftType,N_len,1,pv.VSIP_FFT_FWD,0,0) ra = ca.realview ia = ca.imagview ta = a.cloneview s = ta.stride pv.copy(a,ra) fft.dft(ca) pv.cmagsq(ca,ra) maxv = ra.maxval minv = maxv * rng pv.clip(ra,minv,maxv,minv,maxv,ra) Nlen = int(N_len/2) if N_len%2: ta.putlength(Nlen+1) ra.putlength(Nlen+1) ta.putoffset(Nlen * s) pv.copy(ra,ta) ra.putlength(Nlen) ta.putlength(Nlen) ta.putoffset(a.offset) ra.putoffset(Nlen+1) pv.copy(ra,ta) else : pv.copy(ra,ta) ta.putlength(Nlen) a.putlength(Nlen) ta.putoffset(Nlen * s) pv.swap(ta,a) a.putlength(N_len) a.log10 a *= 10.0 # write vector data to file fname def VU_vwritexyg(fmt,x,y,fname): N=y.length of = open(fname,'w') of.write('%d\n'%N) for i in range(N): of.write(fmt%(x[i],y[i])) of.close() # read vector data from file fname; counterpart of vwritexy def VU_vfreadxy(fname): fd = open(fname,'r') N=int(fd.readline()) x=pv.create('vview_f',N) y=x.empty for i in range(N): ln=fd.readline().partition(' ') x[i]=float(ln[0]) y[i]=float(ln[2]) fd.close() return(x,y) N_data = 24576 dec1 = 1 dec3 = 3 kernel=pv.create('vview_f',128).kaiser(15.0) r_state = pv.Rand('NPRNG',11) data = pv.create('vview_f', 2 * N_data) noise = pv.create('vview_f', 3 * N_data) avg = pv.create('vview_f', 4 * N_data) data.putlength(int((N_data-1)/dec1)+1) avg.putlength(int((N_data-1)/dec1)+1) data.putstride(2) avg.putstride(4) noise.putlength(N_data) noise.putstride(3) conv = pv.CONV('conv1d_f',kernel,pv.VSIP_NONSYM, N_data,dec1,pv.VSIP_SUPPORT_SAME,0,0) fir = pv.FIR('fir_f', kernel,'NONE', N_data,dec1,'NO') avg.fill(0.0) for i in range(10): r_state.randn(noise) conv.convolve(noise,data) VU_vfrdB(data,1e-13) pv.ma(data,0.1,avg,avg) N_len = avg.length x = pv.create('vview_f', N_len).ramp(-.5,1.0/float(N_len-1)) VU_vwritexyg("%8.6f %8.6f\n",x,avg,"conv_dec1"); avg.fill(0.0) for i in range(10): r_state.randn(noise) fir.flt(noise,data) VU_vfrdB(data,1e-13) pv.ma(data,0.1,avg,avg) N_len = avg.length x = pv.create('vview_f', N_len).ramp(-.5,1.0/float(N_len-1)) VU_vwritexyg("%8.6f %8.6f\n",x,avg,"fir_dec1") conv = pv.CONV('conv1d_f', kernel,pv.VSIP_NONSYM, N_data,dec3,pv.VSIP_SUPPORT_SAME,0,0); fir = pv.FIR('fir_f', kernel,'NONE', N_data,dec3,'NO') data.putlength(int((N_data-1)/dec3) + 1) avg.putlength(int((N_data-1)/dec3) + 1) avg.fill(0.0) for i in range(10): r_state.randn(noise) conv.convolve(noise,data); VU_vfrdB(data,1e-13); pv.ma(data,0.1,avg,avg) N_len = avg.length x = pv.create('vview_f', N_len).ramp(-.5,1.0/float(N_len-1)) VU_vwritexyg("%8.6f %8.6f\n", x, avg,"conv_dec3"); avg.fill(0.0) for i in range(10): r_state.randn(noise) fir.flt(noise,data) VU_vfrdB(data,1e-13); pv.ma(data,0.1,avg,avg) N_len = avg.length x = pv.create('vview_f', N_len) x.ramp(-.5,1.0/float(N_len-1)) VU_vwritexyg("%8.6f %8.6f\n", x, avg,"fir_dec3") N_len = kernel.length x = pv.create('vview_f', N_len) x.ramp(0.0,1.0) VU_vwritexyg("%8.6f %8.6f\n", x,kernel,"kaiser_window") x.ramp(-.5,1.0/float(N_len-1)) VU_vfrdB(kernel,1e-20) VU_vwritexyg("%8.6f %8.6f\n", x,kernel,"Freq_Resp_Kaiser") plt.clf() x,y=VU_vfreadxy('fir_dec1') plt.plot(x.list,y.list) x,y=VU_vfreadxy('conv_dec1') plt.hold=True plt.plot(x.list,y.list) plt.ylabel('dB');plt.xlabel('F/Fs');plt.title('FIR versus Convolution For Decimation 1') fig=plt.gcf() fig.set_size_inches(5,2) fig.set_dpi(300) plt.hold=False plt.savefig('FirConvOne.eps',bbox_inches='tight') plt.clf() x,y=VU_vfreadxy('fir_dec3') plt.plot(x.list,y.list,'r');plt.hold=True x,y=VU_vfreadxy('conv_dec3') plt.plot(x.list,y.list,'g') plt.ylabel('dB');plt.xlabel('F/Fs');plt.title('FIR versus Convolution For Decimation 3') fig=plt.gcf() fig.set_size_inches(5,2) fig.set_dpi(300) plt.hold=False plt.savefig('FirConvTwo.eps',bbox_inches='tight') plt.clf() x,y=VU_vfreadxy('kaiser_window') plt.plot(x.list,y.list,'b.') plt.hold=True plt.plot(x.list,y.list,'r-') fig=plt.gcf() fig.set_size_inches(5,1.) fig.set_dpi(300) plt.ylabel('Magnitude');plt.xlabel('Sample Point');plt.title('Kaiser Window') plt.savefig('kaiserWindow.eps',bbox_inches='tight') plt.clf() x,y=VU_vfreadxy('Freq_Resp_Kaiser') plt.plot(x.list,y.list,'c.') plt.hold=True plt.plot(x.list,y.list,'r-') fig=plt.gcf() fig.set_size_inches(5,1.) fig.set_dpi(300) plt.ylabel('dB');plt.xlabel('F/Fs');plt.title('Kaiser Window Frequency Response') plt.savefig('FreqRespKaiser.eps',bbox_inches='tight') <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: msq_d.h,v 2.0 2003/02/22 15:23:26 judd Exp $ */ #include"VU_mprintm_d.include" static void msq_d(void){ printf("\n*********\nTEST msq_d\n"); { vsip_mview_d *M = vsip_mcreate_d(4,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *m1 = vsip_msubview_d(M,0,0,2,3); vsip_mview_d *m2 = vsip_msubview_d(M,2,0,2,3); vsip_mview_d *chk = vsip_mcreate_d(2,3,VSIP_COL,VSIP_MEM_NONE); vsip_scalar_d data[6]; vsip_block_d *block = vsip_blockbind_d(data,6,VSIP_MEM_NONE); vsip_mview_d *ans = vsip_mbind_d(block,0,1,2,2,3); vsip_vview_d *vans = vsip_vbind_d(block,0,1,6); vsip_blockadmit_d(block,VSIP_FALSE); vsip_vramp_d(1,.5,vans); vsip_mcopy_d_d(ans,m1); vsip_blockrelease_d(block,VSIP_TRUE); data[0] = data[0] * data[0]; data[1] = data[1] * data[1]; data[2] = data[2] * data[2]; data[3] = data[3] * data[3]; data[4] = data[4] * data[4]; data[5] = data[5] * data[5]; vsip_blockadmit_d(block,VSIP_TRUE); vsip_msq_d(m1,m2); printf("msq_d(a,b)"); printf("matrix a\n"); VU_mprintm_d("8.6",m1); printf("matrix b\n"); VU_mprintm_d("8.6",m2); printf("right answer\n"); VU_mprintm_d("8.4",ans); vsip_msub_d(m2,ans,chk); vsip_mclip_d(chk,0.0001,0.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); printf("in place\n"); vsip_msq_d(m1,m1); vsip_msub_d(m1,ans,chk); vsip_mclip_d(chk,0.0001,0.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_mdestroy_d(ans); vsip_valldestroy_d(vans); vsip_mdestroy_d(m2); vsip_mdestroy_d(m1); vsip_malldestroy_d(M); vsip_malldestroy_d(chk); } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmprod_d.h,v 2.1 2006/04/09 19:28:53 judd Exp $ */ #include"VU_cmprintm_d.include" static void cmprod_d(void){ printf("********\nTEST cmprod_d\n"); { vsip_scalar_d datal_r[] = {1, 2.0, 3.0, 4, 5.0, 5, .1, .2, .3, .4, 4, 3.0, 2.0, 0, -1.0}; vsip_scalar_d datal_i[] = {9, 3.0, 2.0, 4.3, 3.2, 5, .1, 1.2, .3, 1.4, 3, 2.0, -2.1, 0.1, 1.0}; vsip_scalar_d datar_r[] = { .1, .2, .3, .4, 1.0, 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 2.4, -1.1, -1.2, -1.3, -1.4, 2.1, 2.2, 2.3, 3.4}; vsip_scalar_d datar_i[] = { 1.1, 5.2, 3.3, 1.4, 2.1, 1.0, 1.2, 1.2, 4.1, 3.0, 2.3, 2.3, 1.1, -1.2, -1.3, 1.0, 1.0, 2.2, -2.3, 3.4}; vsip_scalar_d ans_data_r[] = { -17.27, -41.34, -7.85, -13.04, -7.07, -10.83, -1.88, -8.35, 5.5, -7.08, 2.06, 1.63}; vsip_scalar_d ans_data_i[] = { 40.43, 35.62, 10.73, 51.06, 5.55, -0.39, 0.66, 8.03, 17.78, 27.86, 24.34, 12.42}; vsip_cblock_d *blockl = vsip_cblockbind_d(datal_r,datal_i,15,VSIP_MEM_NONE); vsip_cblock_d *blockr = vsip_cblockbind_d(datar_r,datar_i,20,VSIP_MEM_NONE); vsip_cblock_d *block_ans = vsip_cblockbind_d(ans_data_r,ans_data_i,12,VSIP_MEM_NONE); vsip_cblock_d *block = vsip_cblockcreate_d(70,VSIP_MEM_NONE); vsip_cmview_d *ml = vsip_cmbind_d(blockl,0,5,3,1,5); vsip_cmview_d *mr = vsip_cmbind_d(blockr,0,4,5,1,4); vsip_cmview_d *ans = vsip_cmbind_d(block_ans,0,4,3,1,4); vsip_cmview_d *a = vsip_cmbind_d(block,15,-1,3,-3,5); vsip_cmview_d *b = vsip_cmbind_d(block,50,-2,5,-10,4); vsip_cmview_d *c = vsip_cmbind_d(block,49,-8,3,-2,4); vsip_cmview_d *chk = vsip_cmcreate_d(3,4,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *chk_r = vsip_mrealview_d(chk); vsip_cblockadmit_d(blockl,VSIP_TRUE); vsip_cblockadmit_d(blockr,VSIP_TRUE); vsip_cblockadmit_d(block_ans,VSIP_TRUE); vsip_cmcopy_d_d(ml,a); vsip_cmcopy_d_d(mr,b); vsip_cmprod_d(a,b,c); printf("vsip_cmprod_d(a,b,c)\n"); printf("a\n"); VU_cmprintm_d("6.4",a); printf("b\n"); VU_cmprintm_d("6.4",b); printf("c\n"); VU_cmprintm_d("6.4",c); printf("right answer\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(c,ans,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); { /* ccc */ vsip_cmview_d *a1 = vsip_cmcreate_d(3,5,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_d *b1 = vsip_cmcreate_d(5,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_d *c1 = vsip_cmcreate_d(3,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmcopy_d_d(a,a1); vsip_cmcopy_d_d(b,b1); vsip_cmprod_d(a1,b1,c1); printf("c1\n"); VU_cmprintm_d("6.4",c1); printf("right answer\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(c1,ans,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(a1); vsip_cmalldestroy_d(b1); vsip_cmalldestroy_d(c1); } { /* ccr */ vsip_cmview_d *a1 = vsip_cmcreate_d(3,5,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_d *b1 = vsip_cmcreate_d(5,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_d *c1 = vsip_cmcreate_d(3,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmcopy_d_d(a,a1); vsip_cmcopy_d_d(b,b1); vsip_cmprod_d(a1,b1,c1); printf("c1\n"); VU_cmprintm_d("6.4",c1); printf("right answer\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(c1,ans,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(a1); vsip_cmalldestroy_d(b1); vsip_cmalldestroy_d(c1); } { /* crc */ vsip_cmview_d *a1 = vsip_cmcreate_d(3,5,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_d *b1 = vsip_cmcreate_d(5,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *c1 = vsip_cmcreate_d(3,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmcopy_d_d(a,a1); vsip_cmcopy_d_d(b,b1); vsip_cmprod_d(a1,b1,c1); printf("c1\n"); VU_cmprintm_d("6.4",c1); printf("right answer\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(c1,ans,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(a1); vsip_cmalldestroy_d(b1); vsip_cmalldestroy_d(c1); } { /* crr */ vsip_cmview_d *a1 = vsip_cmcreate_d(3,5,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_d *b1 = vsip_cmcreate_d(5,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *c1 = vsip_cmcreate_d(3,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmcopy_d_d(a,a1); vsip_cmcopy_d_d(b,b1); vsip_cmprod_d(a1,b1,c1); printf("c1\n"); VU_cmprintm_d("6.4",c1); printf("right answer\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(c1,ans,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(a1); vsip_cmalldestroy_d(b1); vsip_cmalldestroy_d(c1); } { /* rcc */ vsip_cmview_d *a1 = vsip_cmcreate_d(3,5,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *b1 = vsip_cmcreate_d(5,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_d *c1 = vsip_cmcreate_d(3,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmcopy_d_d(a,a1); vsip_cmcopy_d_d(b,b1); vsip_cmprod_d(a1,b1,c1); printf("c1\n"); VU_cmprintm_d("6.4",c1); printf("right answer\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(c1,ans,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(a1); vsip_cmalldestroy_d(b1); vsip_cmalldestroy_d(c1); } { /* rcr */ vsip_cmview_d *a1 = vsip_cmcreate_d(3,5,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *b1 = vsip_cmcreate_d(5,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_d *c1 = vsip_cmcreate_d(3,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmcopy_d_d(a,a1); vsip_cmcopy_d_d(b,b1); vsip_cmprod_d(a1,b1,c1); printf("c1\n"); VU_cmprintm_d("6.4",c1); printf("right answer\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(c1,ans,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(a1); vsip_cmalldestroy_d(b1); vsip_cmalldestroy_d(c1); } { /* rrc */ vsip_cmview_d *a1 = vsip_cmcreate_d(3,5,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *b1 = vsip_cmcreate_d(5,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *c1 = vsip_cmcreate_d(3,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmcopy_d_d(a,a1); vsip_cmcopy_d_d(b,b1); vsip_cmprod_d(a1,b1,c1); printf("c1\n"); VU_cmprintm_d("6.4",c1); printf("right answer\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(c1,ans,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(a1); vsip_cmalldestroy_d(b1); vsip_cmalldestroy_d(c1); } { /* rrr */ vsip_cmview_d *a1 = vsip_cmcreate_d(3,5,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *b1 = vsip_cmcreate_d(5,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *c1 = vsip_cmcreate_d(3,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmcopy_d_d(a,a1); vsip_cmcopy_d_d(b,b1); vsip_cmprod_d(a1,b1,c1); printf("c1\n"); VU_cmprintm_d("6.4",c1); printf("right answer\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(c1,ans,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(a1); vsip_cmalldestroy_d(b1); vsip_cmalldestroy_d(c1); } vsip_cmalldestroy_d(ml); vsip_cmalldestroy_d(mr); vsip_cmdestroy_d(a); vsip_cmdestroy_d(b); vsip_cmalldestroy_d(c); vsip_cmalldestroy_d(ans); vsip_mdestroy_d(chk_r); vsip_cmalldestroy_d(chk); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_offset_uc.h,v 2.1 2007/04/18 17:05:56 judd Exp $ */ static void get_put_offset_uc(void){ printf("********\nTEST get_put_offset_uc\n"); { vsip_offset ivo = 3; vsip_stride ivs = 0; vsip_length ivl = 3; vsip_offset jvo = 2; vsip_stride irs = 0, ics = 0; vsip_length irl = 2, icl = 3; vsip_stride ixs = 0, iys = 0, izs = 0; vsip_length ixl = 2, iyl = 3, izl = 4; vsip_block_uc *b = vsip_blockcreate_uc(80,VSIP_MEM_NONE); vsip_vview_uc *v = vsip_vbind_uc(b,ivo,ivs,ivl); vsip_mview_uc *m = vsip_mbind_uc(b,ivo,ics,icl,irs,irl); vsip_tview_uc *t = vsip_tbind_uc(b,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_offset s; printf("test vgetoffset_uc\n"); fflush(stdout); { s = vsip_vgetoffset_uc(v); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputoffset_uc\n"); fflush(stdout); { vsip_vputoffset_uc(v,jvo); s = vsip_vgetoffset_uc(v); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /*************************************************************************/ printf("test mgetoffset_uc\n"); fflush(stdout); { s = vsip_mgetoffset_uc(m); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputoffset_uc\n"); fflush(stdout); { vsip_mputoffset_uc(m,jvo); s = vsip_mgetoffset_uc(m); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /*************************************************************************/ printf("test tgetoffset_uc\n"); fflush(stdout); { s = vsip_tgetoffset_uc(t); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputoffset_uc\n"); fflush(stdout); { vsip_tputoffset_uc(t,jvo); s = vsip_tgetoffset_uc(t); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } vsip_vdestroy_uc(v); vsip_mdestroy_uc(m); vsip_talldestroy_uc(t); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mbind_uc.c,v 2.0 2003/02/22 15:18:54 judd Exp $ */ #include"vsip.h" #include"vsip_mviewattributes_uc.h" vsip_mview_uc* (vsip_mbind_uc)( const vsip_block_uc* block, vsip_offset offset, vsip_stride col_stride, vsip_length col_length, vsip_stride row_stride, vsip_length row_length) { { vsip_mview_uc* mview_uc = (vsip_mview_uc*)malloc(sizeof(vsip_mview_uc)); if(mview_uc != NULL){ mview_uc->block = (vsip_block_uc*)block; mview_uc->offset = offset; mview_uc->col_stride = col_stride; mview_uc->row_stride = row_stride; mview_uc->col_length = col_length; mview_uc->row_length = row_length; mview_uc->markings = VSIP_VALID_STRUCTURE_OBJECT; } return mview_uc; } } <file_sep>/* Created RJudd November 2, 2002 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_cblockadmit_f_as.h,v 2.0 2003/02/22 15:18:28 judd Exp $ */ /* VI_cblockadmit_f always split */ { if(b->Rp == (vsip_scalar_f*)NULL) blockadmit = 1; /* fail if no data array */ else if(b->kind != VSIP_USER_BLOCK) blockadmit = 1; /* fail if not a user block */ else { b->admit = VSIP_ADMITTED_BLOCK; b->a_scalar.r = 0.0; b->a_scalar.i = 0.0; b->a_zero.r = 0.0; b->a_zero.i = 0.0; b->a_one.r = 1.0; b->a_one.i = 0.0; b->a_imag_one.r = 0.0; b->a_imag_one.i = 1.0; blockadmit = 0; /* return zero on success */ if(b->Ip == (vsip_scalar_f*)NULL){ /* must be interleaved */ /* copy needed; care about update flag */ b->R->array = b->r_data; b->I->array = b->i_data; if(update){ /* need to copy */ vsip_length n = b->size; vsip_scalar_f *ptr_data = b->Rp, *ptr_Rarray = b->R->array, *ptr_Iarray = b->I->array; while(n-- > 0){ *ptr_Rarray = *ptr_data; ptr_Rarray++; ptr_data++; *ptr_Iarray = *ptr_data; ptr_Iarray++; ptr_data++; } } } else { /* must be split */ /* no copy needed; don't care about update flag, always true */ b->R->array = b->Rp; b->I->array = b->Ip; } } } <file_sep>/* Created By RJudd October 14, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_rcfftop_create_d_fftw.h,v 2.0 2003/02/22 15:18:33 judd Exp $ */ /* real to complex fft */ #ifndef _VI_RCFFTOP_CREATE_D_FFTW_H #define _VI_RCFFTOP_CREATE_D_FFTW_H /* selectively include functions in fftw_obj */ #define __VSIPL_FFTWOBJ_INIT #define __VSIPL_FFTWOBJ_FIN #include"VI_vrealview_d.h" #include"VI_vimagview_d.h" #include"VI_vramp_d.h" #include"VI_vcos_d.h" #include"VI_vsin_d.h" #include"VI_fftw_obj.h" #define VI_ft_d_PI 3.1415926535897932384626433 /* For this function N is required to be even */ vsip_fft_d* vsip_rcfftop_create_d( vsip_length N, vsip_scalar_d scale, unsigned int ntimes, vsip_alg_hint hint) { vsip_fft_d *fft = (vsip_fft_d*) malloc(sizeof(vsip_fft_d)); vsipl_fftw_obj *obj; fftw_direction fftw_dir = FFTW_FORWARD; int flags = (hint == VSIP_ALG_TIME) ? FFTW_MEASURE : FFTW_ESTIMATE; int init; if(fft == NULL) return (vsip_fft_d*) NULL; fft->N = N/2; fft->scale = scale; fft->d = VSIP_FFT_FWD; fft->pn = NULL; fft->p0 = NULL; fft->pF = NULL; fft->wt = (vsip_cvview_d*)NULL; fft->index = (NULL); fft->hint = hint; fft->ntimes = ntimes; fft->type = VSIP_RCFFTOP; fft->temp = vsip_cvcreate_d(fft->N,VSIP_MEM_NONE); init = vsipl_fftwobj_init(&obj,fftw_dir,fft->N,flags); if((init!=0) || (fft->temp == (vsip_cvview_d*)NULL)){ if(init != 0) vsipl_fftwobj_fin(obj); if(fft->temp != NULL) vsip_cvdestroy_d(fft->temp); free(fft); return (vsip_fft_d*)NULL; } fft->ext_fft_obj = (void*)obj; { vsip_vview_d wt1,wt2; vsip_vview_d *wtR = VI_vrealview_d(fft->temp,&wt1); vsip_vview_d *wtI = VI_vimagview_d(fft->temp,&wt2); VI_vramp_d((vsip_scalar_d)0,(vsip_scalar_d)VI_ft_d_PI/fft->N,wtR); VI_vsin_d(wtR,wtI); VI_vcos_d(wtR,wtR); } return fft; } #endif /* _VI_RCFFTOP_CREATE_D_FFTW_H */ <file_sep># Python for JVSIP This directory contains python related development code for the JVSIP VSIP Library. The primary content is in the **vsip** and **pyJvsip** directory. The **pyJvsip** module needs the **vsip** module to build. Everything here is basically a *proof of concept* for C VSIPL with python but the pyJvsip module has become fairly complete and I don't run into bugs very often. ## Python notebooks Much of this implementations documentation and examples run in python notebooks. Since I started this notebooks have undergone many changes and some things may be stale. Currently to start a notebook I do > jupyter notebook then navigate around till I find a notebook I am interested in running. In the **jvsip** root directory you will find the **doc/notebooks** directory. These are generally more instructive. ## Environment I run on an Apple environment with an **Xcode** development environment. I also use [Homebrew](https://brew.sh) to install various tools available including *python2* and *python3* and [SWIG](http://www.swig.org) .<file_sep>from math import pi,ceil,log,pow import pyJvsip as pv from localmax import * from frefine import * from matplotlib import pyplot def faffine(M,wp,ws,Kp,Ks,eta_p,eta_s): """ Usage: ans= faffine(M,wp,ws,Kp,Ks,eta_p,eta_s) h=ans[0], rs=ans[1],del_p=ans[2], del_s=ans[3] Notes from matlab code below. % [h,rs,del_p,del_s] = faffine(M,wp,ws,Kp,Ks,eta_p,eta_s); % Lowpass linear phase FIR filter design by a REMEZ-like algorithm % h : filter of length 2*M+1 % rs : reference set upon convergence % del_p : passband error, del_p = Kp * del + eta_p % del_s : stopband error, del_s = Kp * del + eta_s % wp,ws : band edges % EXAMPLE % M = 17; % wp = 0.30*pi; % ws = 0.37*pi; % Kp = 0; Ks = 1; eta_p = .05; eta_s = 0; % [h,rs,del_p,del_s] = faffine(M,wp,ws,Kp,Ks,eta_p,eta_s); % author: <NAME> % % required subprograms : frefine.m, localmax.m """ # ------------------ initialize some constants ------------------------------ L = int(pow(2,ceil(log(10*M,2)))) SN = 1e-7 w = pv.create('vview_d',int(L+1)).ramp(0,pi/L) S = int(M + 2) np = round(S*(wp+ws)/(2*pi)) np = int(max(np, 1)) if np == S: np = np - 1 ns = int(S - np) r_pass =pv.create('vview_d',np); r_stop=pv.create('vview_d',ns) if np > 1: r_pass.ramp(0,wp/(np-1)) else: r_pass[0] = wp if ns > 1: r_stop.ramp(ws,(pi-ws)/(ns-1)) else: r_stop[0] = ws rs= pv.create('vview_d',S);rs[0:np]=r_pass; rs[np:]=r_stop #initial ref. set D = pv.create('vview_d',int(np+ns)).fill(0.0);D[:np].fill(1.0) sp = pv.create('vview_d',int(S)).fill(0.0); if np % 2: sp[:int(np):2].fill(-1.0);sp[1:int(np):2].fill(1.0) else: sp[:int(np):2].fill(1.0);sp[1:int(np):2].fill(-1.0) ss = sp.empty.fill(0.0); ss[int(np):int(S):2].fill(1.0);ss[int(np)+1:int(S):2].fill(-1.0) Z = int(2*(L+1-M)-3) # begin looping Err = 1 while Err > SN: # --------------- calculate cosine coefficients --------------------------- x1=pv.create('mview_d',M+4,M+4).fill(0.0) x1[M+3,M+3]=-Ks; x1[M+3,M+2]=1.0;x1[M+2,M+1]=1;x1[M+2,M+3]=-Kp x1[:S,:M+1]=rs.outer(pv.create('vview_d',M+1).ramp(0,1)).cos x1.colview(M+1)[:S]=sp.neg; x1.colview(M+2)[:S]=ss.neg; x2=pv.create('vview_d',D.length+2) x2[:D.length]=D;x2[D.length+1]=eta_s;x2[D.length]=eta_p x = x1.luSolve(x2) a = x[0:M+1].copy del_p = x[M+1] del_s = x[M+2] del_ = x[M+3] if (del_p<0) and (del_s<0): print('both del_p and del_s are negative!') elif del_s < 0: # set del_s equal to 0 print('del_s < 0') x1[:S,:M+1]=rs.outer(pv.create('vview_d',M+1).ramp(0,1)).cos x1.colview(M+1)[:S]=sp.neg; x = x1[:S,:M+2].luSolve(D.copy) a = x[0:M+1].copy del_p = x[M+1] del_s = 0; elif del_p < 0: # set del_p equal to 0 print('del_p < 0') x1[:S,:M+1]=rs.outer(pv.create('vview_d',M+1).ramp(0,1)).cos x1.colview(M+1)[:S]=ss.neg; x = x1[:S,:M+2].luSolve(D.copy) a = x[0:M+1].copy del_p = 0; del_s = x[M+1]; A=pv.create('vview_d',a.length*2-1+Z).fill(0.0) A[:a.length]=a; A[1:a.length] *= 0.5; A[a.length+Z:]=A.block.bind(a.length-1,-1,a.length-1) Ac=A.rcfft A=Ac.realview.copy # --------------- determine new reference set----------------------------- # Below neg done in place so undo is required # Could use A.copy.neg instead but pay a create/destroy penalty lmAn=localmax(A.neg);lmA=localmax(A.neg) ri=pv.create('vview_d',lmA.length+lmAn.length).fill(0.0) ri[:lmA.length]=lmA;ri[lmA.length:]=lmAn;ri.sortip() rs=frefine(a,ri*(pi/float(L))) rsp=rs.gather(rs.llt(wp).indexbool) rss=rs.gather(rs.lgt(ws).indexbool) rs=pv.create(rsp.type,rsp.length+rss.length+2).fill(0.0) rs[:rsp.length]=rsp;rs[rsp.length:][0]=wp;rs[rsp.length:][1]=ws; rs[rsp.length+2:]=rss np = rsp.length+1 ns = rss.length+1 D = pv.create('vview_d',np+ns).fill(0.0);D[:np].fill(1.0) sp = D.empty.fill(0.0) if np % 2: sp[:int(np):2].fill(-1.0);sp[1:int(np):2].fill(1.0) else: sp[:int(np):2].fill(1.0);sp[1:int(np):2].fill(-1.0) ss = D.empty.fill(0.0);ss[np::2].fill(1.0);ss[np+1::2].fill(-1.0) lr = rs.length Ar = rs.outer(pv.create(rs.type,M+1).ramp(0,1)).cos.prod(a) if lr > M+2: sp.putlength(M+2) ss.putlength(M+2) D.putlength(M+2) Ar.putlength(M+2) rs.putlength(M+2) if A[0] < A[1]: cp_ = -1.; else: cp_ = 1. if A[L] < A[L-1]: cs = -1. else: cs = 1. if ((A[0]-1.)*cp_ - del_p) < (A[L] * cs - del_s): sp.putoffset(1) ss.putoffset(1) D.putoffset(1) Ar.putoffset(1) rs.putoffset(1) # -------- calculate stopping criterion ------------ Err = ((Ar - D) - ((Kp*del_+eta_p)*sp + (Ks*del_+eta_s)*ss)).mag.maxval print('Err = %20.15f\n'%Err) h = pv.create(a.type,2 * a.length -1).fill(0.0) a[1:] *= 0.5;a2=a[1:];a1=a.block.bind(a2.length -1 + a2.offset,-1,a2.length); h[:a1.length]=a1; h[a1.length]=a[0]; h[a1.length+1:]=a2 # h : filter coefficients pi_inv=1.0/pi pyplot.figure(1) pyplot.plot((w*pi_inv).list,A.list,'r') pyplot.plot((rs*pi_inv).list,Ar.list,'+') pyplot.xlabel('w/pi',fontsize=14);pyplot.ylabel('A',fontsize=14) pyplot.title('Frequency Response Amplitude',fontsize=16) return (h,rs,del_p,del_s) <file_sep>import Foundation public struct Param{ public var c: Double? /* propagation speed */ public var Fs: Double? /* Sample Rate */ public var Nts: Int? /* length of time series */ public var Dsens: Double? /* distance between sensors */ public var Nsens: Int? /* number of sensors */ public var Navg: Int? /* number of instances to average in beamformer*/ public var Nsim: Int? /* number of tones to simulate */ public var freqs: [Double] = [] /* (array) frequencies to simulate */ public var bearings: [Double] = [] /* (array) bearing of each frequencys */ public var Nsim_noise: Int? /* number of noise directions to simualte */ public init(parameterFile: String?){ let input = try! String(contentsOfFile: parameterFile!) let rawParams = input.components(separatedBy: "*") var t = rawParams[1].components(separatedBy: " ")[0] c = Double(t) t = rawParams[2].components(separatedBy: " ")[0] Fs = Double(t) t = rawParams[3].components(separatedBy: " ")[0] Nts = Int(t) t = rawParams[4].components(separatedBy: " ")[0] Dsens = Double(t) t = rawParams[5].components(separatedBy: " ")[0] Nsens = Int(t) t = rawParams[6].components(separatedBy: " ")[0] Navg = Int(t) t = rawParams[7].components(separatedBy: " ")[0] Nsim = Int(t) for i in 8..<(Nsim! + 8) { t = rawParams[i].components(separatedBy: " ")[0] freqs.append(Double(t)!) t = rawParams[i + Nsim!].components(separatedBy: " ")[0] bearings.append(Double(t)!) } t = rawParams[8 + 2 * Nsim!].components(separatedBy: " ")[0] Nsim_noise = Int(t) } public func log(){ print("c: " + String(format: "%f", self.c!)) print("Fs: " + String(format: "%f", self.Fs!)) print("Nts: " + String(format: "%f", self.Nts!)) print("Dsens: " + String(format: "%f", self.Dsens!)) print("Nsens: " + String(format: "%f", self.Nsens!)) print("Navg: " + String(format: "%d", self.Navg!)) print("Nsim: " + String(format:" %d", self.Nsim!)) print("Nsim_noise: " + String(format: "%d", Nsim_noise!)) for i in 0..<self.Nsim! { var outString = "Narrow Band Signal \(i): " outString += String(format: "%5.1f Hz at %5.1f deg", self.freqs[i], self.bearings[i]) print(outString) } } } <file_sep>def scan_achar(fptr): l=str() while not l.startswith('*'): l=fptr.readline() return l def param_read( param_file_name): fptr = open(param_file_name,"r"); obj={'c':1,'Fs':2,'Nts':3,'Dsens':4,'Nsens':5,'Navg':6, 'Nsim_freqs':'7','sim_freqs':[],'sim_bearings':[],'Nsim_noise':10} # get the propagation speed l=scan_achar(fptr) obj['c']=float(l.partition('*')[2].partition(' ')[0]) # get the sample rate l=scan_achar(fptr) obj['Fs']=float(l.partition('*')[2].partition(' ')[0]) # get the time series length */ l=scan_achar(fptr) obj['Nts']=int(l.partition('*')[2].partition(' ')[0]) # get the sensor spacing */ l=scan_achar(fptr) obj['Dsens']=float(l.partition('*')[2].partition(' ')[0]) # get the number of sensors */ l=scan_achar(fptr) obj['Nsens']=int(l.partition('*')[2].partition(' ')[0]) # get the number of averages */ l=scan_achar(fptr) obj['Navg']=int(l.partition('*')[2].partition(' ')[0]) # get the number of narrow band simualted tones */ l=scan_achar(fptr) obj['Nsim_freqs']=int(l.partition('*')[2].partition(' ')[0]) n=obj['Nsim_freqs'] sim_freqs = [] for i in range(n): l=scan_achar(fptr) sim_freqs += [float(l.partition('*')[2].partition(' ')[0])] obj['sim_freqs']=sim_freqs sim_bearings = [] for i in range(n): l=scan_achar(fptr) sim_bearings += [float(l.partition('*')[2].partition(' ')[0])] obj['sim_bearings']=sim_bearings # Nsim_noise l=scan_achar(fptr) obj['Nsim_noise']=int(l.partition('*')[2].partition(' ')[0]) fptr.close() return obj <file_sep>/* Created RJudd October 6, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_mimagview_f.h,v 2.0 2003/02/22 15:18:33 judd Exp $ */ #ifndef _VI_MIMAGVIEW_F_H #define _VI_MIMAGVIEW_F_H #include"vsip_cmviewattributes_f.h" #include"vsip_mviewattributes_f.h" static vsip_mview_f* VI_mimagview_f( const vsip_cmview_f* X, vsip_mview_f* Y) { Y->block = X->block->I; Y->offset = X->offset; Y->row_length = X->row_length; Y->col_length = X->col_length; Y->row_stride = X->row_stride; Y->col_stride = X->col_stride; Y->markings = VSIP_VALID_STRUCTURE_OBJECT; return Y; } #endif /* _VI_MIMAGVIEW_F_H */ <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D881 */ #ifndef _vsip_firattributes_d_h #define _vsip_firattributes_d_h 1 #include"VI.h" struct vsip_firattributes_d{ vsip_vview_d *h; vsip_vview_d *s; vsip_length N; vsip_length M; vsip_length p; vsip_length D; int ntimes; vsip_symmetry symm; vsip_alg_hint hint; vsip_obj_state state; }; #endif /* _vsip_firattributes_d_h */ <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: rcmsub_f.h,v 2.0 2003/02/22 15:23:26 judd Exp $ */ #include"VU_mprintm_f.include" #include"VU_cmprintm_f.include" static void rcmsub_f(void){ printf("\n******\nTEST rcmsub_f\n"); { vsip_scalar_f data1[]= {1,.1, 2,.2, 3,.3, 4,-.1, 5,-.3, 6,-.4, 7,.8, 8,.9, 9,-1}; vsip_scalar_f data2_r[]= {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9}; vsip_scalar_f data2_i[]= {-1.1, 2.2, -3.3, 4.4, -5.5, 6.6, -7.7, 8.8, -9.9}; vsip_scalar_f ans[] = {-0.1, 1.1, -2.4, -4.4, -4.7, 7.7, 1.8, -2.2, -0.5, 5.5, -2.8, - 8.8, 3.7, 3.3, 1.4, -6.6, -0.9, 9.9}; vsip_cmview_f *c_m1 = vsip_cmbind_f( vsip_cblockbind_f(data1,NDPTR_f,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_mview_f *m1= vsip_mrealview_f(c_m1); vsip_cmview_f *m2 = vsip_cmbind_f( vsip_cblockbind_f(data2_r,data2_i,9,VSIP_MEM_NONE),0,1,3,3,3); vsip_cmview_f *ma = vsip_cmbind_f( vsip_cblockbind_f(ans,NDPTR_f,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_cmview_f *m3 = vsip_cmcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *chk = vsip_cmcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *chk_r = vsip_mrealview_f(chk); vsip_cblockadmit_f(vsip_cmgetblock_f(c_m1),VSIP_TRUE); vsip_cblockadmit_f(vsip_cmgetblock_f(m2),VSIP_TRUE); vsip_cblockadmit_f(vsip_cmgetblock_f(ma),VSIP_TRUE); printf("call vsip_rcmsub_f(a,b,c)\n"); printf("a =\n");VU_mprintm_f("8.6",m1); printf("b =\n");VU_cmprintm_f("8.6",m2); vsip_rcmsub_f(m1,m2,m3); printf("c =\n");VU_cmprintm_f("8.6",m3); printf("\nright answer =\n"); VU_cmprintm_f("6.4",ma); vsip_cmsub_f(ma,m3,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,0,2 * .0001,0,1,chk_r); if(fabs(vsip_msumval_f(chk_r)) > .5) printf("error\n"); else printf("correct\n"); { vsip_mview_f *a = vsip_mimagview_f(m3); vsip_mcopy_f_f(m1,a); printf(" a,c inplace with <a> imagview of <c>\n"); vsip_rcmsub_f(a,m2,m3); vsip_cmsub_f(ma,m3,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,0,2 * .0001,0,1,chk_r); if(fabs(vsip_msumval_f(chk_r)) > .5) printf("error\n"); else printf("correct\n"); vsip_mdestroy_f(a); } vsip_cmcopy_f_f(m2,m3); printf(" b,c inplace\n"); vsip_rcmsub_f(m1,m3,m3); vsip_cmsub_f(ma,m3,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,0,2 * .0001,0,1,chk_r); if(fabs(vsip_msumval_f(chk_r)) > .5) printf("error\n"); else printf("correct\n"); vsip_mdestroy_f(m1); vsip_cmalldestroy_f(c_m1); vsip_cmalldestroy_f(m2); vsip_cmalldestroy_f(m3); vsip_cmalldestroy_f(ma); vsip_mdestroy_f(chk_r); vsip_cmalldestroy_f(chk); } return; } <file_sep>/* Created RJudd October 9, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cmdiagview_d.c,v 2.0 2003/02/22 15:18:42 judd Exp $ */ #include"vsip.h" #include"vsip_cmviewattributes_d.h" vsip_cvview_d* (vsip_cmdiagview_d)( const vsip_cmview_d* v, vsip_stride idiag) { vsip_index i = (idiag < 0) ? -idiag : 0, /* row index of origin */ j = (idiag > 0) ? idiag : 0; /* col index of origin */ vsip_length n_row = v->col_length - i; /* # rows from origin to end */ vsip_length n_col = v->row_length - j; /* # cols from origin to end */ return vsip_cvbind_d( v->block, v->offset + i * v->col_stride + j * v->row_stride, v->row_stride + v->col_stride, (n_row < n_col) ? n_row : n_col); } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_length_f.h,v 2.1 2007/04/18 17:05:56 judd Exp $ */ static void get_put_length_f(void){ printf("********\nTEST get_put_length_f\n"); { vsip_offset ivo = 3, icvo=10; vsip_stride ivs = 0, icvs=0; vsip_length ivl = 3, icvl=4; vsip_length jvl = 5, jcvl=7; vsip_stride irs = 0, ics = 0; vsip_length irl = 2, icl = 3; vsip_length jrl = 5, jcl = 2; vsip_stride ixs = 0, iys = 0, izs = 0; vsip_length ixl = 2, iyl = 3, izl = 4; vsip_length jxl = 3, jyl = 4, jzl = 2; vsip_block_f *b = vsip_blockcreate_f(80,VSIP_MEM_NONE); vsip_cblock_f *cb = vsip_cblockcreate_f(80,VSIP_MEM_NONE); vsip_vview_f *v = vsip_vbind_f(b,ivo,ivs,ivl); vsip_mview_f *m = vsip_mbind_f(b,ivo,ics,icl,irs,irl); vsip_tview_f *t = vsip_tbind_f(b,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_cvview_f *cv = vsip_cvbind_f(cb,icvo,icvs,icvl); vsip_cmview_f *cm = vsip_cmbind_f(cb,ivo,ics,icl,irs,irl); vsip_ctview_f *ct = vsip_ctbind_f(cb,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_length s; printf("test vgetlength_f\n"); fflush(stdout); { s = vsip_vgetlength_f(v); (s == ivl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputlength_f\n"); fflush(stdout); { vsip_vputlength_f(v,jvl); s = vsip_vgetlength_f(v); (s == jvl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test cvgetlength_f\n"); fflush(stdout); { s = vsip_cvgetlength_f(cv); (s == icvl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputlength_f\n"); fflush(stdout); { vsip_cvputlength_f(cv,jcvl); s = vsip_cvgetlength_f(cv); (s == jcvl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /*************************************************************************/ printf("test mgetrowlength_f\n"); fflush(stdout); { s = vsip_mgetrowlength_f(m); (s == irl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputrowlength_f\n"); fflush(stdout); { vsip_mputrowlength_f(m,jrl); s = vsip_mgetrowlength_f(m); (s == jrl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test mgetcollength_f\n"); fflush(stdout); { s = vsip_mgetcollength_f(m); (s == icl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputcollength_f\n"); fflush(stdout); { vsip_mputcollength_f(m,jcl); s = vsip_mgetcollength_f(m); (s == jcl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test cmgetrowlength_f\n"); fflush(stdout); { s = vsip_cmgetrowlength_f(cm); (s == irl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test cmputrowlength_f\n"); fflush(stdout); { vsip_cmputrowlength_f(cm,jrl); s = vsip_cmgetrowlength_f(cm); (s == jrl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test cmgetcollength_f\n"); fflush(stdout); { s = vsip_cmgetcollength_f(cm); (s == icl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test cmputcollength_f\n"); fflush(stdout); { vsip_cmputcollength_f(cm,jcl); s = vsip_cmgetcollength_f(cm); (s == jcl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /*************************************************************************/ printf("test tgetxlength_f\n"); fflush(stdout); { s = vsip_tgetxlength_f(t); (s == ixl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputxlength_f\n"); fflush(stdout); { vsip_tputxlength_f(t,jxl); s = vsip_tgetxlength_f(t); (s == jxl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test ctgetxlength_f\n"); fflush(stdout); { s = vsip_ctgetxlength_f(ct); (s == ixl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test ctputxlength_f\n"); fflush(stdout); { vsip_ctputxlength_f(ct,jxl); s = vsip_ctgetxlength_f(ct); (s == jxl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test tgetylength_f\n"); fflush(stdout); { s = vsip_tgetylength_f(t); (s == iyl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputylength_f\n"); fflush(stdout); { vsip_tputylength_f(t,jyl); s = vsip_tgetylength_f(t); (s == jyl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test ctgetylength_f\n"); fflush(stdout); { s = vsip_ctgetylength_f(ct); (s == iyl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test ctputylength_f\n"); fflush(stdout); { vsip_ctputylength_f(ct,jyl); s = vsip_ctgetylength_f(ct); (s == jyl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test tgetzlength_f\n"); fflush(stdout); { s = vsip_tgetzlength_f(t); (s == izl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputzlength_f\n"); fflush(stdout); { vsip_tputzlength_f(t,jzl); s = vsip_tgetzlength_f(t); (s == jzl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test ctgetzlength_f\n"); fflush(stdout); { s = vsip_ctgetzlength_f(ct); (s == izl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test ctputzlength_f\n"); fflush(stdout); { vsip_ctputzlength_f(ct,jzl); s = vsip_ctgetzlength_f(ct); (s == jzl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } vsip_vdestroy_f(v); vsip_mdestroy_f(m); vsip_talldestroy_f(t); vsip_cvdestroy_f(cv); vsip_cmdestroy_f(cm); vsip_ctalldestroy_f(ct); } return; } <file_sep>#ifndef _vsipprivate_h #define _vsipprivate_h 1 #define vsip_valid_structure_object (0x5555) #define VSIP_VALID_STRUCTURE_OBJECT (0x5555) #define vsip_freed_structure_object (0xAAAA) #define VSIP_FREED_STRUCTURE_OBJECT (0xAAAA) #define VSIP_RELEASED_BLOCK (0) #define VSIP_ADMITTED_BLOCK (1) #define VSIP_VSIPL_BLOCK (0) #define VSIP_USER_BLOCK (1) #define VSIP_DERIVED_BLOCK (2) struct vsip_cblock_f; struct vsip_cblock_d; struct vsip_blockattributes_f { vsip_cblock_f* parent; /* if derived point to parent */ vsip_scalar_f* array; /* external data array */ int kind; /* 0 ==> private, 1 ==> public, 2==> derived */ int admit; /* 0 ==> No, 1 ==> Yes */ vsip_stride rstride; /* real block stride; stride = view_stride * block_stride */ size_t size; /* block size in elements */ int bindings; /* reference counter */ int markings; /* valid|destoyed block object */ vsip_memory_hint hint; /* Not used in this implementation */ vsip_scalar_bl update; /* a place to store update flag */ }; struct vsip_blockattributes_d { vsip_cblock_d* parent; /* if derived point to parent else null */ vsip_scalar_d* array; /* external data array */ int kind; /* 0 ==> private, 1 ==> public, 2==> derived */ int admit; /* 0 ==> No, 1 ==> Yes */ vsip_stride rstride; /* real block stride; stride = view_stride * block_stride */ size_t size; /* block size in elements */ int bindings; /* reference counter */ int markings; /* valid|destoyed block object */ vsip_memory_hint hint; /* Not used in this implementation */ vsip_scalar_bl update; /* a place to store update flag */ }; struct vsip_cblockattributes_d { vsip_block_d *R, *I; /* blocks holding data array */ int kind; /* 0 ==> private, 1 ==> public */ int admit; /* 0 ==> No, 1 ==> Yes */ vsip_stride cstride; /* 1 for split, 2 for interleaved */ size_t size; /* block size in elements */ int bindings; /* reference counter */ int markings; /* valid|destoyed block object */ vsip_memory_hint hint; /* not used in this implementation */ vsip_cscalar_d a_scalar; vsip_cscalar_d a_zero; vsip_cscalar_d a_one; vsip_cscalar_d a_imag_one; vsip_scalar_bl update; /* a place to store update flag */ }; struct vsip_cblockattributes_f { vsip_block_f *R, *I; /* blocks holding data arrays */ int kind; /* 0 ==> private, 1 ==> public */ int admit; /* 0 ==> No, 1 ==> Yes */ vsip_stride cstride; /* 1 for split, 2 for interleaved */ size_t size; /* block size in elements */ int bindings; /* reference counter */ int markings; /* valid|destoyed block object */ vsip_memory_hint hint; /* not used in this implementation */ vsip_cscalar_f a_scalar; vsip_cscalar_f a_zero; vsip_cscalar_f a_one; vsip_cscalar_f a_imag_one; vsip_scalar_bl update; /* a place to store update flag */ }; struct vsip_blockattributes_i { vsip_scalar_i* array; /* external data array */ int kind; /* 0 ==> private, 1 ==> public */ int admit; /* 0 ==> No, 1 ==> Yes */ size_t size; /* block size in elements */ int bindings; /* reference counter */ int markings; /* valid|destoyed block object */ vsip_memory_hint hint; /* Not used in this implementation */ vsip_scalar_bl update; /* a place to store update flag */ }; struct vsip_blockattributes_vi { vsip_scalar_vi* array; /* external data array */ int kind; /* 0 ==> private, 1 ==> public */ int admit; /* 0 ==> No, 1 ==> Yes */ size_t size; /* block size in elements */ int bindings; /* reference counter */ int markings; /* valid|destoyed block object */ vsip_memory_hint hint; /* not used in this implementation */ vsip_scalar_bl update; /* a place to store update flag */ }; #endif /* _vsipprivate_h */ <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vcopyfrom_user_i.h,v 1.1 2007/04/21 19:38:33 judd Exp $ */ #include"VU_vprintm_i.include" void vcopyfrom_user_i(void){ printf("********\nTEST vcopyfrom_user_i\n"); { int i; vsip_block_i *block = vsip_blockcreate_i(200,VSIP_MEM_NONE); vsip_scalar_i input[5]={0,1,2,3,4}; vsip_vview_i *view = vsip_vbind_i(block,100,3,5); vsip_vview_i *all = vsip_vbind_i(block,0,1,200); vsip_scalar_i check = 0; vsip_vfill_i(-1,all); vsip_vcopyfrom_user_i(input,view); VU_vprintm_i("3",view); for(i=0; i<5; i++){ check += fabs((float)(input[i] - vsip_vget_i(view,(vsip_index)i))); } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_vdestroy_i(all); vsip_vdestroy_i(view); vsip_blockdestroy_i(block); } return; } <file_sep>/* Created RJudd */ /********************************************************************** // TASP VSIPL Documentation and Code includes no warranty, / // express or implied, including the warranties of merchantability / // and fitness for a particular purpose. No person or organization / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_minterp_linear_d.c,v 2.1 2008/09/14 20:48:40 judd Exp $ */ #include"vsip.h" #include"vsip_vviewattributes_d.h" #include"vsip_mviewattributes_d.h" #define GETROW(_a,_i,_row) {\ _row->block = _a->block; \ _row->stride = _a->row_stride; \ _row->length = _a->row_length; \ _row->offset = _a->offset + _i * _a->col_stride;\ } #define GETCOL(_a,_i,_col) {\ _col->block = _a->block; \ _col->stride = _a->col_stride; \ _col->length = _a->col_length; \ _col->offset = _a->offset + _i * _a->row_stride;\ } #define F1(x0,x1,y0,y1,x,y) {y = y0 + (y1-y0)/(x1-x0) * (x - x0);} #define VINTERP_LINEAR(_x, _y, _xf, _yf) { \ vsip_length N0 = _x->length; vsip_length N = _xf->length; vsip_index i=0,j=0; \ vsip_scalar_d sx1,sx2,sy1,sy2,sx; \ vsip_stride _xst = _x->stride * _x->block->rstride, _yst = _y->stride * _x->block->rstride,\ _xfst = _xf->stride * _xf->block->rstride, _yfst = _yf->stride * _yf->block->rstride;\ vsip_scalar_d *_xptr = (_x->block->array) + _x->offset * _x->block->rstride, \ *_yptr = (_y->block->array) + _y->offset * _y->block->rstride,\ *_xfptr = (_xf->block->array) + _xf->offset * _xf->block->rstride, \ *_yfptr = (_yf->block->array) + _yf->offset * _yf->block->rstride; \ while((j < N) && (i < N0-1)){\ sx1 = _xptr[i * _xst];\ sx2 = _xptr[(i + 1) * _xst];\ sy1 = _yptr[i * _yst];\ sy2 = _yptr[(i + 1) * _yst];;\ sx = _xfptr[j * _xfst];\ if(sx < sx2) {\ vsip_scalar_d a;\ F1(sx1,sx2,sy1,sy2,sx,a);\ _yfptr[j * _yfst] = a;\ j++;\ } else i++;\ }\ } void vsip_minterp_linear_d( const vsip_vview_d *ax, const vsip_mview_d *ay, vsip_major major, const vsip_vview_d *bx, const vsip_mview_d *by){ vsip_index i; vsip_vview_d *y,yy; vsip_vview_d *yf,yyf; y = &yy; yf = &yyf; if(major == VSIP_ROW) { vsip_length M = ay->col_length; for(i=0; i<M; i++){ GETROW(ay,i,y); GETROW(by,i,yf); VINTERP_LINEAR(ax,y,bx,yf) } } else { /* must be by column */ vsip_length M = ay->row_length; for(i=0; i<M; i++){ GETCOL(ay,i,y); GETCOL(by,i,yf); VINTERP_LINEAR(ax,y,bx,yf) } } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: csvdiv_f.h,v 2.0 2003/02/22 15:23:22 judd Exp $ */ #include"VU_cvprintm_f.include" static void csvdiv_f(void){ printf("\n********\nTEST csvdiv_f\n"); { vsip_cscalar_f alpha = vsip_cmplx_f(1.5,-1.5); vsip_cvview_f *b = vsip_cvcreate_f(7,VSIP_MEM_NONE); vsip_cvview_f *c = vsip_cvcreate_f(7,VSIP_MEM_NONE); vsip_vview_f *c_i = vsip_vimagview_f(c); vsip_cvview_f *chk = vsip_cvcreate_f(7,VSIP_MEM_NONE); vsip_vview_f *chk_i = vsip_vimagview_f(chk); vsip_scalar_f data_r[] ={.1, .2, .3, .4, .5, .6, .7}; vsip_scalar_f data_i[] ={7,6,5,4,3,2,1}; vsip_scalar_f data_ans[] ={-.2112,-.2173, -.2414,-.2580, -.2810,-.3169, -.3342,-.4084, -.4054,-.5676, -.4817,-0.8945, -0.3020,-1.7114}; vsip_cblock_f *cblock = vsip_cblockbind_f(data_r,data_i,7,VSIP_MEM_NONE); vsip_cblock_f *cblock_ans = vsip_cblockbind_f(data_ans, (vsip_scalar_f*)NULL,7,VSIP_MEM_NONE); vsip_cvview_f *u_b = vsip_cvbind_f(cblock,0,1,7); vsip_cvview_f *u_ans = vsip_cvbind_f(cblock_ans,0,1,7); vsip_cblockadmit_f(cblock,VSIP_TRUE); vsip_cblockadmit_f(cblock_ans,VSIP_TRUE); vsip_cvcopy_f_f(u_b,b); printf("call vsip_csvdiv_f(alpha,b,c)\n"); printf("alpha = %f %+fi\n",vsip_real_f(alpha),vsip_imag_f(alpha)); printf("b =\n");VU_cvprintm_f("8.6",b); printf("test normal out of place\n"); vsip_csvdiv_f(alpha,b,c); printf("c =\n");VU_cvprintm_f("8.6",c); printf("right answer =\n");VU_cvprintm_f("8.4",u_ans); vsip_cvsub_f(u_ans,c,chk); vsip_cvmag_f(chk,chk_i); vsip_vclip_f(chk_i,.0002,.0002,0,1,chk_i); if(vsip_vsumval_f(chk_i) > .5) printf("error\n"); else printf("correct\n"); printf("test b,c inplace\n"); vsip_csvdiv_f(alpha,b,b); vsip_cvsub_f(u_ans,b,chk); vsip_cvmag_f(chk,chk_i); vsip_vclip_f(chk_i,.0002,.0002,0,1,chk_i); if(vsip_vsumval_f(chk_i) > .5) printf("error\n"); else printf("correct\n"); vsip_cvalldestroy_f(b); vsip_vdestroy_f(c_i); vsip_cvalldestroy_f(c); vsip_vdestroy_f(chk_i); vsip_cvalldestroy_f(chk); vsip_cvalldestroy_f(u_b); vsip_cvalldestroy_f(u_ans); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: ctget_put_d.h,v 2.0 2003/02/22 15:23:33 judd Exp $ */ static void ctget_put_d(void){ printf("********\nTEST ctget_put_d\n"); { vsip_scalar_d datar_a[] = { 0, 1, 1, 0, 1, 0, 2, 1, -1, -2, 0 ,1}; vsip_scalar_d datai_a[] = { 1, -1, -1, 1, -1, 1, -2, 0, 1, 2, 1,-1}; vsip_scalar_d ansr[2][3][2] = {{{ 0, 1},{ 1, 0},{ 1, 0}},{{ 2, 1},{ -1, -2},{ 0 ,1}}}; vsip_scalar_d ansi[2][3][2] = {{{ 1, -1},{ -1, 1},{ -1, 1}},{{ -2, 0},{ 1, 2},{ 1,-1}}}; vsip_cblock_d *block_a = vsip_cblockbind_d(datar_a,datai_a,12,VSIP_MEM_NONE); vsip_ctview_d *a = vsip_ctbind_d(block_a,0,6,2,2,3,1,2); vsip_cblock_d *block_b = vsip_cblockcreate_d(50,VSIP_MEM_NONE); vsip_ctview_d *b = vsip_ctbind_d(block_b,4, 1,2,3,3,10,2); vsip_index h,i,j; vsip_cblockadmit_d(block_a,VSIP_TRUE); /* copy <a> into <b> */ for(h=0; h<2; h++) for(j=0; j<2; j++) for(i=0; i<3; i++) vsip_ctput_d(b,h,i,j,vsip_ctget_d(a,h,i,j)); /* check <a> against ans */ printf("check unit stride compact view\n"); for(h=0; h<2; h++) for(j=0; j<2; j++) for(i=0; i<3; i++){ vsip_cscalar_d chk = vsip_ctget_d(a,h,i,j); chk.r = chk.r - ansr[h][i][j]; chk.i = chk.i - ansi[h][i][j]; chk.r = chk.r * chk.r + chk.i * chk.i; (chk.r < 0.0001) ? printf("correct\n") : printf("error\n"); fflush(stdout); } printf("check general stride view\n"); for(h=0; h<2; h++) for(j=0; j<2; j++) for(i=0; i<3; i++){ vsip_cscalar_d chk = vsip_ctget_d(b,h,i,j); chk.r = chk.r - ansr[h][i][j]; chk.i = chk.i - ansi[h][i][j]; chk.r = chk.r * chk.r + chk.i * chk.i; (chk.r < 0.0001) ? printf("correct\n") : printf("error\n"); fflush(stdout); } vsip_ctalldestroy_d(a); vsip_ctalldestroy_d(b); } return; } <file_sep>/* Created RJudd */ /********************************************************************** // TASP VSIPL Documentation and Code includes no warranty, / // express or implied, including the warranties of merchantability / // and fitness for a particular purpose. No person or organization / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vinterp_linear_f.c,v 2.1 2008/08/17 18:01:49 judd Exp $ */ #include"vsip.h" #include"vsip_vviewattributes_f.h" #define F1(x0,x1,y0,y1,x,y) {y = y0 + (y1-y0)/(x1-x0) * (x - x0);} void vsip_vinterp_linear_f( const vsip_vview_f *ax, const vsip_vview_f *ay, const vsip_vview_f *bx, const vsip_vview_f *by){ vsip_length N0 = ax->length; vsip_length N = bx->length; vsip_index i=0,j=0; vsip_scalar_f sx1,sx2,sy1,sy2,sx; vsip_stride axst = ax->stride * ax->block->rstride, ayst = ay->stride * ax->block->rstride, bxst = bx->stride * bx->block->rstride, byst = by->stride * by->block->rstride; vsip_scalar_f *axptr = (ax->block->array) + ax->offset * ax->block->rstride, *ayptr = (ay->block->array) + ay->offset * ay->block->rstride, *bxptr = (bx->block->array) + bx->offset * bx->block->rstride, *byptr = (by->block->array) + by->offset * by->block->rstride; while((j < N) && (i < N0-1)){ sx1 = axptr[i * axst]; sx2 = axptr[(i + 1) * axst]; sy1 = ayptr[i * ayst]; sy2 = ayptr[(i + 1) * ayst];; sx = bxptr[j * bxst]; if(sx < sx2) { vsip_scalar_f a; F1(sx1,sx2,sy1,sy2,sx,a); byptr[j * byst] = a; j++; } else i++; } return; } <file_sep>/* * vsip_svsub_vi.c * tvcpp_xcode * * Created by <NAME> on 7/17/06. * See Copyright statement in top level directory */ /* $Id: vsip_svsub_vi.c,v 2.2 2007/04/16 18:39:38 judd Exp $ */ #include"vsip.h" #include"vsip_vviewattributes_vi.h" void (vsip_svsub_vi)( vsip_scalar_vi a, const vsip_vview_vi *b, const vsip_vview_vi *r) { register vsip_scalar_vi alpha = a; vsip_length n = r->length; vsip_stride bst = b->stride, rst = r->stride; vsip_scalar_vi *bp = (b->block->array) + b->offset, *rp = (r->block->array) + r->offset; while(n-- > 0){ *rp = (*bp > alpha) ? 0 : alpha - *bp; bp += bst; rp += rst; } } <file_sep>import Foundation import Accelerate public struct Vector { public var block: Block public var offset: Int public var stride: Int public var length: Int public var type: BlockTypes { get { return self.block.type } } public init(block: Block, offset: Int, stride: Int, length: Int) { self.block = block self.offset = offset self.stride = stride self.length = length } public init(length: Int, type: BlockTypes) { self.block = Block(length: length, type: type) self.offset = 0 self.stride = 1 self.length = length } public subscript(index: Int) -> Scalar { get { return self.block[self.offset + index * self.stride] } set(value) { self.block[self.offset + index * self.stride] = value } } public mutating func fill(value: Scalar){ for index in 0..<self.length { self[index] = value } } public func vdsp_fill(value: Scalar) { switch self.type { case .f: var s = value.realf let dta = UnsafeMutablePointer<Float>(mutating: self.block.dta?.assumingMemoryBound(to: Float.self)) vDSP_vfill(&s,(dta! + self.offset), vDSP_Stride(self.stride), vDSP_Length(self.length)) case .d: var s = value.reald let dta = UnsafeMutablePointer<Double>(mutating: self.block.dta?.assumingMemoryBound(to: Double.self)) vDSP_vfillD( &s,(dta! + self.offset), vDSP_Stride(self.stride), vDSP_Length(self.length)) case .cf: var sr = value.realf var si = value.imagf let dtaReal = UnsafeMutablePointer<Float>(mutating: self.block.dta?.assumingMemoryBound(to: Float.self)) let dtaImag = UnsafeMutablePointer<Float>(mutating: self.block.imagDta?.assumingMemoryBound(to: Float.self)) vDSP_vfill(&sr,(dtaReal! + self.offset), vDSP_Stride(self.stride), vDSP_Length(self.length)) vDSP_vfill(&si,(dtaImag! + self.offset), vDSP_Stride(self.stride), vDSP_Length(self.length)) case .cd: var sr = value.reald var si = value.imagd let dtaReal = UnsafeMutablePointer<Double>(mutating: self.block.dta?.assumingMemoryBound(to: Double.self)) let dtaImag = UnsafeMutablePointer<Double>(mutating: self.block.imagDta?.assumingMemoryBound(to: Double.self)) vDSP_vfillD(&sr,(dtaReal! + self.offset), vDSP_Stride(self.stride), vDSP_Length(self.length)) vDSP_vfillD(&si,(dtaImag! + self.offset), vDSP_Stride(self.stride), vDSP_Length(self.length)) default: preconditionFailure("type \(self.type) not supported for fill") } } public mutating func ramp(start: Scalar, increment: Scalar) { for i in 0..<self.length { self[i] = Scalar(Int32(i)) * increment + start } } public func vdsp_ramp(start: Scalar, increment: Scalar){ switch self.type { case .f: let dta = UnsafeMutablePointer<Float>(mutating: self.block.dta?.assumingMemoryBound(to: Float.self)) var st = start.realf var inc = increment.realf vDSP_vramp(&st, &inc, (dta! + self.offset), vDSP_Stride(self.stride), vDSP_Length(self.length)) case .d: let dta = UnsafeMutablePointer<Double>(mutating: self.block.dta?.assumingMemoryBound(to: Double.self)) var st = start.reald var inc = increment.reald vDSP_vrampD(&st, &inc, (dta! + self.offset), vDSP_Stride(self.stride), vDSP_Length(self.length)) default: preconditionFailure("vdsp_ramp not supported for \(self.type)") } } public var sumval: Scalar { var sum = self[0] for i in 1..<self.length { sum = sum + self[i] } return sum } public var vdsp_sumval: Scalar { var retval: Scalar switch self.type { case .f: var sum: Float = 0.0 let dta = UnsafeMutablePointer<Float>(mutating: self.block.dta?.assumingMemoryBound(to: Float.self)) vDSP_sve((dta! + self.offset), vDSP_Stride(self.stride),&sum, vDSP_Length(self.length)) retval = Scalar(sum) case .d: var sum: Double = 0.0 let dta = UnsafeMutablePointer<Double>(mutating: self.block.dta?.assumingMemoryBound(to: Double.self)) vDSP_sveD((dta! + self.offset), vDSP_Stride(self.stride),&sum, vDSP_Length(self.length)) retval = Scalar(sum) default: preconditionFailure("vdsp_sumval not supported for \(self.type)") } return retval } public func string(format: String) -> String { var s = "" for i in 0..<self.length { s.append(self[i].string(format: format) + "\n") } return s } } <file_sep>/* Created by RJudd January 7, 1999 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_ccfftmip_f_def.h,v 2.0 2003/02/22 15:18:30 judd Exp $ */ #include"VI_fftm_building_blocks_f.h" void vsip_ccfftmip_f(const vsip_fftm_f *Offt, const vsip_cmview_f *y) { vsip_fftm_f Nfft = *Offt; vsip_fftm_f *fftm = &Nfft; VI_ccfftmip_f(fftm,y); } <file_sep>// // Vector.swift // SJVsip // // Created by <NAME> on 11/4/17. // Copyright © 2017 JVSIP. All rights reserved. // import Foundation import vsip public func sizeEqual(_ check: Vector, against: Vector) -> Bool{ return check.length == against.length } public class Vector : View, Sequence { fileprivate var tryVsip: OpaquePointer? = nil public var vsip: OpaquePointer { get { return tryVsip! } } public func makeIterator() -> AnyIterator<Scalar> { var vindex = 0 return AnyIterator { let nextIndex = vindex guard vindex < self.length else { return nil } vindex += 1 // return DSPDoubleComplex(real: self.rdata[nextIndex], imag: self.idata[nextIndex]) return self[nextIndex] } } // vector bind private func vBind(_ offset : Int, stride : Int, length : Int) -> OpaquePointer? { let blk = self.block.vsip let t = self.block.type switch t { case .f: return vsip_vbind_f(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .d: return vsip_vbind_d(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .cf: return vsip_cvbind_f(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .cd: return vsip_cvbind_d(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .i: return vsip_vbind_i(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .li: return vsip_vbind_li(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .si: return vsip_vbind_si(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .uc: return vsip_vbind_uc(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .vi: return vsip_vbind_vi(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .mi: return vsip_vbind_mi(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .bl: return vsip_vbind_bl(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) } } public init(block: Block, offset: Int, stride: Int, length: Int){ super.init(block: block, shape: .v) if let v = self.vBind(offset, stride: stride, length: length){ self.tryVsip = v } else { preconditionFailure("Failed to bind to a vsip vector") } } // vector create public convenience init(length : Int, type : Scalar.Types){ let blk = Block(length: length, type: type) self.init(block: blk, offset: 0, stride: 1, length: length) } // create view to hold derived subview public init(block: Block, cView: OpaquePointer){ super.init(block: block, shape: .v) self.tryVsip = cView } deinit{ let t = self.block.type //let id = self.myId.int32Value switch t { case .f: vsip_vdestroy_f(self.vsip) /* if _isDebugAssertConfiguration(){ print("vdestroy_f id \(id)") }*/ case .d: vsip_vdestroy_d(self.vsip) /* if _isDebugAssertConfiguration(){ print("vdestroy_d id \(id)") }*/ case .cf: vsip_cvdestroy_f(self.vsip) /* if _isDebugAssertConfiguration(){ print("cvdestroy_f id \(id)") }*/ case .cd: vsip_cvdestroy_d(self.vsip) /*if _isDebugAssertConfiguration(){ print("cvdestroy_d id \(id)") }*/ case .i: vsip_vdestroy_i(self.vsip) /*if _isDebugAssertConfiguration(){ print("vdestroy_i id \(id)") }*/ case .li: vsip_vdestroy_li(self.vsip) /* if _isDebugAssertConfiguration(){ print("vdestroy_li id \(id)") }*/ case .si: vsip_vdestroy_si(self.vsip) /*if _isDebugAssertConfiguration(){ print("vdestroy_si id \(id)") }*/ case .uc: vsip_vdestroy_uc(self.vsip) /*if _isDebugAssertConfiguration(){ print("vdestroy_uc id \(id)") }*/ case .vi: vsip_vdestroy_vi(self.vsip) /*if _isDebugAssertConfiguration(){ print("vdestroy_vi id \(id)") }*/ case .mi: vsip_vdestroy_mi(self.vsip) /*if _isDebugAssertConfiguration(){ print("vdestroy_mi id \(id)") }*/ case .bl: vsip_vdestroy_bl(self.vsip) /*if _isDebugAssertConfiguration(){ print("vdestroy_bl id \(id)") }*/ } } // MARK: Attributes public var offset: Int { get{ switch self.type { case .f : return Int(vsip_vgetoffset_f(self.vsip)) case .d : return Int(vsip_vgetoffset_d(self.vsip)) case .cf : return Int(vsip_cvgetoffset_f(self.vsip)) case .cd : return Int(vsip_cvgetoffset_d(self.vsip)) case .si : return Int(vsip_vgetoffset_si(self.vsip)) case .i : return Int(vsip_vgetoffset_i(self.vsip)) case .li : return Int(vsip_vgetoffset_li(self.vsip)) case .uc : return Int(vsip_vgetoffset_uc(self.vsip)) case .vi : return Int(vsip_vgetoffset_vi(self.vsip)) case .mi : return Int(vsip_vgetoffset_mi(self.vsip)) case .bl : return Int(vsip_vgetoffset_bl(self.vsip)) } } set(offset){ switch self.type { case .f : vsip_vputoffset_f(self.vsip, vsip_offset(offset)) case .d : vsip_vputoffset_d(self.vsip, vsip_offset(offset)) case .cf : vsip_cvputoffset_f(self.vsip, vsip_offset(offset)) case .cd : vsip_cvputoffset_d(self.vsip, vsip_offset(offset)) case .si : vsip_vputoffset_si(self.vsip, vsip_offset(offset)) case .i : vsip_vputoffset_i(self.vsip, vsip_offset(offset)) case .li : vsip_vputoffset_li(self.vsip, vsip_offset(offset)) case .uc : vsip_vputoffset_uc(self.vsip, vsip_offset(offset)) case .mi : vsip_vputoffset_mi(self.vsip, vsip_offset(offset)) case .vi : vsip_vputoffset_vi(self.vsip, vsip_offset(offset)) case .bl : vsip_vputoffset_bl(self.vsip, vsip_offset(offset)) } } } public var stride: Int { get{ switch self.type { case .f : return Int(vsip_vgetstride_f(self.vsip)) case .d : return Int(vsip_vgetstride_d(self.vsip)) case .cf : return Int(vsip_cvgetstride_f(self.vsip)) case .cd : return Int(vsip_cvgetstride_d(self.vsip)) case .si : return Int(vsip_vgetstride_si(self.vsip)) case .i : return Int(vsip_vgetstride_i(self.vsip)) case .li : return Int(vsip_vgetstride_li(self.vsip)) case .uc : return Int(vsip_vgetstride_uc(self.vsip)) case .vi : return Int(vsip_vgetstride_vi(self.vsip)) case .mi : return Int(vsip_vgetstride_mi(self.vsip)) case .bl : return Int(vsip_vgetstride_bl(self.vsip)) } } set(stride){ switch self.type { case .f : vsip_vputstride_f(self.vsip, vsip_stride(stride)) case .d : vsip_vputstride_d(self.vsip, vsip_stride(stride)) case .cf : vsip_cvputstride_f(self.vsip, vsip_stride(stride)) case .cd : vsip_cvputstride_d(self.vsip, vsip_stride(stride)) case .si : vsip_vputstride_si(self.vsip, vsip_stride(stride)) case .i : vsip_vputstride_i(self.vsip, vsip_stride(stride)) case .li : vsip_vputstride_li(self.vsip, vsip_stride(stride)) case .uc : vsip_vputstride_uc(self.vsip, vsip_stride(stride)) case .mi : vsip_vputstride_mi(self.vsip, vsip_stride(stride)) case .vi : vsip_vputstride_vi(self.vsip, vsip_stride(stride)) case .bl : vsip_vputstride_bl(self.vsip, vsip_stride(stride)) } } } public var length: Int { get{ switch self.type { case .f : return Int(vsip_vgetlength_f(self.vsip)) case .d : return Int(vsip_vgetlength_d(self.vsip)) case .cf : return Int(vsip_cvgetlength_f(self.vsip)) case .cd : return Int(vsip_cvgetlength_d(self.vsip)) case .si : return Int(vsip_vgetlength_si(self.vsip)) case .i : return Int(vsip_vgetlength_i(self.vsip)) case .li : return Int(vsip_vgetlength_li(self.vsip)) case .uc : return Int(vsip_vgetlength_uc(self.vsip)) case .vi : return Int(vsip_vgetlength_vi(self.vsip)) case .mi : return Int(vsip_vgetlength_mi(self.vsip)) case .bl : return Int(vsip_vgetlength_bl(self.vsip)) } } set(length){ switch self.type { case .f : vsip_vputlength_f(self.vsip, vsip_length(length)) case .d : vsip_vputlength_d(self.vsip, vsip_length(length)) case .cf : vsip_cvputlength_f(self.vsip, vsip_length(length)) case .cd : vsip_cvputlength_d(self.vsip, vsip_length(length)) case .si : vsip_vputlength_si(self.vsip, vsip_length(length)) case .i : vsip_vputlength_i(self.vsip, vsip_length(length)) case .li : vsip_vputlength_li(self.vsip, vsip_length(length)) case .uc : vsip_vputlength_uc(self.vsip, vsip_length(length)) case .mi : vsip_vputlength_mi(self.vsip, vsip_length(length)) case .vi : vsip_vputlength_vi(self.vsip, vsip_length(length)) case .bl : vsip_vputlength_bl(self.vsip, vsip_length(length)) } } } // MARK: sub views public var real: Vector{ get{ let ans = super.real(self.vsip) // C VSIP real view let blk = ans.0 let v = ans.1 return Vector(block: blk, cView: v) } } public var imag: Vector{ get{ let ans = super.imag(self.vsip) // C VSIP imag view let blk = ans.0! let v = ans.1! return Vector(block: blk, cView: v) } } // vector subscript operator public subscript(index: Int) -> Scalar { get{ return super.get(self.vsip, index: vsip_index(index)) } set(value){ super.put(self.vsip, index: vsip_index(index), value: value) } } public subscript() -> Scalar{ get{ return self[0] } set(value){ self.fill(value) } } // create empty vector of same type and view size. New data space created public var empty: Vector { return Vector(length: self.length, type: self.type) } public func empty(_ type: Scalar.Types) -> Vector { return Vector(length: self.length, type: type) } public var newCopy: Vector { let view = self.empty switch view.type{ case .f: vsip_vcopy_f_f(self.vsip,view.vsip) case .d: vsip_vcopy_d_d(self.vsip, view.vsip) case .cf: vsip_cvcopy_f_f(self.vsip,view.vsip) case .cd: vsip_cvcopy_d_d(self.vsip, view.vsip) case .i: vsip_vcopy_i_i(self.vsip,view.vsip) case .si: vsip_vcopy_si_si(self.vsip, view.vsip) case .vi: vsip_vcopy_vi_vi(self.vsip,view.vsip) case .mi: vsip_vcopy_mi_mi(self.vsip, view.vsip) default: break } return view } public func copy(_ resultsIn: Vector) -> Vector{ let t = (self.type, resultsIn.type) switch t{ case (.f,.f): vsip_vcopy_f_f(self.vsip,resultsIn.vsip) case (.f,.cf): let r = resultsIn.real;let i = resultsIn.real vsip_vcopy_f_f(self.vsip,r.vsip) vsip_vfill_f(0.0,i.vsip) case (.d,.d): vsip_vcopy_d_d(self.vsip,resultsIn.vsip) case (.d,.cd): let r = resultsIn.real;let i = resultsIn.real vsip_vcopy_d_d(self.vsip,r.vsip) vsip_vfill_d(0.0,i.vsip) case (.d,.f): vsip_vcopy_d_f(self.vsip,resultsIn.vsip) case (.f,.d): vsip_vcopy_f_d(self.vsip,resultsIn.vsip) case (.i,.f): vsip_vcopy_i_f(self.vsip,resultsIn.vsip) case (.i,.d): vsip_vcopy_i_d(self.vsip, resultsIn.vsip) case (.i,.i): vsip_vcopy_i_i(self.vsip, resultsIn.vsip) case (.i,.uc): vsip_vcopy_i_uc(self.vsip, resultsIn.vsip) case (.i,.vi): vsip_vcopy_i_vi(self.vsip, resultsIn.vsip) case (.si, .si): vsip_vcopy_si_si(self.vsip, resultsIn.vsip) case (.si, .d): vsip_vcopy_si_d(self.vsip, resultsIn.vsip) case (.si, .f): vsip_vcopy_si_f(self.vsip, resultsIn.vsip) case (.vi,.vi): vsip_vcopy_vi_vi(self.vsip, resultsIn.vsip) case (.vi, .i): vsip_vcopy_vi_i(self.vsip, resultsIn.vsip) case (.vi,.d): vsip_vcopy_vi_d(self.vsip, resultsIn.vsip) default: break } return resultsIn } public var clone: Vector { return Vector(block: self.block, offset: self.offset, stride: self.stride, length: self.length) } // MARK: Vector Data Generators public func ramp(_ start : Scalar, increment : Scalar) -> Vector { switch self.type { case .d: vsip_vramp_d(start.vsip_d, increment.vsip_d, self.vsip) case .f: vsip_vramp_f(start.vsip_f, increment.vsip_f, self.vsip) case .i: vsip_vramp_i(start.vsip_i, increment.vsip_i, self.vsip) case .si: vsip_vramp_si(start.vsip_si, increment.vsip_si, self.vsip) case .uc: vsip_vramp_uc(start.vsip_uc, increment.vsip_uc, self.vsip) case .vi: vsip_vramp_vi(start.vsip_vi, increment.vsip_vi, self.vsip) default: preconditionFailure("Type " + self.type.rawValue + " not supported for ramp") } return self } public func fill(_ value: Scalar){ switch self.type{ case .d: vsip_vfill_d(value.vsip_d, self.vsip) case .f: vsip_vfill_f(value.vsip_f, self.vsip) case .cd: vsip_cvfill_d(value.vsip_cd,self.vsip) case .cf: vsip_cvfill_f(value.vsip_cf,self.vsip) case .vi: vsip_vfill_vi(value.vsip_vi,self.vsip) case .i: vsip_vfill_i(value.vsip_i,self.vsip) case .li: vsip_vfill_li(value.vsip_li,self.vsip) case .si: vsip_vfill_si(value.vsip_si,self.vsip) case .uc: vsip_vfill_uc(value.vsip_uc,self.vsip) default: preconditionFailure("Type " + self.type.rawValue + " not supported for fill") } } // MARK: Print public func mString(_ format: String) -> String { let fmt = formatFmt(format) var retval = "" let n = self.length - 1 for i in 0...n { retval += (i == 0) ? "[" : " " retval += scalarString(fmt, value: self[i]) retval += (i == n) ? "]\n" : ";\n" } return retval } public func mPrint(_ format: String){ let m = mString(format) print(m) } // MARK: Elementary Functions public func acos(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vacos_d(self.vsip, out.vsip) case .f: vsip_vacos_f(self.vsip, out.vsip) default: return out } return out } public func asin(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vasin_d(self.vsip, out.vsip) case .f: vsip_vasin_f(self.vsip, out.vsip) default: return out } return out } public func atan(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vatan_d(self.vsip, out.vsip) case .f: vsip_vatan_f(self.vsip, out.vsip) default: return out } return out } public func cos(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vcos_d(self.vsip, out.vsip) case .f: vsip_vcos_f(self.vsip, out.vsip) default: return out } return out } public func sin(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vasin_d(self.vsip, out.vsip) case .f: vsip_vasin_f(self.vsip, out.vsip) default: return out } return out } public func tan(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vtan_d(self.vsip, out.vsip) case .f: vsip_vtan_f(self.vsip, out.vsip) default: return out } return out } public func exp(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vexp_d(self.vsip, out.vsip) case .f: vsip_vexp_f(self.vsip, out.vsip) default: return out } return out } public func exp10(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vexp10_d(self.vsip, out.vsip) case .f: vsip_vexp10_f(self.vsip, out.vsip) default: return out } return out } public func log(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vlog_d(self.vsip, out.vsip) case .f: vsip_vlog_f(self.vsip, out.vsip) default: return out } return out } public func log10(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vlog10_d(self.vsip, out.vsip) case .f: vsip_vlog10_f(self.vsip, out.vsip) default: return out } return out } // Mark: - Jvsip methods Vector public func put(_ data: Double...) { for i in 0..<data.count{ self[i] = Scalar(data[i]) } } } <file_sep>/* Created RJudd March 18, 2012 */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"vsip.h" #include"vsip_mviewattributes_d.h" #include"vsip_vviewattributes_d.h" #include"vsip_cmviewattributes_d.h" #include"vsip_cvviewattributes_d.h" #include"vsip_scalars.h" #include"VI_mrowview_d.h" #include"VI_mcolview_d.h" #include"VI_cmrowview_d.h" #include"VI_cmcolview_d.h" static void vrect_d(vsip_vview_d* r, vsip_vview_d* t, vsip_cvview_d* a) { vsip_length n = r->length; vsip_stride cast = a->block->cstride, rrst = r->block->rstride, trst = r->block->rstride; vsip_scalar_d *apr = (vsip_scalar_d*) ((a->block->R->array) + cast * a->offset), *rp = (vsip_scalar_d*) ((r->block->array) + rrst * r->offset), *tp = (vsip_scalar_d*) ((t->block->array) + trst * t->offset); vsip_scalar_d *api = (vsip_scalar_d*) ((a->block->I->array) + cast * a->offset); vsip_scalar_d temp = 0; vsip_stride ast = cast * a->stride, rst = rrst * r->stride, tst = trst * t->stride; while(n-- > 0){ temp = *rp * VSIP_SIN_D(*tp); *apr = *rp * VSIP_COS_D(*tp); *api = temp; apr += ast; api += ast; rp += rst; tp += tst; } } void vsip_mrect_d( const vsip_mview_d* r, const vsip_mview_d *t, const vsip_cmview_d* a){ vsip_index i; vsip_vview_d rv; vsip_vview_d tv; vsip_cvview_d av; if(a->row_stride < a->col_stride){ for(i=0; i < a->col_length; i++){ VI_mrowview_d(r,i,&rv); VI_mrowview_d(t,i,&tv);VI_cmrowview_d(a,i,&av); vrect_d(&rv,&tv,&av); } } else { for(i=0; i < a->col_length; i++){ VI_mcolview_d(r,i,&rv); VI_mcolview_d(t,i,&tv);VI_cmcolview_d(a,i,&av); vrect_d(&rv,&tv,&av); } } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_attrib_bl.h,v 2.0 2003/02/22 15:23:33 judd Exp $ */ static void get_put_attrib_bl(void){ printf("********\nTEST get_put_attrib_bl\n"); { vsip_offset ivo = 3; vsip_stride ivs = 2; vsip_length ivl = 3; vsip_offset jvo = 2; vsip_stride jvs = 3; vsip_length jvl = 5; vsip_stride irs = 1, ics = 3; vsip_length irl = 2, icl = 3; vsip_stride jrs = 5, jcs = 2; vsip_length jrl = 5, jcl = 2; vsip_block_bl *b = vsip_blockcreate_bl(80,VSIP_MEM_NONE); vsip_vview_bl *v = vsip_vbind_bl(b,ivo,ivs,ivl); vsip_mview_bl *m = vsip_mbind_bl(b,ivo,ics,icl,irs,irl); vsip_vattr_bl attr; vsip_mattr_bl mattr; printf("test vgetattrib_bl\n"); fflush(stdout); { vsip_vgetattrib_bl(v,&attr); (attr.offset == ivo) ? printf("offset correct\n") : printf("offset error \n"); (attr.stride == ivs) ? printf("stride correct\n") : printf("stride error \n"); (attr.length == ivl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputattrib_bl\n"); fflush(stdout); { attr.offset = jvo; attr.stride = jvs; attr.length = jvl; vsip_vputattrib_bl(v,&attr); vsip_vgetattrib_bl(v,&attr); (attr.offset == jvo) ? printf("offset correct\n") : printf("offset error \n"); (attr.stride == jvs) ? printf("stride correct\n") : printf("stride error \n"); (attr.length == jvl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test mgetattrib_bl\n"); fflush(stdout); { vsip_mgetattrib_bl(m,&mattr); (mattr.offset == ivo) ? printf("offset correct\n") : printf("offset error \n"); (mattr.col_stride == ics) ? printf("col_stride correct\n") : printf("col_stride error \n"); (mattr.row_stride == irs) ? printf("row_stride correct\n") : printf("row_stride error \n"); (mattr.col_length == icl) ? printf("col_length correct\n") : printf("col_length error \n"); (mattr.row_length == irl) ? printf("row_length correct\n") : printf("row_length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputattrib_bl\n"); fflush(stdout); { mattr.offset = jvo; mattr.col_stride = jcs; mattr.col_length = jcl; mattr.row_stride = jrs; mattr.row_length = jrl; vsip_mputattrib_bl(m,&mattr); vsip_mgetattrib_bl(m,&mattr); (mattr.offset == jvo) ? printf("offset correct\n") : printf("offset error \n"); (mattr.col_stride == jcs) ? printf("col_stride correct\n") : printf("col_stride error \n"); (mattr.col_length == jcl) ? printf("col_length correct\n") : printf("col_length error \n"); (mattr.row_stride == jrs) ? printf("row_stride correct\n") : printf("row_stride error \n"); (mattr.row_length == jrl) ? printf("row_length correct\n") : printf("row_length error \n"); fflush(stdout); } vsip_vdestroy_bl(v); vsip_malldestroy_bl(m); } return; } <file_sep>/* Created R Judd */ /* Copyright (c) 2006 <NAME> */ /* MIT style license, see Copyright notice in top level directory */ /* $Id: cllsqsol_d.h,v 1.1 2006/05/16 16:45:18 judd Exp $ */ #include"VU_cmprintm_d.include" static int cllsqsol_d(void) { vsip_cmview_d *A = vsip_cmcreate_d(10,6,VSIP_ROW,VSIP_MEM_NONE); vsip_cvview_d *ad = vsip_cmdiagview_d(A,0); vsip_vview_d *ad_r = vsip_vrealview_d(ad); vsip_vview_d *ad_i = vsip_vimagview_d(ad); vsip_cvview_d *ac = vsip_cmcolview_d(A,0); vsip_cmview_d *BX = vsip_cmcreate_d(10,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cvview_d *bxr = vsip_cmrowview_d(BX,0); vsip_cmview_d *B = vsip_cmcreate_d(10,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *Bs = vsip_cmsubview_d(B,0,0,6,3); vsip_cmview_d *X = vsip_cmcreate_d(6,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *Ans = vsip_cmcreate_d(6,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *AHA = vsip_cmcreate_d(6,6,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *AH = vsip_cmcreate_d(6,10,VSIP_ROW,VSIP_MEM_NONE); vsip_cblock_d *ablock = vsip_cblockcreate_d(500,VSIP_MEM_NONE); vsip_cmview_d *A1 = vsip_cmbind_d(ablock,200,-3,10,-31,6); vsip_cmview_d *BX1 = vsip_cmbind_d(ablock,203,8,10,2,3); vsip_cmview_d *BX1s = vsip_cmsubview_d(BX1,0,0,6,3); vsip_cchol_d *chol = vsip_cchold_create_d(VSIP_TR_LOW,6); vsip_cscalar_d a0 = vsip_cmplx_d(0.0,0.0); int i; vsip_cmfill_d(a0,A); vsip_cmfill_d(a0,BX); vsip_cmfill_d(a0,AHA); printf("********\nTEST cllsqsol_d\n"); printf("Test covariance solver vsip_cllsqsol_d\n"); /* need to make up some data */ for(i=0; i<6; i++){ vsip_cvputoffset_d(ac,i);{ vsip_vview_d *ac_r = vsip_vrealview_d(ac); vsip_vview_d *ac_i = vsip_vimagview_d(ac); vsip_vramp_d(-1.3,1.1,ac_r); vsip_vramp_d(+1.3,-1.1,ac_i); vsip_vdestroy_d(ac_r); vsip_vdestroy_d(ac_i); } } for(i=0; i<10; i++){ vsip_cvputoffset_d(bxr,i*3);{ vsip_vview_d *bxr_r = vsip_vrealview_d(bxr); vsip_vview_d *bxr_i = vsip_vimagview_d(bxr); vsip_vramp_d(.1,(vsip_scalar_d)i/3.0,bxr_r); vsip_vramp_d(.1,(vsip_scalar_d)i/4.0,bxr_i); vsip_vdestroy_d(bxr_r);vsip_vdestroy_d(bxr_i); } } vsip_vramp_d(3,1.2,ad_r); vsip_vramp_d(3,-1.2,ad_i); vsip_cmherm_d(A,AH); vsip_cmprod_d(AH,A,AHA); vsip_cmcopy_d_d(BX,BX1); vsip_cmcopy_d_d(A,A1); /* check input data */ printf("Input data \n"); printf("A = ");VU_cmprintm_d("4.2",A); printf("\nAH * A = ");VU_cmprintm_d("4.2",AHA); printf("\nBX = ");VU_cmprintm_d("4.2",BX); /* solve using Cholesky and AHA matrix */ printf("\nSolve using Cholesky and calculated AHA \n (AH * A) X = B \nfor X"); vsip_cmprod_d(AH,BX,Bs); printf("\nBs = ");VU_cmprintm_d("4.2",Bs); vsip_cmcopy_d_d(Bs,X); vsip_cchold_d(chol,AHA); vsip_ccholsol_d(chol,Bs); vsip_cmcopy_d_d(Bs,Ans); printf("\nBs = ");VU_cmprintm_d("7.5",Bs); /* check */ printf("\ncheck"); vsip_cmprod_d(AH,A,AHA); vsip_cmprod_d(AHA,Ans,Bs); printf("\nAHA * Bs ="); VU_cmprintm_d("4.2",Bs); vsip_cmsub_d(X,Bs,X); { float check = (float) vsip_cmmeansqval_d(X); if(fabs(check) < .0001) printf("check = %f\ncorrect\n",check); else printf("check = %f\nerror\n",check); } printf("\nsolve using cqrd_d and cqrsol_d with A matrix\n"); /* solve using cqrsol and A matrix */ { vsip_cqr_d *qr = vsip_cqrd_create_d(vsip_cmgetcollength_d(A),vsip_cmgetrowlength_d(A),VSIP_QRD_SAVEQ); vsip_cmcopy_d_d(BX,B); printf("\nSolve using qr and A\n (AH * A) X = B \nfor X"); vsip_cqrd_d(qr,A1); vsip_cqrsol_d(qr,VSIP_LLS,B); printf("\nBs = ");VU_cmprintm_d("7.5",Bs); /* check */ printf("\ncheck"); vsip_cmsub_d(Ans,Bs,X); { float check = (float) vsip_cmmeansqval_d(X); if(fabs(check) < .0001) printf("\ncheck = %f\ncorrect\n",check); else printf("\ncheck = %f\nerror\n",check); } vsip_cmcopy_d_d(A,A1); vsip_cqrd_destroy_d(qr); } vsip_cmcopy_d_d(BX,B); /* solve using covsol and A matrix*/ printf("Solve using cllsqsol_d and simple input matrix\n"); printf("\nSolve\n (AH * A) X = B \nfor X"); vsip_cllsqsol_d(A,B); printf("\nAHA * X ="); VU_cmprintm_d("7.5",Bs); vsip_cmsub_d(Ans,Bs,X); { float check = (float) vsip_cmmeansqval_d(X); if(fabs(check) < .0001) printf("\ncheck = %f\ncorrect\n",check); else printf("\ncheck = %f\nerror\n",check); } /* solve using covsol and A1,BX1 inputs */ printf("\nSolve using cllsqsol_d and nonstandard stride \n (AH * A) X = B \nfor X"); vsip_cllsqsol_d(A1,BX1); printf("\nAHA * X ="); VU_cmprintm_d("7.5",BX1s); vsip_cmsub_d(Ans,BX1s,X); { float check = (float) vsip_cmmeansqval_d(X); if(fabs(check) < .0001) printf("\ncheck = %f\ncorrect\n",check); else printf("\ncheck = %f\nerror\n",check); } vsip_cmdestroy_d(A1); vsip_cmdestroy_d(BX1); vsip_cmdestroy_d(BX1s); vsip_cblockdestroy_d(ablock); vsip_cvdestroy_d(ac); vsip_vdestroy_d(ad_i); vsip_vdestroy_d(ad_r); vsip_cvdestroy_d(ad); vsip_cmalldestroy_d(A); vsip_cmalldestroy_d(AH); vsip_cvdestroy_d(bxr); vsip_cmalldestroy_d(BX); vsip_cmalldestroy_d(X); vsip_cmalldestroy_d(Ans); vsip_cmdestroy_d(Bs); vsip_cmalldestroy_d(B); vsip_cmalldestroy_d(AHA); vsip_cchold_destroy_d(chol); return 0; } <file_sep>/* Created RJudd */ /* */ #include"VU_cvprintm_f.include" static void cvfreqswap_f(void){ printf("*********\nTEST vfreqswap_f\n"); { vsip_length M=8,N=9; vsip_cvview_f *even = vsip_cvcreate_f(M,VSIP_MEM_NONE); vsip_cvview_f *ans_even=vsip_cvcreate_f(M,VSIP_MEM_NONE); vsip_vview_f *v; vsip_cvview_f *odd = vsip_cvcreate_f(N,VSIP_MEM_NONE); vsip_cvview_f *ans_odd=vsip_cvcreate_f(N,VSIP_MEM_NONE); vsip_scalar_f even_ans_r[] = {4, 5, 6, 7, 0, 1, 2, 3}; vsip_scalar_f even_ans_i[]={-4, -5, -6, -7, -0, -1, -2, -3}; vsip_scalar_f odd_ans_r[] = {4, 5, 6, 7, 8, 0, 1, 2, 3}; vsip_scalar_f odd_ans_i[]={-4,-5,-6,-7,-8,0,-1,-2,-3}; vsip_cvcopyfrom_user_f(even_ans_r,even_ans_i, ans_even); vsip_cvcopyfrom_user_f(odd_ans_r,odd_ans_i, ans_odd); v=vsip_vrealview_f(even);vsip_vramp_f(0,1,v);vsip_vdestroy_f(v); v=vsip_vimagview_f(even);vsip_vramp_f(0,-1,v);vsip_vdestroy_f(v); v=vsip_vrealview_f(odd);vsip_vramp_f(0,1,v);vsip_vdestroy_f(v); v=vsip_vimagview_f(odd);vsip_vramp_f(0,-1,v);vsip_vdestroy_f(v); printf("INPUT even\n");VU_cvprintm_f("2.1",even); vsip_cvfreqswap_f(even); printf("For even expect\n");VU_cvprintm_f("2.1",ans_even); printf("for even result\n");VU_cvprintm_f("2.1",even); { vsip_cvsub_f(even,ans_even,ans_even); if(vsip_vcmaxmgsqval_f(ans_even,NULL) > .00001){ printf("error\n"); }else{ printf("correct\n"); } } printf("INPUT odd\n");VU_cvprintm_f("2.1",odd); vsip_cvfreqswap_f(odd); printf("For odd expect\n");VU_cvprintm_f("2.1",ans_odd); printf("for odd result\n");VU_cvprintm_f("2.1",odd); { vsip_cvsub_f(odd,ans_odd,ans_odd); if(vsip_vcmaxmgsqval_f(ans_odd,NULL) > .00001){ printf("error\n"); }else{ printf("correct\n"); } } vsip_cvalldestroy_f(even); vsip_cvalldestroy_f(odd); } } <file_sep># -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <markdowncell> # ## Decomposition Utilities Introduction # ### Notation and Simple Relations to pyJvsip # #### Vector # A vector is designated $\vec{x}$ and generally uses a lower case. For math purposes a vector should be considered equivalent to a single column of a matrix; although for program puposes there are differeces between vector and matrice views. # #### Vector Norm and View Methods # Vector and Matrix norms are not supported in C VSIPL but have been included with the pyJvsip implementation. For mathematical definitions of norms the reader should consult a linear algebra text or search the internet. The norms supported in pyJvsip are the one norm (norm1), the two norm (norm2), the infinity norm (normInf) and the Frobenius norm (normFro). # A vector norm is designated as $\parallel \vec{x} \parallel $. A two norm as ${\parallel \vec{x} \parallel }_{\:2} $ # #### Unit Vectors # A unit vector is designated as in $\hat{x}$. To produce a unit vector $\hat{x} = {\vec{x} \over {{\parallel \vec{x} \parallel }_{2}}}$ # #### dot, jdot and outer # Note that `dot`, `jdot`, and `outer` are only defined for views of type vector. # A math indicator like $ \vec{x} {\;} \vec{y}^H $ in done using an outer product and produces a view of type matrix. An indicator like $\vec{x}^H {\;} \vec{y} $ is done using `jdot` and produces a scalar. An indicator like $\vec{x}^T {\;} \vec{y} $ is done using `dot` and produces a scalar. # #### Identity Matrix # The identity matrix is square with ones on the diagonal and zero elsewhere. We designate it as $I$ and when the size is of interest we indicate it as a subscript as in $I_m$ or $I_n$. The function `eye(type,size)` is defined for creating a data space with an identity matrix in it. This is a convenience since we sometimes need a matrix for matrix product accumulations and the identity matrix is a convenient starting place. # <codecell> import pyJvsip as pv # <markdowncell> # #### Identity Matrix # The function eye(t,n) where t is a pyJvsip matrix type and n is an integer creates and returns an identity matrix of size n and type t. This is a convenience function. # <codecell> def eye(t,n): # create and return an identity matrix of size n and type t return pv.create(t,n,n).identity # <markdowncell> # #### Sign Function # The sign function is used for Householder and Givens calculations. It is defined in several texts although the text I am using here is the LAPACK Working Notes document #148. # <codecell> def sign(a_in): # see LAPACK Working Notes 148 for definition of sign if type(a_in) is int: a=float(a_in) else: a=a_in if type(a) is float or type(a) is complex: t=pv.vsip_hypot_d(a.real,a.imag) if t == 0.0: return 1.0 elif a.imag==0.0: if a.real < 0.0: return -1.0 else: return 1.0 else: return a/t else: print('sign function only works on scalars') return <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: matindex.h,v 2.1 2009/09/05 18:01:45 judd Exp $ */ static void matindex(void){ printf("********\nTEST matindex\n"); { vsip_scalar_vi a_r = 2; vsip_scalar_vi a_c = 3; vsip_scalar_mi a = vsip_matindex(a_r,a_c); printf("(%u %u) = vsip_matindex(%2u,%2u)\n",(unsigned)a.r,(unsigned)a.c,(unsigned)a_r,(unsigned)a_c); ((a.r == a_r) && (a.c == a_c)) ? printf("correct\n") : printf("error\n"); fflush(stdout); } return; } /* done */ <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mmeanval_f.h,v 2.0 2003/02/22 15:23:25 judd Exp $ */ #include"VU_mprintm_f.include" static void mmeanval_f(void){ printf("\n*******\nTEST mmeanval_f\n"); { vsip_scalar_f data[] = {1.0, 1.1, 1.2, 1.3, 1.4, 1.4, 1.3, 1.2, 1.1, 1.0}; vsip_mview_f *m1 = vsip_mbind_f( vsip_blockbind_f(data,10,VSIP_MEM_NONE),0,5,2,1,5); vsip_block_f *block = vsip_blockcreate_f(1024,VSIP_MEM_NONE); vsip_mview_f *m = vsip_mbind_f(block,4,20,2,2,5); vsip_blockadmit_f(vsip_mgetblock_f(m1),VSIP_TRUE); vsip_mcopy_f_f(m1,m); printf("matrix m1, user matrix, compact, row major\n"); VU_mprintm_f("6.4",m1); printf("matrix m1, VSIPL matrix, irregular, row major\n"); printf("col stride 20, row stride 2\n"); printf("copy m1 to m. Matrix m equals\n"); VU_mprintm_f("6.4",m); printf("mmeanval_f(m1) = %f\n",vsip_mmeanval_f(m1)); printf("mmeanval_f(m) = %f\n",vsip_mmeanval_f(m)); printf("ans should be 1.2 \n"); if(fabs(1.2000-vsip_mmeanval_f(m)) > .0001 || fabs(1.2000-vsip_mmeanval_f(m1)) > .0001) { printf("error\n"); }else{ printf("correct\n"); } vsip_malldestroy_f(m); vsip_malldestroy_f(m1); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_stride_f.h,v 2.1 2007/04/18 17:05:56 judd Exp $ */ static void get_put_stride_f(void){ printf("********\nTEST get_put_stride_f\n"); { vsip_offset ivo = 3, icvo=10; vsip_stride ivs = 2, icvs=-1; vsip_length ivl = 3, icvl=4; vsip_stride jvs = 3, jcvs=1; vsip_stride irs = 1, ics = 3; vsip_length irl = 2, icl = 3; vsip_stride jrs = 5, jcs = 2; vsip_stride ixs = 2, iys = 4, izs = 14; vsip_length ixl = 2, iyl = 3, izl = 4; vsip_stride jxs = 4, jys = 14, jzs = 2; vsip_block_f *b = vsip_blockcreate_f(80,VSIP_MEM_NONE); vsip_cblock_f *cb = vsip_cblockcreate_f(80,VSIP_MEM_NONE); vsip_vview_f *v = vsip_vbind_f(b,ivo,ivs,ivl); vsip_mview_f *m = vsip_mbind_f(b,ivo,ics,icl,irs,irl); vsip_tview_f *t = vsip_tbind_f(b,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_cvview_f *cv = vsip_cvbind_f(cb,icvo,icvs,icvl); vsip_cmview_f *cm = vsip_cmbind_f(cb,ivo,ics,icl,irs,irl); vsip_ctview_f *ct = vsip_ctbind_f(cb,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_stride s; printf("test vgetstride_f\n"); fflush(stdout); { s = vsip_vgetstride_f(v); (s == ivs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputstride_f\n"); fflush(stdout); { vsip_vputstride_f(v,jvs); s = vsip_vgetstride_f(v); (s == jvs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test cvgetstride_f\n"); fflush(stdout); { s = vsip_cvgetstride_f(cv); (s == icvs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputstride_f\n"); fflush(stdout); { vsip_cvputstride_f(cv,jcvs); s = vsip_cvgetstride_f(cv); (s == jcvs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /*************************************************************************/ printf("test mgetrowstride_f\n"); fflush(stdout); { s = vsip_mgetrowstride_f(m); (s == irs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputrowstride_f\n"); fflush(stdout); { vsip_mputrowstride_f(m,jrs); s = vsip_mgetrowstride_f(m); (s == jrs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test mgetcolstride_f\n"); fflush(stdout); { s = vsip_mgetcolstride_f(m); (s == ics) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputcolstride_f\n"); fflush(stdout); { vsip_mputcolstride_f(m,jcs); s = vsip_mgetcolstride_f(m); (s == jcs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test cmgetrowstride_f\n"); fflush(stdout); { s = vsip_cmgetrowstride_f(cm); (s == irs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test cmputrowstride_f\n"); fflush(stdout); { vsip_cmputrowstride_f(cm,jrs); s = vsip_cmgetrowstride_f(cm); (s == jrs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test cmgetcolstride_f\n"); fflush(stdout); { s = vsip_cmgetcolstride_f(cm); (s == ics) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test cmputcolstride_f\n"); fflush(stdout); { vsip_cmputcolstride_f(cm,jcs); s = vsip_cmgetcolstride_f(cm); (s == jcs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /*************************************************************************/ printf("test tgetxstride_f\n"); fflush(stdout); { s = vsip_tgetxstride_f(t); (s == ixs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputxstride_f\n"); fflush(stdout); { vsip_tputxstride_f(t,jxs); s = vsip_tgetxstride_f(t); (s == jxs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test ctgetxstride_f\n"); fflush(stdout); { s = vsip_ctgetxstride_f(ct); (s == ixs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test ctputxstride_f\n"); fflush(stdout); { vsip_ctputxstride_f(ct,jxs); s = vsip_ctgetxstride_f(ct); (s == jxs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test tgetystride_f\n"); fflush(stdout); { s = vsip_tgetystride_f(t); (s == iys) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputystride_f\n"); fflush(stdout); { vsip_tputystride_f(t,jys); s = vsip_tgetystride_f(t); (s == jys) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test ctgetystride_f\n"); fflush(stdout); { s = vsip_ctgetystride_f(ct); (s == iys) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test ctputystride_f\n"); fflush(stdout); { vsip_ctputystride_f(ct,jys); s = vsip_ctgetystride_f(ct); (s == jys) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test tgetzstride_f\n"); fflush(stdout); { s = vsip_tgetzstride_f(t); (s == izs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputzstride_f\n"); fflush(stdout); { vsip_tputzstride_f(t,jzs); s = vsip_tgetzstride_f(t); (s == jzs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test ctgetzstride_f\n"); fflush(stdout); { s = vsip_ctgetzstride_f(ct); (s == izs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test ctputzstride_f\n"); fflush(stdout); { vsip_ctputzstride_f(ct,jzs); s = vsip_ctgetzstride_f(ct); (s == jzs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } vsip_vdestroy_f(v); vsip_mdestroy_f(m); vsip_talldestroy_f(t); vsip_cvdestroy_f(cv); vsip_cmdestroy_f(cm); vsip_ctalldestroy_f(ct); } return; } <file_sep>import Foundation import SJVsip <file_sep>/* Created RJudd October 6, 2000 */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_cmtransview_d.h,v 2.1 2003/03/08 14:54:14 judd Exp $ */ #ifndef _VI_CMTRANSVIEW_D_H #define _VI_CMTRANSVIEW_D_H #include"vsip.h" #include"vsip_cmviewattributes_d.h" static vsip_cmview_d* VI_cmtransview_d( const vsip_cmview_d* v, vsip_cmview_d * a) { *a = *v; a->row_stride = v->col_stride; a->col_stride = v->row_stride; a->row_length = v->col_length; a->col_length = v->row_length; return a; } #endif /* _VI_CMTRANSVIEW_D_H */ <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_attrib_mi.h,v 2.0 2003/02/22 15:23:33 judd Exp $ */ static void get_put_attrib_mi(void){ printf("********\nTEST get_put_attrib_mi\n"); { vsip_offset ivo = 3; vsip_stride ivs = 2; vsip_length ivl = 3; vsip_offset jvo = 2; vsip_stride jvs = 3; vsip_length jvl = 5; vsip_block_mi *b = vsip_blockcreate_mi(80,VSIP_MEM_NONE); vsip_vview_mi *v = vsip_vbind_mi(b,ivo,ivs,ivl); vsip_vattr_mi attr; printf("test vgetattrib_mi\n"); fflush(stdout); { vsip_vgetattrib_mi(v,&attr); (attr.offset == ivo) ? printf("offset correct\n") : printf("offset error \n"); (attr.stride == ivs) ? printf("stride correct\n") : printf("stride error \n"); (attr.length == ivl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputattrib_mi\n"); fflush(stdout); { attr.offset = jvo; attr.stride = jvs; attr.length = jvl; vsip_vputattrib_mi(v,&attr); vsip_vgetattrib_mi(v,&attr); (attr.offset == jvo) ? printf("offset correct\n") : printf("offset error \n"); (attr.stride == jvs) ? printf("stride correct\n") : printf("stride error \n"); (attr.length == jvl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } vsip_valldestroy_mi(v); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: varg_d.h,v 2.0 2003/02/22 15:23:28 judd Exp $ */ #include"VU_vprintm_d.include" #include"VU_cvprintm_d.include" static void varg_d(void){ printf("\n*****\nTEST varg_d\n"); { vsip_cvview_d *a = vsip_cvcreate_d(22,VSIP_MEM_NONE); vsip_cvview_d *b = vsip_cvsubview_d(a,2,6); vsip_vview_d *chk = vsip_vcreate_d(6,VSIP_MEM_NONE); vsip_vview_d *b_r, *b_i; vsip_vview_d *arg = vsip_vcreate_d(6,VSIP_MEM_NONE); vsip_scalar_d data[] = {1.5708, 1.4601, 1.3258, 1.1659, .9828, .7854}; vsip_block_d *block = vsip_blockbind_d(data,6,VSIP_MEM_NONE); vsip_vview_d *ans = vsip_vbind_d(block,0,1,6); vsip_blockadmit_d(block,VSIP_TRUE); vsip_cvputstride_d(b,2); b_r = vsip_vrealview_d(b); b_i = vsip_vimagview_d(b); vsip_vramp_d(0,.1,b_r); vsip_vramp_d(1,-.1,b_i); printf("input vector\n"); VU_cvprintm_d("8.6",b); vsip_varg_d(b,arg); printf("varg_d(b,arg)\n"); VU_vprintm_d("8.6",arg); printf("answer to 4 digits\n"); VU_vprintm_d("8.4",ans); vsip_vsub_d(arg,ans,chk); vsip_vmag_d(chk,chk); if(vsip_vsumval_d(chk) > .0006) printf("error\n"); else printf("correct\n"); vsip_cvdestroy_d(b); vsip_vdestroy_d(b_i); vsip_vdestroy_d(b_r); vsip_cvalldestroy_d(a); vsip_valldestroy_d(arg); vsip_valldestroy_d(ans); vsip_valldestroy_d(chk); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cblock_admit_release_d.h,v 2.0 2003/02/22 15:23:32 judd Exp $ */ #include"VU_cvprintm_d.include" static void cblock_admit_release_d(void){ printf("********\nTEST cblock_admit_release_d\n"); { int i; vsip_scalar_d *ptr1,*ptr2; vsip_scalar_d *ptr1s,*ptr2s; vsip_scalar_d data_r[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; vsip_scalar_d data_i[10] = { 0, -1, -2, -3, -4, -5, -6, -7, -8, -9}; vsip_scalar_d datarb_r[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; vsip_scalar_d datarb_i[10] = { 0, -1, -2, -3, -4, -5, -6, -7, -8, -9}; vsip_scalar_d data_ri[20] = { 0,0, 1,-1, 2,-2, 3,-3, 4,-4, 5,-5, 6,-6, 7,-7, 8,-8, 9,-9}; vsip_scalar_d datarb_ri[20] = { 0,0, 1,-1, 2,-2, 3,-3, 4,-4, 5,-5, 6,-6, 7,-7, 8,-8, 9,-9}; vsip_cblock_d *b_r_i = vsip_cblockbind_d(data_r,data_i,10,VSIP_MEM_NONE); vsip_cvview_d *v_r_i = vsip_cvbind_d(b_r_i,0,1,10); vsip_cblock_d *b_ri = vsip_cblockbind_d(data_ri,(vsip_scalar_d*)NULL,10,VSIP_MEM_NONE); vsip_cvview_d *v_ri = vsip_cvbind_d(b_ri,0,1,10); vsip_cscalar_d chk_i= vsip_cmplx_d(0,0); vsip_cscalar_d chk_s= vsip_cmplx_d(0,0); int chk = 0; vsip_cblockadmit_d(b_r_i,VSIP_TRUE); vsip_cblockadmit_d(b_ri,VSIP_TRUE); vsip_rscvmul_d(2.0,v_r_i,v_r_i); vsip_rscvmul_d(2.0,v_ri,v_ri); /* VU_cvprintm_d("2.0",v_r_i); VU_cvprintm_d("2.0",v_ri); */ for(i=0; i<10; i++){ chk_i = vsip_cvget_d(v_ri,(vsip_index)i); chk_s = vsip_cvget_d(v_r_i,(vsip_index)i); if( (chk_i.r != chk_s.r) || (chk_i.i != chk_s.i)) chk++; } printf("check admit\n"); if(chk != 0) printf("error\n"); else printf("correct\n"); fflush(stdout); chk = 0; vsip_cblockrelease_d(b_r_i,VSIP_TRUE,&ptr1s,&ptr2s); vsip_cblockrelease_d(b_ri,VSIP_TRUE,&ptr1,&ptr2); printf("check release\n"); for(i=0; i< 10; i++){ if((ptr1[2*i] != ptr1s[i]) || (ptr1[2*i+1] != ptr2s[i])) chk++; /* printf("%2.0f, %2.0f; %2.0f, %2.0f\n",ptr1[2*i],ptr1[2*i+1], ptr1s[i],ptr2s[i]); */ } if(chk != 0) printf("error\n"); else printf("correct\n"); fflush(stdout); chk = 0; vsip_cblockrebind_d(b_ri,datarb_r,datarb_i,&ptr1,&ptr2); vsip_cblockrebind_d(b_r_i,datarb_ri,(vsip_scalar_d*)NULL,&ptr1s,&ptr2s); printf("check rebind\n"); printf("check correct pointer returned\n"); for(i=0; i< 10; i++){ if((ptr1[2*i] != ptr1s[i]) || (ptr1[2*i+1] != ptr2s[i])) chk++; } if(chk != 0) printf("error\n"); else printf("correct\n"); fflush(stdout); chk = 0; vsip_cblockadmit_d(b_r_i,VSIP_TRUE); vsip_cblockadmit_d(b_ri,VSIP_TRUE); vsip_rscvmul_d(2.0,v_r_i,v_r_i); vsip_rscvmul_d(2.0,v_ri,v_ri); for(i=0; i<10; i++){ chk_i = vsip_cvget_d(v_ri,(vsip_index)i); chk_s = vsip_cvget_d(v_r_i,(vsip_index)i); if( (chk_i.r != chk_s.r) || (chk_i.i != chk_s.i)) chk++; } printf("check admit\n"); if(chk != 0) printf("error\n"); else printf("correct\n"); fflush(stdout); chk = 0; fflush(stdout); vsip_cblockrelease_d(b_ri,VSIP_TRUE,&ptr1s,&ptr2s); vsip_cblockrelease_d(b_r_i,VSIP_TRUE,&ptr1,&ptr2); printf("check release\n"); for(i=0; i< 10; i++){ if((ptr1[2*i] != ptr1s[i]) || (ptr1[2*i+1] != ptr2s[i])) chk++; } if(chk != 0) printf("error\n"); else printf("correct\n"); fflush(stdout); vsip_cvalldestroy_d(v_r_i); vsip_cvalldestroy_d(v_ri); } return; } <file_sep>/* Created By RJudd July 9, 2002 */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_rcfftmop_create_d_loop.h,v 2.0 2003/02/22 15:18:33 judd Exp $ */ /* real to complex fft */ #ifndef _VI_RCFFTMOP_CREATE_D_LOOP_H #define _VI_RCFFTMOP_CREATE_D_LOOP_H vsip_fftm_d* vsip_rcfftmop_create_d( vsip_length M, vsip_length N, vsip_scalar_d scale, vsip_major major, unsigned int ntimes, vsip_alg_hint hint) { vsip_fftm_d *fftm = (vsip_fftm_d*)malloc(sizeof(vsip_fftm_d)); vsip_fft_d *fft = (vsip_fft_d*)NULL; /* find the length of the fft */ vsip_length L = (major == VSIP_ROW) ? N:M; if(fftm == NULL) return (vsip_fftm_d*)NULL; fftm->N = N; fftm->M = M; fftm->MN = (major == VSIP_ROW) ? N/2: M/2; fftm->mN = (major == VSIP_ROW) ? M : N; fftm->major = major; fftm->scale = scale; fftm->d = VSIP_FFT_FWD; fftm->pn = (vsip_scalar_vi*)NULL; fftm->p0 = (vsip_scalar_vi*)NULL; fftm->pF = (vsip_scalar_vi*)NULL; fftm->temp = (vsip_cvview_d*)NULL; fftm->wt = (vsip_cvview_d*)NULL; fftm->index = (vsip_scalar_vi*)NULL; fftm->hint = hint; fftm->ntimes = ntimes; fftm->type = VSIP_RCFFTOP; fft = vsip_rcfftop_create_d(L,scale,ntimes,hint); if(fft == NULL){ free(fftm); fftm = (vsip_fftm_d*)NULL; } else { fftm->ext_fftm_obj = (void*)fft; } return fftm; } #endif /* _VI_RCFFTMOP_CREATE_D_LOOP_H */ <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mvprod3_d.h,v 2.1 2006/04/09 19:28:23 judd Exp $ */ #include"VU_mprintm_d.include" #include"VU_vprintm_d.include" static void mvprod3_d(void){ printf("********\nTEST mvprod_d\n"); { vsip_scalar_d datav[] = {1,2,3}; vsip_scalar_d datam[] = { 1,1,1,2,2,2,3,3,3}; vsip_scalar_d ans_data[] = {6,12,18}; vsip_block_d *blockv = vsip_blockbind_d(datav,3,VSIP_MEM_NONE); vsip_block_d *blockm = vsip_blockbind_d(datam,9,VSIP_MEM_NONE); vsip_block_d *block_ans = vsip_blockbind_d(ans_data,3,VSIP_MEM_NONE); vsip_block_d *block = vsip_blockcreate_d(70,VSIP_MEM_NONE); vsip_vview_d *v = vsip_vbind_d(blockv,0,1,3); vsip_mview_d *m = vsip_mbind_d(blockm,0,3,3,1,3); vsip_vview_d *ans = vsip_vbind_d(block_ans,0,1,3); vsip_vview_d *b = vsip_vbind_d(block,5,-1,3); vsip_mview_d *a = vsip_mbind_d(block,50,-2,3,-8,3); vsip_vview_d *c = vsip_vbind_d(block,49,-2,3); vsip_vview_d *chk = vsip_vcreate_d(3,VSIP_MEM_NONE); vsip_blockadmit_d(blockv,VSIP_TRUE); vsip_blockadmit_d(blockm,VSIP_TRUE); vsip_blockadmit_d(block_ans,VSIP_TRUE); vsip_vcopy_d_d(v,b); vsip_mcopy_d_d(m,a); vsip_mvprod3_d(a,b,c); printf("vsip_mvprod3_d(a,b,c)\n"); printf("a\n"); VU_mprintm_d("6.4",a); printf("b\n"); VU_vprintm_d("6.4",b); printf("c\n"); VU_vprintm_d("6.4",c); printf("right answer\n"); VU_vprintm_d("6.4",ans); vsip_vsub_d(c,ans,chk); vsip_vmag_d(chk,chk); vsip_vclip_d(chk,.0001,.0001,0,1,chk); if(vsip_vsumval_d(chk) > .1) printf("error\n"); else printf("correct\n"); vsip_valldestroy_d(v); vsip_malldestroy_d(m); vsip_valldestroy_d(ans); vsip_vdestroy_d(b); vsip_mdestroy_d(a); vsip_valldestroy_d(c); vsip_valldestroy_d(chk); } return; } <file_sep>/* Created RJudd October 6, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_mimagview_d.h,v 2.0 2003/02/22 15:18:32 judd Exp $ */ #ifndef _VI_MIMAGVIEW_D_H #define _VI_MIMAGVIEW_D_H #include"vsip_cmviewattributes_d.h" #include"vsip_mviewattributes_d.h" static vsip_mview_d* VI_mimagview_d( const vsip_cmview_d* X, vsip_mview_d* Y) { Y->block = X->block->I; Y->offset = X->offset; Y->row_length = X->row_length; Y->col_length = X->col_length; Y->row_stride = X->row_stride; Y->col_stride = X->col_stride; Y->markings = VSIP_VALID_STRUCTURE_OBJECT; return Y; } #endif /* _VI_MIMAGVIEW_D_H */ <file_sep>/* Created RJudd September 15, 1999*/ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #ifndef _vsip_cludattributes_f_h #define _vsip_cludattributes_f_h 1 #include"vsip.h" #include"VI.h" #include"vsip_cmviewattributes_f.h" #include"vsip_cvviewattributes_f.h" #include"vsip_vviewattributes_vi.h" struct vsip_cludattributes_f{ vsip_cmview_f* LU; vsip_cmview_f LLU; vsip_index* P; vsip_length N; }; #endif /* _vsip_cludattributes_f */ <file_sep>/* Created RJudd */ /********************************************************************** // TASP VSIPL Documentation and Code includes no warranty, / // express or implied, including the warranties of merchantability / // and fitness for a particular purpose. No person or organization / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_spline_destroy_d.c,v 2.1 2008/09/14 20:48:40 judd Exp $ */ #include"vsip.h" #include"vsip_splineattributes_d.h" void vsip_spline_destroy_d(vsip_spline_d *spline){ if(spline){ spline->markings = VSIP_FREED_STRUCTURE_OBJECT; free(spline->h); free(spline); } return; } <file_sep>/* Created RJudd August 30, 2002 */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cchold_create_d.c,v 2.0 2003/02/22 15:18:39 judd Exp $ */ #include"vsip.h" #include"vsip_cmviewattributes_d.h" #include"vsip_ccholdattributes_d.h" vsip_cchol_d* vsip_cchold_create_d( vsip_mat_uplo uplo, vsip_length N) { vsip_cchol_d* chol = (vsip_cchol_d*)malloc(sizeof(vsip_cchol_d)); if(chol != NULL){ chol->N = N; chol->uplo = uplo; chol->matrix = (vsip_cmview_d*)NULL; } return chol; } <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mcopyfrom_user_f.c,v 2.1 2007/04/18 17:15:18 judd Exp $ */ #include"vsip.h" #include"vsip_mviewattributes_f.h" void (vsip_mcopyfrom_user_f)( vsip_scalar_f* const r, vsip_major major, const vsip_mview_f *a){ vsip_length row_length = a->row_length; vsip_length col_length = a->col_length; vsip_scalar_f *ap = a->block->array + a->offset * a->block->rstride; vsip_stride row_st = a->row_stride * a->block->rstride, col_st = a->col_stride * a->block->rstride; vsip_scalar_f *rp = r; vsip_index i,j; if(major == VSIP_ROW){ /* copy by rows */ for(i=0; i<col_length; i++){ vsip_scalar_f *ap_r = ap + i * col_st; for(j=0; j<row_length; j++){ *ap_r = *rp; rp++; ap_r += row_st; } } } else { /* copy by columns */ for(j=0; j<row_length; j++){ vsip_scalar_f *ap_c = ap + j * row_st; for(i=0; i<col_length; i++){ *ap_c = *rp; rp++; ap_c += col_st; } } } return; } <file_sep>/* Created RJudd June 2, 2002 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_cblockadmit_f_di.h,v 2.0 2003/02/22 15:18:28 judd Exp $ */ /* VI_cblockadmit_f default interleaved */ { if ((vsip_scalar_f*)NULL == b->R->array) blockadmit = 1; /* fail if no data array */ else if (b->kind != VSIP_USER_BLOCK) blockadmit = 1; /* fail if not a user block */ else{ b->admit = VSIP_ADMITTED_BLOCK; b->a_scalar.r = 0.0; b->a_scalar.i = 0.0; b->a_zero.r = 0.0; b->a_zero.i = 0.0; b->a_one.r = 1.0; b->a_one.i = 0.0; b->a_imag_one.r = 0.0; b->a_imag_one.i = 1.0; blockadmit = 0; /* return zero on success */ } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D881 */ #ifndef _vsip_corr1dattributes_f #define _vsip_corr1dattributes_f 1 #include"VI.h" struct vsip_corr1dattributes_f{ vsip_cvview_f *h; vsip_cvview_f *x; vsip_fft_f *fft; vsip_length n; vsip_length m; vsip_length mn; vsip_length N; vsip_length lag_len; int ntimes; vsip_support_region support; vsip_alg_hint hint; }; #endif /* _vsip_corr1dattributes_f */ <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mget_put_i.h,v 2.0 2003/02/22 15:23:34 judd Exp $ */ static void mget_put_i(void){ printf("********\nTEST mget_put_i\n"); { vsip_scalar_i data_a[] = { 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1}; vsip_scalar_i ans[6][2] = {{ 0, 1},{ 1, 0},{ 1, 0},{ 1, 0},{ 0, 1},{ 0, 1}}; vsip_block_i *block_a = vsip_blockbind_i(data_a,12,VSIP_MEM_NONE); vsip_mview_i *a = vsip_mbind_i(block_a,0,2,6,1,2); vsip_block_i *block_b = vsip_blockcreate_i(50,VSIP_MEM_NONE); vsip_mview_i *b = vsip_mbind_i(block_b,5,5,6,2,2); vsip_index i,j; vsip_blockadmit_i(block_a,VSIP_TRUE); /* copy <a> into <b> */ for(i=0; i<6; i++) for(j=0; j<2; j++) vsip_mput_i(b,i,j,vsip_mget_i(a,i,j)); /* check <a> against ans */ printf("check unit stride compact view\n"); for(i=0; i<6; i++) for(j=0; j<2; j++) { vsip_scalar_i chk = (ans[i][j] - vsip_mget_i(a,i,j)); (chk == 0) ? printf("correct\n") : printf("error\n"); fflush(stdout); } printf("check general stride view\n"); for(i=0; i<6; i++) for(j=0; j<2; j++){ vsip_scalar_i chk = (ans[i][j] - vsip_mget_i(b,i,j)); (chk == 0) ? printf("correct\n") : printf("error\n"); fflush(stdout); } vsip_malldestroy_i(a); vsip_malldestroy_i(b); } return; } <file_sep>/* Created <NAME> */ /* Retired */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cmprod4_d.c,v 2.1 2006/04/09 19:25:53 judd Exp $ */ /* New disclaimer now I am retired */ #include"vsip.h" #include"VI.h" #include"vsip_cmviewattributes_d.h" #include"vsip_cvviewattributes_d.h" /* note that matrix products may not be done in place */ void (vsip_cmprod4_d)( const vsip_cmview_d* a, const vsip_cmview_d* b, const vsip_cmview_d* c) { /* get the stride info */ /* st_r => stride row; st_c => stride column */ vsip_stride a_st_r = a->row_stride * a->block->cstride, a_st_c = a->col_stride * a->block->cstride, b_st_r = b->row_stride * b->block->cstride, b_st_c = b->col_stride * b->block->cstride, c_st_r = c->row_stride * c->block->cstride, c_st_c = c->col_stride * c->block->cstride; /* get the length info */ /* note we know a is 4 by 4 and b is 4 by row length */ vsip_length c_r_l = c->row_length; /* j_size */ /* get the pointers to the input and output data spaces */ vsip_scalar_d *ap_r = (a->block->R->array) + a->offset * a->block->cstride, *ap_i = (a->block->I->array) + a->offset * a->block->cstride, *bp_r = (b->block->R->array) + b->offset * b->block->cstride, *bp_i = (b->block->I->array) + b->offset * b->block->cstride, *cp_r = (c->block->R->array) + c->offset * c->block->cstride, *cp_i = (c->block->I->array) + c->offset * c->block->cstride; /* some additional pointers to store initial data */ vsip_scalar_d *ap0_r = ap_r, *ap0_i = ap_i, *bp0_r, *bp0_i, *cp0_r, *cp0_i; register vsip_scalar_d a00_r, a01_r, a02_r, a03_r, a00_i, a01_i, a02_i,a03_i; register vsip_scalar_d a10_r, a11_r, a12_r, a13_r, a10_i, a11_i, a12_i,a13_i; register vsip_scalar_d a20_r, a21_r, a22_r, a23_r, a20_i, a21_i, a22_i,a23_i; register vsip_scalar_d a30_r, a31_r, a32_r, a33_r, a30_i, a31_i, a32_i,a33_i; /* we need local storage for a column of b */ register vsip_scalar_d b0_r, b1_r, b2_r, b3_r; register vsip_scalar_d b0_i, b1_i, b2_i, b3_i; vsip_length i; /* need a counter */ /* we copy a to local storage */ a00_r = *ap0_r; a00_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a01_r = *ap0_r; a01_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a02_r = *ap0_r; a02_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a03_r = *ap0_r; a03_i = *ap0_i; ap0_r= ap_r + a_st_c; ap0_i = ap_i + a_st_c; a10_r = *ap0_r; a10_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a11_r = *ap0_r; a11_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a12_r = *ap0_r; a12_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a13_r = *ap0_r; a13_i = *ap0_i; ap0_r= ap_r + 2 * a_st_c; ap0_i = ap_i + 2 * a_st_c; a20_r = *ap0_r; a20_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a21_r = *ap0_r; a21_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a22_r = *ap0_r; a22_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a23_r = *ap0_r; a23_i = *ap0_i; ap0_r= ap_r + 3 * a_st_c; ap0_i = ap_i + 3 * a_st_c; a30_r = *ap0_r; a30_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a31_r = *ap0_r; a31_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a32_r = *ap0_r; a32_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a33_r = *ap0_r; a33_i = *ap0_i; for(i=0; i< c_r_l; i++){ /* copy i'th column of b into local */ bp0_r = bp_r + (vsip_stride)i * b_st_r; bp0_i = bp_i + (vsip_stride)i * b_st_r; b0_r = *bp0_r; b0_i = *bp0_i; bp0_r += b_st_c; bp0_i += b_st_c; b1_r = *bp0_r; b1_i = *bp0_i; bp0_r += b_st_c; bp0_i += b_st_c; b2_r = *bp0_r; b2_i = *bp0_i; bp0_r += b_st_c; bp0_i += b_st_c; b3_r = *bp0_r; b3_i = *bp0_i; /* get the pointer to the column where output will go */ cp0_r = cp_r + (vsip_stride)i * c_st_r; cp0_i = cp_i + (vsip_stride)i * c_st_r; /* do the math */ /* the real part */ *cp0_r = (a00_r * b0_r + a01_r * b1_r + a02_r * b2_r + a03_r * b3_r) - (a00_i * b0_i + a01_i * b1_i + a02_i * b2_i + a03_i * b3_i); cp0_r += c_st_c; *cp0_r = (a10_r * b0_r + a11_r * b1_r + a12_r * b2_r + a13_r * b3_r) - (a10_i * b0_i + a11_i * b1_i + a12_i * b2_i + a13_i * b3_i); cp0_r += c_st_c; *cp0_r = (a20_r * b0_r + a21_r * b1_r + a22_r * b2_r + a23_r * b3_r) - (a20_i * b0_i + a21_i * b1_i + a22_i * b2_i + a23_i * b3_i); cp0_r += c_st_c; *cp0_r = (a30_r * b0_r + a31_r * b1_r + a32_r * b2_r + a33_r * b3_r) - (a30_i * b0_i + a31_i * b1_i + a32_i * b2_i + a33_i * b3_i); /* the imaginary part */ *cp0_i = a00_r * b0_i + a01_r * b1_i + a02_r * b2_i + a03_r * b3_i + a00_i * b0_r + a01_i * b1_r + a02_i * b2_r + a03_i * b3_r; cp0_i += c_st_c; *cp0_i = a10_r * b0_i + a11_r * b1_i + a12_r * b2_i + a13_r * b3_i + a10_i * b0_r + a11_i * b1_r + a12_i * b2_r + a13_i * b3_r; cp0_i += c_st_c; *cp0_i = a20_r * b0_i + a21_r * b1_i + a22_r * b2_i + a23_r * b3_i + a20_i * b0_r + a21_i * b1_r + a22_i * b2_r + a23_i * b3_r; cp0_i += c_st_c; *cp0_i = a30_r * b0_i + a31_r * b1_i + a32_r * b2_i + a33_r * b3_i + a30_i * b0_r + a31_i * b1_r + a32_i * b2_r + a33_i * b3_r; } } <file_sep>// Strassen Multiplication // G&VL Alg 1.3.1 #include<cstdlib> #include<vsip/initfin.hpp> #include<vsip/vector.hpp> #include<vsip/matrix.hpp> #include<vsip/math.hpp> vsip::Matrix<vsip::scalar_f> strass( vsip::Matrix<vsip::scalar_f>A, vsip::Matrix<vsip::scalar_f>B, vsip::length_type n, vsip::length_type n_min) { if(n <= n_min){ return (vsip::prod(A,B)); } else { vsip::Matrix<vsip::scalar_f> C(n,n); vsip::length_type m = n/2; vsip::Domain<1> u(0,1,m); vsip::Domain<1> v(m,1,n); vsip::Domain<2> uu(u,u); vsip::Domain<2> vv(v,v); vsip::Domain<2> vu(v,u); vsip::Domain<2> uv(u,v); vsip::Matrix<vsip::scalar_f>::subview_type Auu(A(uu)); vsip::Matrix<vsip::scalar_f>::subview_type Buu(B(uu)); vsip::Matrix<vsip::scalar_f>::subview_type Avv(A(vv)); vsip::Matrix<vsip::scalar_f>::subview_type Bvv(B(vv)); vsip::Matrix<vsip::scalar_f>::subview_type Avu(A(vu)); vsip::Matrix<vsip::scalar_f>::subview_type Auv(A(uv)); vsip::Matrix<vsip::scalar_f>::subview_type Bvu(B(vu)); vsip::Matrix<vsip::scalar_f>::subview_type Buv(B(uv)); vsip::Matrix<vsip::scalar_f> P1 = strass(Auu + Avv, Buu + Bvv, m, n_min); vsip::Matrix<vsip::scalar_f> P2 = strass(Avu + Avv, Buu, m, n_min); vsip::Matrix<vsip::scalar_f> P3 = strass(Auu , Buv - Bvv, m, n_min); vsip::Matrix<vsip::scalar_f> P4 = strass(Avv , Bvu - Buu, m, n_min); vsip::Matrix<vsip::scalar_f> P5 = strass(Auu + Auv, Bvv, m, n_min); vsip::Matrix<vsip::scalar_f> P6 = strass(Avu - Auu, Buu + Buv, m, n_min); vsip::Matrix<vsip::scalar_f> P7 = strass(Auv - Avv, Bvu + Bvv, m, n_min); C(uu) = P1 + P4 - P5 + P7; C(uv) = P3 + P5; C(vu) = P2 + P4; C(vv) = P1 + P3 - P2 + P6; return C; } } <file_sep>import Foundation import vsip //public var unaryVsipOperation: Dictionary<String, (_: OpaquePointer, _:OpaquePointer?) -> Void)> = [:] <file_sep>/* Created RJudd */ /********************************************************************** // TASP VSIPL Documentation and Code includes no warranty, / // express or implied, including the warranties of merchantability / // and fitness for a particular purpose. No person or organization / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_minterp_nearest_d.c,v 2.1 2008/09/14 20:48:40 judd Exp $ */ #include"vsip.h" #include"vsip_vviewattributes_d.h" #include"vsip_mviewattributes_d.h" #define GETROW(_a,_i,_row) {\ _row->block = _a->block; \ _row->stride = _a->row_stride; \ _row->length = _a->row_length; \ _row->offset = _a->offset + _i * _a->col_stride;\ } #define GETCOL(_a,_i,_col) {\ _col->block = _a->block; \ _col->stride = _a->col_stride; \ _col->length = _a->col_length; \ _col->offset = _a->offset + _i * _a->row_stride;\ } #define F2(_x1,_x2,_y1,_y2,_x,_y) { \ vsip_scalar_d dif1 = _x - _x1;\ vsip_scalar_d dif2 = _x2 - _x;\ if(dif1 > dif2) \ _y = _y2;\ else \ _y = _y1; \ } #define VINTERP_NEAREST( _x0, _y0, _x, _y) {\ vsip_length N0 = _x0->length; \ vsip_length N = _x->length; \ vsip_stride x0_str = _x0->stride * _x0->block->rstride, \ y0_str = _y0->stride * _y0->block->rstride, \ x_str = _x->stride * _x->block->rstride, \ y_str = _y->stride * _y->block->rstride; \ vsip_scalar_d *x0_ptr = _x0->block->array + _x0->offset * _x0->block->rstride, \ *y0_ptr = _y0->block->array + _y0->offset * _y0->block->rstride, \ *x_ptr = _x->block->array + _x->offset * _x->block->rstride, \ *y_ptr = _y->block->array + _y->offset * _y->block->rstride; \ vsip_index i=0,j=0; \ vsip_scalar_d sx1,sx2,sy1,sy2,sx; \ while((j < N) && (i < N0-1)){ \ sx1 = x0_ptr[i * x0_str]; \ sx2 = x0_ptr[(i+1)*x0_str]; \ sy1 = y0_ptr[i * y0_str]; \ sy2 = y0_ptr[(i+1) * y0_str]; \ sx = x_ptr[j * x_str]; \ if(sx < sx2) { \ vsip_scalar_d a; \ F2(sx1,sx2,sy1,sy2,sx,a); \ y_ptr[j * y_str] = a; \ j++; \ } else i++; \ } \ } void vsip_minterp_nearest_d( const vsip_vview_d *ax, const vsip_mview_d *ay, vsip_major major, const vsip_vview_d *bx, const vsip_mview_d *by){ vsip_index i; vsip_vview_d *y,yy; vsip_vview_d *yf,yyf; y = &yy; yf = &yyf; if(major == VSIP_ROW) { vsip_length M = ay->col_length; for(i=0; i<M; i++){ GETROW(ay,i,y); GETROW(by,i,yf); VINTERP_NEAREST(ax,y,bx,yf) } } else { /* must be by column */ vsip_length M = ay->row_length; for(i=0; i<M; i++){ GETCOL(ay,i,y); GETCOL(by,i,yf); VINTERP_NEAREST(ax,y,bx,yf) } } return; } <file_sep>/* Created R Judd */ /* Copyright (c) 2006 <NAME> */ /* MIT style license, see Copyright notice in top level directory */ /* $Id: covsol_d.h,v 1.2 2006/05/16 16:45:18 judd Exp $ */ #include"VU_mprintm_d.include" static int covsol_d(void) { vsip_mview_d *A = vsip_mcreate_d(10,6,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *BX = vsip_mcreate_d(6,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *B = vsip_mcreate_d(6,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *X = vsip_mcreate_d(6,3,VSIP_ROW,VSIP_MEM_NONE); vsip_vview_d *ad = vsip_mdiagview_d(A,0); vsip_vview_d *ac = vsip_mcolview_d(A,0); vsip_vview_d *bxr = vsip_mrowview_d(BX,0); vsip_mview_d *ATA = vsip_mcreate_d(6,6,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *AT = vsip_mtransview_d(A); int i; vsip_chol_d *chol = vsip_chold_create_d(VSIP_TR_LOW,6); vsip_block_d *ablock = vsip_blockcreate_d(500,VSIP_MEM_NONE); vsip_mview_d *A1 = vsip_mbind_d(ablock,200,-3,10,-31,6); vsip_mview_d *BX1 = vsip_mbind_d(ablock,203,8,6,2,3); vsip_mfill_d(0.0,A); vsip_mfill_d(0.0,BX); vsip_mfill_d(0.0,ATA); printf("********\nTEST covsol_d\n"); printf("\n Test vsip_covsol_d\n"); /* need to make up some data */ for(i=0; i<6; i++){ vsip_vputoffset_d(ac,i); vsip_vputoffset_d(bxr,i*3); vsip_vramp_d(.1,(vsip_scalar_d)i/3.0,bxr); vsip_vramp_d(-1.3,1.1,ac); } vsip_vramp_d(3,1.2,ad); vsip_mprod_d(AT,A,ATA); vsip_mcopy_d_d(BX,B); vsip_mcopy_d_d(BX,BX1); vsip_mcopy_d_d(A,A1); /* check input data */ printf("Input Data \n"); printf("A = ");VU_mprintm_d("4.2",A); printf("\nAT * A = ");VU_mprintm_d("4.2",ATA); printf("\nB = ");VU_mprintm_d("4.2",B); /* slove using Cholesky and ATA matrix */ printf("\nSolve using cholesky and ATA matrix \n (AT * A) X = B \nfor X"); vsip_chold_d(chol,ATA); vsip_cholsol_d(chol,BX); vsip_mcopy_d_d(BX,X); printf("\nX = ");VU_mprintm_d("7.5",X); /* check */ printf("\ncheck"); vsip_mprod_d(AT,A,ATA); vsip_mprod_d(ATA,X,BX); printf("\nATA * X ="); VU_mprintm_d("4.2",BX); vsip_msub_d(B,BX,X); { float check = (float) vsip_msumval_d(X); if(fabs(check) < .0001) printf("check = %f\ncorrect\n",check); else printf("check = %f\nerror\n",check); } /* slove using covsol and A matrix*/ vsip_mcopy_d_d(B,BX); /* restore BX */ printf("\nSolve\n (AT * A) X = B \nfor X"); vsip_covsol_d(A,BX); vsip_mcopy_d_d(BX,X); printf("\nX = ");VU_mprintm_d("7.5",X); vsip_mprod_d(ATA,X,BX); printf("\nATA * X ="); VU_mprintm_d("4.2",BX); vsip_msub_d(B,BX,X); { float check = (float) vsip_msumval_d(X); if(fabs(check) < .0001) printf("check = %f\ncorrect\n",check); else printf("check = %f\nerror\n",check); } /* slove using covsol and A1,BX1 inputs */ printf("\nSolve nonstandard stride _d \n (AT * A) X = B \nfor X"); vsip_covsol_d(A1,BX1); vsip_mcopy_d_d(BX1,X); printf("\nX = ");VU_mprintm_d("7.5",X); vsip_mprod_d(ATA,X,BX); printf("\nATA * X ="); VU_mprintm_d("4.2",BX); vsip_msub_d(B,BX,X); { float check = (float) vsip_msumval_d(X); if(fabs(check) < .0001) printf("check = %f\ncorrect\n",check); else printf("check = %f\nerror\n",check); } vsip_mdestroy_d(A1); vsip_mdestroy_d(BX1); vsip_blockdestroy_d(ablock); vsip_vdestroy_d(ad); vsip_vdestroy_d(ac); vsip_vdestroy_d(bxr); vsip_mdestroy_d(AT); vsip_malldestroy_d(A); vsip_malldestroy_d(BX); vsip_malldestroy_d(X); vsip_malldestroy_d(B); vsip_malldestroy_d(ATA); vsip_chold_destroy_d(chol); return 0; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: meuler_d.h,v 2.0 2003/02/22 15:23:24 judd Exp $ */ #include"VU_mprintm_d.include" #include"VU_cmprintm_d.include" static void meuler_d(void){ printf("\n*******\nTEST meuler_d\n\n"); { vsip_scalar_d data[] = {M_PI/8.0, M_PI/4.0, M_PI/3.0, M_PI/1.5, 1.25 * M_PI, 1.75 * M_PI}; vsip_scalar_d ans_r[] = {0.9239, 0.7071, 0.5000, -0.5000, -0.7071, 0.7071}; vsip_scalar_d ans_i[] = {0.3827, 0.7071, 0.8660, 0.8660, -0.7071, -0.7071}; vsip_block_d *block = vsip_blockbind_d(data,6,VSIP_MEM_NONE); vsip_cblock_d *ans_block = vsip_cblockbind_d(ans_r,ans_i,6,VSIP_MEM_NONE); vsip_mview_d *a = vsip_mbind_d(block,0,2,3,1,2); vsip_cmview_d *ansm = vsip_cmbind_d(ans_block,0,2,3,1,2); vsip_cmview_d *b = vsip_cmcreate_d(3,2,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *chk = vsip_cmcreate_d(3,2,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *chk_r = vsip_mrealview_d(chk); vsip_blockadmit_d(block,VSIP_TRUE); vsip_cblockadmit_d(ans_block,VSIP_TRUE); printf("test out of place, compact, user \"a\", vsipl \"b\"\n"); vsip_meuler_d(a,b); printf("meuler_d(a,b)\n matrix a\n");VU_mprintm_d("8.6",a); printf("matrix b\n");VU_cmprintm_d("8.6",b); printf("answer\n");VU_cmprintm_d("8.4",ansm); vsip_cmsub_d(b,ansm,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); printf("check meuler_d in place, <a> realview of <b>.\n"); { vsip_mview_d *d = vsip_mrealview_d(b); vsip_mcopy_d_d(a,d); vsip_meuler_d(d,b); vsip_cmsub_d(b,ansm,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_mdestroy_d(d); } vsip_malldestroy_d(a); vsip_cmalldestroy_d(b); vsip_mdestroy_d(chk_r); vsip_cmalldestroy_d(chk); vsip_cmalldestroy_d(ansm); } return; } <file_sep>import pyJvsip as pjv from math import pi as pi n=1000 x=pjv.create('vview_d',n).ramp(0,2*pi/float(n)) c=pjv.cos(x,x.empty) cClip=pjv.clip(c,-.9,.9,-.8,.8,c.empty) <file_sep>/* Modified RJudd June 27, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_cvalldestroy_f.h,v 2.0 2003/02/22 15:18:31 judd Exp $ */ #include"vsip.h" #ifndef VI_CVALLDESTROY_F_H #define VI_CVALLDESTROY_F_H #include"VI_cblockdestroy_f.h" #include"VI_cvdestroy_f.h" static void VI_cvalldestroy_f( vsip_cvview_f* v) { /* vector view destructor*/ VI_cblockdestroy_f(VI_cvdestroy_f(v)); } #endif <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: tmisc_view_uc.h,v 2.1 2009/09/05 18:01:45 judd Exp $ */ static void tmisc_view_uc(void){ printf("********\nTEST tmisc_view_uc\n"); { vsip_index k,j,i; vsip_scalar_uc data_r[4][3][4] = {{{00, 001, 002, 003}, \ {01, 011, 012, 013}, \ {02, 021, 022, 023}}, \ {{10, 101, 102, 103}, \ {11, 111, 112, 113}, \ {12, 121, 122, 123}}, \ {{20, 201, 202, 203}, \ {21, 211, 212, 213}, \ {22, 221, 222, 223}}, \ {{30, 001, 002, 003}, \ {31, 011, 012, 013}, \ {32, 021, 022, 023}}}; /* if a problem with tcreate is suspected check both leading and trailing options here */ vsip_tview_uc *tview_a = vsip_tcreate_uc(12,9,12,VSIP_LEADING,VSIP_MEM_NONE); /* vsip_tview_uc *tview_a = vsip_tcreate_uc(12,9,12,VSIP_TRAILING,VSIP_MEM_NONE); */ vsip_block_uc *block_a = vsip_tgetblock_uc(tview_a); vsip_tview_uc *tview_b = vsip_tsubview_uc(tview_a,1,2,3,4,3,4); vsip_stride z_a_st = vsip_tgetzstride_uc(tview_a); vsip_stride y_a_st = vsip_tgetystride_uc(tview_a); vsip_stride x_a_st = vsip_tgetxstride_uc(tview_a); vsip_offset b_o_calc = z_a_st + 2 * y_a_st + 3 * x_a_st; vsip_offset b_o_get = vsip_tgetoffset_uc(tview_b); vsip_tview_uc *v = vsip_tbind_uc(block_a,b_o_calc, z_a_st,4, y_a_st,3, x_a_st,4); vsip_mview_uc *mview = (vsip_mview_uc*)NULL; vsip_vview_uc *vview = (vsip_vview_uc*)NULL; vsip_tview_uc *tview = (vsip_tview_uc*)NULL; vsip_scalar_uc a; int chk = 0; printf("z_a_st %d; y_a_st %d; x_a_st %d\n",(int)z_a_st,(int)y_a_st,(int)x_a_st); fflush(stdout); printf("b_o_calc %ul; b_o_get %ul\n",(unsigned)b_o_calc,(unsigned)b_o_get); fflush(stdout); for(k = 0; k < 4; k++){ for(j = 0; j < 3; j++){ for(i = 0; i < 4; i++){ a = data_r[k][j][i]; vsip_tput_uc(v,k,j,i,a); } } } printf("test tmatrixview_uc\n"); printf("TMZY\n"); fflush(stdout); for(i = 0; i < 4; i++){ mview = vsip_tmatrixview_uc(v,VSIP_TMZY,i); for(j = 0; j < 3; j++){ for(k = 0; k < 4; k++){ a = vsip_mget_uc(mview,k,j); a -= data_r[k][j][i]; chk += a * a; } } vsip_mdestroy_uc(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TMYX\n"); fflush(stdout); for(k = 0; k < 4; k++){ mview = vsip_tmatrixview_uc(v,VSIP_TMYX,k); for(j = 0; j < 3; j++){ for(i = 0; i < 4; i++){ a = vsip_mget_uc(mview,j,i); a -= data_r[k][j][i]; chk += a * a; } } vsip_mdestroy_uc(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TMZX\n"); fflush(stdout); for(j = 0; j < 3; j++){ mview = vsip_tmatrixview_uc(v,VSIP_TMZX,j); for(k = 0; k < 4; k++){ for(i = 0; i < 4; i++){ a = vsip_mget_uc(mview,k,i); a -= data_r[k][j][i]; chk += a * a; } } vsip_mdestroy_uc(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test tvectview_uc\n"); printf("TVX \n"); fflush(stdout); for(k=0; k<4; k++){ for(j=0; j<3; j++){ vview = vsip_tvectview_uc(v,VSIP_TVX,k,j); for(i=0; i<4; i++){ a = vsip_vget_uc(vview,i); a -= data_r[k][j][i]; chk += a * a; } } vsip_vdestroy_uc(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test tvectview_uc\n"); printf("TVY \n"); fflush(stdout); for(k=0; k<4; k++){ for(i=0; i<4; i++){ vview = vsip_tvectview_uc(v,VSIP_TVY,k,i); for(j=0; j<3; j++){ a = vsip_vget_uc(vview,j); a -= data_r[k][j][i]; chk += a * a ; } } vsip_vdestroy_uc(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TVZ \n"); fflush(stdout); for(j=0; j<3; j++){ for(i=0; i<4; i++){ vview = vsip_tvectview_uc(v,VSIP_TVZ,j,i); for(k=0; k<4; k++){ a = vsip_vget_uc(vview,k); a -= data_r[k][j][i]; chk += a * a; } } vsip_vdestroy_uc(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test ttransview_uc\n"); fflush(stdout); printf("NOP\n"); fflush(stdout); tview = vsip_ttransview_uc(v,VSIP_TTRANS_NOP); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_uc(tview,k,j,i); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_uc(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YX\n"); fflush(stdout); tview = vsip_ttransview_uc(v,VSIP_TTRANS_YX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_uc(tview,k,i,j); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_uc(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("ZY\n"); fflush(stdout); tview = vsip_ttransview_uc(v,VSIP_TTRANS_ZY); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_uc(tview,j,k,i); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_uc(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("ZX\n"); fflush(stdout); tview = vsip_ttransview_uc(v,VSIP_TTRANS_ZX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_uc(tview,i,j,k); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_uc(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YXZY\n"); fflush(stdout); tview = vsip_ttransview_uc(v,VSIP_TTRANS_YXZY); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_uc(tview,i,k,j); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_uc(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YXZX\n"); fflush(stdout); tview = vsip_ttransview_uc(v,VSIP_TTRANS_YXZX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_uc(tview,j,i,k); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_uc(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; vsip_tdestroy_uc(v); vsip_tdestroy_uc(tview_b); vsip_talldestroy_uc(tview_a); } return; } <file_sep>/* Created <NAME> 19, 1999 */ /* SPAWARSYSCEN D881 */ #ifndef _vsip_conv1dattributes_d #define _vsip_conv1dattributes_d 1 #include"VI.h" struct vsip_conv1dattributes_d{ vsip_cvview_d *H; vsip_cvview_d *x; vsip_cmview_d *Xm; vsip_fft_d *fft; vsip_fftm_d *fftm; vsip_scalar_vi method; /* 0 = vector, 1 = matrix */ vsip_symmetry symm; int D; /* decimation */ vsip_length nh; /* length of h */ vsip_length nx; /* length of input */ vsip_length Nsection; /* length of section */ vsip_length Noutput; /* total length of output vector */ vsip_length Ndata; vsip_length Ndataf; vsip_length NumSection; int ntimes; /* ignored */ vsip_support_region support; vsip_alg_hint hint; /* ignored */ }; #endif /* _vsip_conv1dattributes_d */ <file_sep>/* Created by RJudd June 10, 2002 */ /* SPAWARSYSCEN code 2857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_ccfftip_d_fftw.h,v 2.0 2003/02/22 15:18:29 judd Exp $ */ /* use fftw for calculation */ #include"vsip.h" #include"vsip_fftattributes_d.h" #include"vsip_cvviewattributes_d.h" #if !defined(VSIP_ASSUME_COMPLEX_IS_INTERLEAVED) #define __VSIPL_CVCOPY_TO_FFTW_D #define __VSIPL_CVCOPY_FROM_FFTW_D #endif #include"VI_fftw_obj.h" /*========================================================*/ void vsip_ccfftip_d(const vsip_fft_d *Offt, const vsip_cvview_d *x) { vsip_fft_d Nfft = *Offt; vsip_fft_d *fft = &Nfft; vsipl_fftw_obj *obj = (vsipl_fftw_obj*)fft->ext_fft_obj; #if defined(VSIP_ASSUME_COMPLEX_IS_INTERLEAVED) fftw_complex *in, *out; vsip_cvview_d *z = fft->temp; int howmany = 1; int istride = (int)(z->stride); int ostride = (int)(x->stride); int idist = 1, odist = 1; vsip_cvcopy_d_d(x,z); in = (fftw_complex*)(z->block->R->array + z->offset * z->block->R->rstride); out = (fftw_complex*)(x->block->R->array + x->offset * x->block->R->rstride); fftw(obj->p,howmany,in,istride,idist,out,ostride,odist); #else vsipl_cvcopy_to_fftw_d(x,obj); fftw_one(obj->p,obj->in,obj->out); vsipl_cvcopy_from_fftw_d(obj,x); #endif if (fft->scale != 1) vsip_rscvmul_d(fft->scale,x,x); return; } <file_sep>// // cholesky.swift // SJVsip // // Created by <NAME> on 11/12/17. // Copyright © 2017 JVSIP. All rights reserved. // import Foundation import vsip // MARK: - Chold public class Chold { var size: Int var type: Scalar.Types { return (jVsip?.type)! } fileprivate var vsip: OpaquePointer { get { return (jVsip?.vsip)! } } fileprivate class chol { var tryVsip : OpaquePointer? var vsip: OpaquePointer { get { return tryVsip! } } let jInit : JVSIP var type : Scalar.Types? init(){ jInit = JVSIP() } } fileprivate class chol_d: chol { init(size: Int){ super.init() self.type = .d if let chold = vsip_chold_create_d(VSIP_TR_LOW, vsip_length(size)){ self.tryVsip = chold } else { preconditionFailure("Failed to create vsip cholesky object") } } deinit{ /* if _isDebugAssertConfiguration(){ print("vsip_chold_destroy_d \(jInit.myId.int32Value)") }*/ vsip_chold_destroy_d(self.vsip) } } fileprivate class chol_f: chol { init(size: Int){ super.init() self.type = .f if let chold = vsip_chold_create_f(VSIP_TR_LOW, vsip_length(size)){ self.tryVsip = chold } else { preconditionFailure("Failed to create vsip cholesky object") } } deinit{ /* if _isDebugAssertConfiguration(){ print("vsip_chold_destroy_f \(jInit.myId.int32Value)") }*/ vsip_chold_destroy_f(self.vsip) } } fileprivate class chol_cd: chol { init(size: Int){ super.init() self.type = .cd if let chold = vsip_cchold_create_d(VSIP_TR_LOW, vsip_length(size)){ self.tryVsip = chold } else { preconditionFailure("Failed to create vsip cholesky object") } } deinit{ /* if _isDebugAssertConfiguration(){ print("vsip_cchold_destroy_d \(jInit.myId.int32Value)") }*/ vsip_cchold_destroy_d(self.vsip) } } fileprivate class chol_cf: chol { init(size: Int){ super.init() self.type = .cf if let chold = vsip_cchold_create_f(VSIP_TR_LOW, vsip_length(size)){ self.tryVsip = chold } else { preconditionFailure("Failed to create vsip cholesky object") } } deinit{ /* if _isDebugAssertConfiguration(){ print("vsip_cchold_destroy_f \(jInit.myId.int32Value)") }*/ vsip_cchold_destroy_f(self.vsip) } } fileprivate let jVsip : chol? init(type: Scalar.Types, size: Int) { self.size = size switch type { case .f: self.jVsip = chol_f(size: size) case .d: self.jVsip = chol_d(size: size) case .cf: self.jVsip = chol_cf(size: size) case .cd: self.jVsip = chol_cd(size: size) default: preconditionFailure ("type \(type) not found for cholesky decomposition") } } public func decompose(_ A: Matrix) -> Int { let t = (self.type, A.type) switch t { case (.f, .f): return Int(vsip_chold_f(self.vsip, A.vsip)) case (.d, .d): return Int(vsip_chold_d(self.vsip, A.vsip)) case (.cf, .cf): return Int(vsip_cchold_f(self.vsip, A.vsip)) case (.cd, .cd): return Int(vsip_cchold_d(self.vsip, A.vsip)) default: preconditionFailure("Type \(t) not supported for cholesky decompostion") } } public func solve(_ XB: Matrix) -> Int { let t = (self.type, XB.type) switch t { case (.f, .f): return Int(vsip_cholsol_f(self.vsip, XB.vsip)) case (.d, .d): return Int(vsip_cholsol_d(self.vsip, XB.vsip)) case (.cf, .cf): return Int(vsip_ccholsol_f(self.vsip, XB.vsip)) case (.cd, .cd): return Int(vsip_ccholsol_d(self.vsip, XB.vsip)) default: preconditionFailure ("type \(type) not found for cholesky decomposition") } } } <file_sep>#include<vsip.h> #include"svd.h" static void cmprint_f(vsip_cmview_f *A){ vsip_length n=vsip_cmgetrowlength_f(A); vsip_length m=vsip_cmgetcollength_f(A); vsip_index i,j; printf("["); for(i=0; i<m; i++){ for(j=0; j<n; j++){ vsip_cscalar_f a=vsip_cmget_f(A,i,j); printf("%.5f%+.5fi ",a.r,a.i); if(j < n - 1) printf(","); } printf(";\n") ; } printf("]\n"); } static void vprint_f(vsip_vview_f *v){ vsip_index i; printf("["); for(i=0; i<vsip_vgetlength_f(v); i++) printf("%+.5f ",vsip_vget_f(v,i)); printf("]\n"); } static vsip_scalar_f cmnormFro_f(vsip_cmview_f *v){ vsip_mview_f* re=vsip_mrealview_f(v); vsip_mview_f* im=vsip_mimagview_f(v); return vsip_sqrt_f(vsip_msumsqval_f(re)+vsip_msumsqval_f(im)); vsip_mdestroy_f(re);vsip_mdestroy_f(im); } static vsip_scalar_f ccheckBack_f(vsip_cmview_f* A,vsip_cmview_f* L, vsip_vview_f* d, vsip_cmview_f* R){ vsip_scalar_f c; vsip_cmview_f *VH=vsip_cmcreate_f(vsip_cmgetcollength_f(R),vsip_cmgetrowlength_f(R),VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *Ac=vsip_cmcreate_f(vsip_cmgetcollength_f(A),vsip_cmgetrowlength_f(A),VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *L0=vsip_cmsubview_f(L,0,0,vsip_cmgetcollength_f(L),vsip_vgetlength_f(d)); vsip_cmcopy_f_f(R,VH); vsip_rvcmmul_f(d,VH,VSIP_COL,VH); vsip_cmprod_f(L0,VH,Ac); vsip_cmsub_f(A,Ac,Ac); c = cmnormFro_f(Ac); vsip_cmalldestroy_f(VH);vsip_cmalldestroy_f(Ac);vsip_cmdestroy_f(L0); return c; } int main(int argc, char* argv[]){ int init=vsip_init((void*)0); if(init) exit(0); csvdObj_f s; vsip_cmview_f *A = vsip_cmcreate_f(8,6,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *Ar=vsip_mrealview_f(A); vsip_mview_f *Ai=vsip_mimagview_f(A); vsip_vview_f *ar = vsip_vbind_f(vsip_mgetblock_f(Ar),0,1,48); vsip_vview_f *ai = vsip_vbind_f(vsip_mgetblock_f(Ai),0,1,48); vsip_randstate *rnd=vsip_randcreate(5,1,1,VSIP_PRNG); vsip_vrandn_f(rnd,ar); vsip_vrandn_f(rnd,ai); cmprint_f(A); printf("\n"); s=csvd_f(A); cmprint_f(s.L); printf("\n"); vprint_f(s.d); printf("\n"); cmprint_f(s.R); printf("Check value %f\n",ccheckBack_f(A,s.L,s.d,s.R)); vsip_cmalldestroy_f(s.L); vsip_cmalldestroy_f(s.R); vsip_valldestroy_f(s.d); vsip_mdestroy_f(Ar);vsip_mdestroy_f(Ai); vsip_vdestroy_f(ar); vsip_vdestroy_f(ai); vsip_cmalldestroy_f(A); vsip_randdestroy(rnd); vsip_finalize((void*)0); return 1; } <file_sep>/* Created R Judd */ /* Copyright (c) 2006 <NAME> */ /* MIT style license, see Copyright notice in top level directory */ /* $Id: ctoeplitz_f.h,v 1.1 2006/05/16 16:45:18 judd Exp $ */ #include"VU_cvprintm_f.include" static void ctoeplitz_f(void) { vsip_cmview_f *A = vsip_cmcreate_f(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *B = vsip_cmcreate_f(4,1,VSIP_ROW,VSIP_MEM_NONE); vsip_cvview_f *b = vsip_cmcolview_f(B,0); vsip_cvview_f *t = vsip_cvcreate_f(4,VSIP_MEM_NONE), *x = vsip_cvcreate_f(4,VSIP_MEM_NONE), *w = vsip_cvcreate_f(4,VSIP_MEM_NONE), *y = vsip_cvcreate_f(4,VSIP_MEM_NONE); printf("********\nTEST ctoeplitz_f\n"); printf("\nTest ctoeplitz_f\n"); vsip_cvput_f(t,(vsip_index)0,vsip_cmplx_f(1.0,0)); vsip_cvput_f(t,(vsip_index)1,vsip_cmplx_f(0.0,.4)); vsip_cvput_f(t,(vsip_index)2,vsip_cmplx_f(0.0,.2)); vsip_cvput_f(t,(vsip_index)3,vsip_cmplx_f(0.0,.15)); vsip_cvput_f(y,(vsip_index)0,vsip_cmplx_f(4.0,1)); vsip_cvput_f(y,(vsip_index)1,vsip_cmplx_f(-1.0,2)); vsip_cvput_f(y,(vsip_index)2,vsip_cmplx_f(3.0,3)); vsip_cvput_f(y,(vsip_index)3,vsip_cmplx_f(-2.0,-4)); /* place full (lower diagonal) matrix in A */ vsip_cmput_f(A,0,0,vsip_cvget_f(t,0)); vsip_cmput_f(A,1,0,vsip_conj_f(vsip_cvget_f(t,1)));vsip_cmput_f(A,1,1,vsip_cvget_f(t,0)); vsip_cmput_f(A,2,0,vsip_conj_f(vsip_cvget_f(t,2)));vsip_cmput_f(A,2,1,vsip_conj_f(vsip_cvget_f(t,1)));vsip_cmput_f(A,2,2,vsip_cvget_f(t,0)); vsip_cmput_f(A,3,0,vsip_conj_f(vsip_cvget_f(t,3)));vsip_cmput_f(A,3,1,vsip_conj_f(vsip_cvget_f(t,2)));vsip_cmput_f(A,3,2,vsip_conj_f(vsip_cvget_f(t,1)));vsip_cmput_f(A,3,3,vsip_cvget_f(t,0)); vsip_cvcopy_f_f(y,b); /* solve using cholesky */ { vsip_cchol_f *chol = vsip_cchold_create_f(VSIP_TR_LOW,4); vsip_cchold_f(chol,A); vsip_ccholsol_f(chol,B); vsip_cchold_destroy_f(chol); } printf("the solution using cholesky is\n"); VU_cvprintm_f("7.5",b); printf("t=\n");VU_cvprintm_f("6.4",t); printf("y=\n");VU_cvprintm_f("6.4",y); vsip_ctoepsol_f(t,y,w,x); printf("t=\n");VU_cvprintm_f("6.4",t); printf("y=\n");VU_cvprintm_f("6.4",y); printf("the solution using toeplitz is\n"); printf("x=\n");VU_cvprintm_f("6.4",x); vsip_cvsub_f(x,b,w); if(vsip_cmag_f(vsip_cvsumval_f(w)) < .00001) printf("\ncorrect\n"); else printf("\nerror\n"); vsip_cvalldestroy_f(t); vsip_cvalldestroy_f(x); vsip_cvalldestroy_f(w); vsip_cvalldestroy_f(y); vsip_cmalldestroy_f(A); vsip_cvdestroy_f(b); vsip_cmalldestroy_f(B); } <file_sep>## Created RJudd ## Top Level of library distribution RDIR=../.. ## C compiler CC=cc INCLUDEDIR=-I$(RDIR)/include LIBDIR=-L$(RDIR)/lib LIBS= -lvsip -lm OPTIONS=-O2 example: example14.c $(CC) -o example14 example14.c $(OPTIONS) $(INCLUDEDIR) $(LIBDIR) $(LIBS) clean: rm -f example14 example14.exe <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_offset_si.h,v 2.1 2007/04/18 17:05:56 judd Exp $ */ static void get_put_offset_si(void){ printf("********\nTEST get_put_offset_si\n"); { vsip_offset ivo = 3; vsip_stride ivs = 0; vsip_length ivl = 3; vsip_offset jvo = 2; vsip_stride irs = 0, ics = 0; vsip_length irl = 2, icl = 3; vsip_stride ixs = 0, iys = 0, izs = 0; vsip_length ixl = 2, iyl = 3, izl = 4; vsip_block_si *b = vsip_blockcreate_si(80,VSIP_MEM_NONE); vsip_vview_si *v = vsip_vbind_si(b,ivo,ivs,ivl); vsip_mview_si *m = vsip_mbind_si(b,ivo,ics,icl,irs,irl); vsip_tview_si *t = vsip_tbind_si(b,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_offset s; printf("test vgetoffset_si\n"); fflush(stdout); { s = vsip_vgetoffset_si(v); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputoffset_si\n"); fflush(stdout); { vsip_vputoffset_si(v,jvo); s = vsip_vgetoffset_si(v); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /*************************************************************************/ printf("test mgetoffset_si\n"); fflush(stdout); { s = vsip_mgetoffset_si(m); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputoffset_si\n"); fflush(stdout); { vsip_mputoffset_si(m,jvo); s = vsip_mgetoffset_si(m); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /*************************************************************************/ printf("test tgetoffset_si\n"); fflush(stdout); { s = vsip_tgetoffset_si(t); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputoffset_si\n"); fflush(stdout); { vsip_tputoffset_si(t,jvo); s = vsip_tgetoffset_si(t); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } vsip_vdestroy_si(v); vsip_mdestroy_si(m); vsip_talldestroy_si(t); } return; } <file_sep># Python Jvsip **pyJvsip** module This directory contains a module which demonstrates a VSIPL inspired, python vector/matrix signal processing library. The **pyJvsip** module imports the **vsip** module. It must be installed for pyJvsip to work properly. ## Build and Install Should be able to just do > python setup.py install --user ## Notes: * There seem to be continual changes to python and it's environment which have caused problems. I have changed the intall to --user which seems to cause fewer problems. Distutils seems to be deprecated but still around and how to replace it is not clear. I have more trouble on my apple devices. I also build and test on a raspberry pi which seems to be less sensitive. The code works. Getting it installed may require the use of a python knowledgable person. * The **vsip** module is the raw C VSIPL library as a python module. Encapsulation was done using SWIG. [SWIG](http://www.swig.org) provides type information in the encapsulation but all the naming and use of VSIPL functions remains pretty much the same as in C VSIPL. * The **pyJvsip** module defines true python clases to wrap the C VSIPL objects. For instance pyJvsip has a block and view class which wrap the C VSIPL block and view objects in a python object. No init, finalize, create or destroy is required in the pyJvsip implementation as all that is handled by the pyJvsip implementation and the python garbage collector. <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: tget_put_uc.h,v 2.0 2003/02/22 15:23:35 judd Exp $ */ static void tget_put_uc(void){ printf("********\nTEST tget_put_uc\n"); { vsip_scalar_uc data_a[] = { 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 2, 1, 1, 2, 1, 2}; vsip_scalar_uc ans[2][3][3] = {{{ 0, 1, 1},{ 0, 1, 0}, { 1, 0, 0}}, {{ 1, 0, 1}, {2, 1, 1},{ 2, 1, 2}}}; vsip_block_uc *block_a = vsip_blockbind_uc(data_a,18,VSIP_MEM_NONE); vsip_tview_uc *a = vsip_tbind_uc(block_a,0,9,2,3,3,1,3); vsip_block_uc *block_b = vsip_blockcreate_uc(50,VSIP_MEM_NONE); vsip_tview_uc *b = vsip_tbind_uc(block_b,2,22,2,7,3,2,3); vsip_index h,i,j; vsip_blockadmit_uc(block_a,VSIP_TRUE); /* copy <a> into <b> */ for(h=0; h<2; h++) for(i=0; i<3; i++) for(j=0; j<3; j++) vsip_tput_uc(b,h,i,j,vsip_tget_uc(a,h,i,j)); /* check <a> against ans */ printf("check unit stride compact view\n"); for(h=0; h<2; h++) for(i=0; i<3; i++) for(j=0; j<3; j++) { vsip_scalar_uc chk = (ans[h][i][j] - vsip_tget_uc(a,h,i,j)); (chk == 0) ? printf("correct\n") : printf("error\n"); fflush(stdout); } printf("check general stride view\n"); for(h=0; h<2; h++) for(i=0; i<3; i++) for(j=0; j<3; j++) { vsip_scalar_uc chk = (ans[h][i][j] - vsip_tget_uc(b,h,i,j)); (chk == 0) ? printf("correct\n") : printf("error\n"); fflush(stdout); } vsip_talldestroy_uc(a); vsip_talldestroy_uc(b); } return; } <file_sep>/* Created R Judd */ /* Copyright (c) 2006 <NAME> */ /* MIT style license, see Copyright notice in top level directory */ /* $Id: toeplitz_d.h,v 1.1 2006/05/16 16:45:18 judd Exp $ */ #include"VU_vprintm_d.include" static void toeplitz_d(void) { vsip_mview_d *A = vsip_mcreate_d(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *B = vsip_mcreate_d(4,1,VSIP_ROW,VSIP_MEM_NONE); vsip_vview_d *b = vsip_mcolview_d(B,0); vsip_vview_d *t = vsip_vcreate_d(4,VSIP_MEM_NONE), *x = vsip_vcreate_d(4,VSIP_MEM_NONE), *w = vsip_vcreate_d(4,VSIP_MEM_NONE), *y = vsip_vcreate_d(4,VSIP_MEM_NONE); printf("********\nTEST toeplitz_d\n"); printf("\nTest toeplitz_d\n"); vsip_vput_d(t,(vsip_index)0,(vsip_scalar_d)5.0); vsip_vput_d(t,(vsip_index)1,(vsip_scalar_d)0.5); vsip_vput_d(t,(vsip_index)2,(vsip_scalar_d)0.2); vsip_vput_d(t,(vsip_index)3,(vsip_scalar_d)0.1); vsip_vput_d(y,(vsip_index)0,(vsip_scalar_d)4.0); vsip_vput_d(y,(vsip_index)1,(vsip_scalar_d)-1.0); vsip_vput_d(y,(vsip_index)2,(vsip_scalar_d)3.0); vsip_vput_d(y,(vsip_index)3,(vsip_scalar_d)-2.0); /* place full matrix in A */ vsip_mput_d(A,0,0,vsip_vget_d(t,0)); vsip_mput_d(A,0,1,vsip_vget_d(t,1)); vsip_mput_d(A,0,2,vsip_vget_d(t,2)); vsip_mput_d(A,0,3,vsip_vget_d(t,3)); vsip_mput_d(A,1,0,vsip_vget_d(t,1)); vsip_mput_d(A,1,1,vsip_vget_d(t,0)); vsip_mput_d(A,1,2,vsip_vget_d(t,1)); vsip_mput_d(A,1,3,vsip_vget_d(t,2)); vsip_mput_d(A,2,0,vsip_vget_d(t,2)); vsip_mput_d(A,2,1,vsip_vget_d(t,1)); vsip_mput_d(A,2,2,vsip_vget_d(t,0)); vsip_mput_d(A,2,3,vsip_vget_d(t,1)); vsip_mput_d(A,3,0,vsip_vget_d(t,3)); vsip_mput_d(A,3,1,vsip_vget_d(t,2)); vsip_mput_d(A,3,2,vsip_vget_d(t,1)); vsip_mput_d(A,3,3,vsip_vget_d(t,0)); /* place y in B */ vsip_vcopy_d_d(y,b); /* solve using cholesky */ { vsip_chol_d *chol = vsip_chold_create_d(VSIP_TR_LOW,4); vsip_chold_d(chol,A); vsip_cholsol_d(chol,B); vsip_chold_destroy_d(chol); } printf("the solution using cholesky is\n"); VU_vprintm_d("7.5",b); printf("t=\n");VU_vprintm_d("6.4",t); printf("y=\n");VU_vprintm_d("6.4",y); vsip_toepsol_d(t,y,w,x); printf("t=\n");VU_vprintm_d("6.4",t); printf("y=\n");VU_vprintm_d("6.4",y); printf("w=\n");VU_vprintm_d("6.4",w); printf("the solution using toeplitz is\n"); printf("x=\n");VU_vprintm_d("6.4",x); vsip_vsub_d(x,b,b); if(fabs(vsip_vsumval_d(b)) < .00001) printf("\ncorrect\n"); else printf("\nerror\n"); vsip_valldestroy_d(t); vsip_valldestroy_d(x); vsip_valldestroy_d(w); vsip_valldestroy_d(y); vsip_malldestroy_d(A); vsip_vdestroy_d(b); vsip_malldestroy_d(B); } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: meuler_f.h,v 2.0 2003/02/22 15:23:24 judd Exp $ */ #include"VU_mprintm_f.include" #include"VU_cmprintm_f.include" static void meuler_f(void){ printf("\n*******\nTEST meuler_f\n\n"); { vsip_scalar_f data[] = {M_PI/8.0, M_PI/4.0, M_PI/3.0, M_PI/1.5, 1.25 * M_PI, 1.75 * M_PI}; vsip_scalar_f ans_r[] = {0.9239, 0.7071, 0.5000, -0.5000, -0.7071, 0.7071}; vsip_scalar_f ans_i[] = {0.3827, 0.7071, 0.8660, 0.8660, -0.7071, -0.7071}; vsip_block_f *block = vsip_blockbind_f(data,6,VSIP_MEM_NONE); vsip_cblock_f *ans_block = vsip_cblockbind_f(ans_r,ans_i,6,VSIP_MEM_NONE); vsip_mview_f *a = vsip_mbind_f(block,0,2,3,1,2); vsip_cmview_f *ansm = vsip_cmbind_f(ans_block,0,2,3,1,2); vsip_cmview_f *b = vsip_cmcreate_f(3,2,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *chk = vsip_cmcreate_f(3,2,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *chk_r = vsip_mrealview_f(chk); vsip_blockadmit_f(block,VSIP_TRUE); vsip_cblockadmit_f(ans_block,VSIP_TRUE); printf("test out of place, compact, user \"a\", vsipl \"b\"\n"); vsip_meuler_f(a,b); printf("meuler_f(a,b)\n matrix a\n");VU_mprintm_f("8.6",a); printf("matrix b\n");VU_cmprintm_f("8.6",b); printf("answer\n");VU_cmprintm_f("8.4",ansm); vsip_cmsub_f(b,ansm,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); printf("check meuler_f in place, <a> realview of <b>.\n"); { vsip_mview_f *d = vsip_mrealview_f(b); vsip_mcopy_f_f(a,d); vsip_meuler_f(d,b); vsip_cmsub_f(b,ansm,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_mdestroy_f(d); } vsip_malldestroy_f(a); vsip_cmalldestroy_f(b); vsip_mdestroy_f(chk_r); vsip_cmalldestroy_f(chk); vsip_cmalldestroy_f(ansm); } return; } <file_sep>import Cocoa public func makeRGBImage(width: Int, height: Int, buffer: [Double]) -> CGContext { let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue let colorSpace = CGColorSpaceCreateDeviceRGB() let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 4 * width, space: colorSpace, bitmapInfo: bitmapInfo) var pix: [UInt8] = [0,0,0,0] let dta = UnsafeMutablePointer<UInt8>(mutating: context?.data?.assumingMemoryBound(to: UInt8.self))! // Write image data for y in 0..<height { let jmp = 4 * width * y for x in 0..<width { let indxBuf = y * width + x setRGB(ptr: &pix, val: buffer[indxBuf]) let indxPix = 4 * x + jmp dta[indxPix] = pix[0] // red dta[indxPix+1] = pix[1] // green dta[indxPix+2] = pix[2] // blue dta[indxPix+3] = pix[3] // alpha } } return context! } public func setRGB(ptr: inout [UInt8], val: Double) { var v = Int(val * 767) if (v < 0) { v = 0 } else if (v > 767){ v = 767 } let offset: Int = v % 256 if (v<256) { ptr[0] = 0; ptr[1] = 0; ptr[2] = UInt8(offset) } else if (v<512) { ptr[0] = 0; ptr[1] = UInt8(offset); ptr[2] = 255 - UInt8(offset) } else { ptr[0] = UInt8(offset); ptr[1] = 255 - UInt8(offset); ptr[2] = 0 } ptr[3] = 255 } <file_sep>/* Created RJudd September 19, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_tbind_li.c,v 2.0 2003/02/22 15:19:05 judd Exp $ */ #define VI_TVIEW_I_ #include"VI_support_priv_li.h" vsip_tview_li *vsip_tbind_li( const vsip_block_li *block, vsip_offset offset, vsip_stride z_stride, vsip_length z_length, vsip_stride y_stride, vsip_length y_length, vsip_stride x_stride, vsip_length x_length) { vsip_tview_li *tview = VI_tview_li(); if(tview != NULL){ tview->block = (vsip_block_li*) block; tview->offset = offset; tview->z_length = z_length; tview->y_length = y_length; tview->x_length = x_length; tview->z_stride = z_stride; tview->y_stride = y_stride; tview->x_stride = x_stride; tview->markings = VSIP_VALID_STRUCTURE_OBJECT; } return tview; } <file_sep>/* Created RJudd August 29, 1999 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_covsol_d.c,v 2.1 2006/05/07 15:54:34 judd Exp $ */ #include"vsip.h" #include"vsip_qrdattributes_d.h" #include"VI_mrowview_d.h" #include"VI_vput_d.h" #include"VI_vget_d.h" static void VI_vsubvmprodIP_d( vsip_vview_d *a, vsip_mview_d *B, vsip_vview_d *r) { vsip_scalar_d temp; vsip_length nx = 0, mx = 0; vsip_scalar_d *ap = a->block->array + a->offset * a->block->rstride, *ap0 = ap, *rp = r->block->array + r->offset * a->block->rstride, *Byp = B->block->array + B->offset * a->block->rstride, *Bxp = Byp; vsip_stride BCst = B->col_stride * B->block->rstride, BRst = B->row_stride * B->block->rstride, rst = r->stride * r->block->rstride; while(nx++ < B->row_length){ temp = 0; mx = 0; while(mx++ < B->col_length){ temp += (*ap * *Byp); ap += a->stride; Byp += BCst; } *rp -= temp; ap = ap0; Byp = (Bxp += BRst); rp += rst; } } static void VI_solve_ut_d( vsip_mview_d *R, vsip_mview_d *B) { vsip_length N = R->row_length; vsip_mview_d XX = *B; vsip_mview_d *X = &XX; vsip_vview_d xx, rr; vsip_vview_d *x = VI_mrowview_d(X,(vsip_index) (N-1),&xx); vsip_vview_d *r_d = VI_mrowview_d(R,(vsip_index) 0,&rr); vsip_vview_d rr_m = rr; vsip_vview_d *r_m = &rr_m; vsip_stride d_s = R->row_stride + R->col_stride; r_d->length = 1; r_d->offset += ((N-1) * d_s); r_m->length = 0; r_m->offset = r_d->offset + R->row_stride; X->col_length = 1; X->offset = x->offset; vsip_svmul_d((vsip_scalar_d) 1.0/(VI_VGET_D(r_d,0)),x,x); N--; while(N-- >0){ r_d->offset -= d_s; r_m->length++; r_m->offset -= d_s; x->offset -= X->col_stride; VI_vsubvmprodIP_d(r_m,X,x); vsip_svmul_d((vsip_scalar_d) 1.0/(VI_VGET_D(r_d,0)),x,x); X->col_length++; X->offset = x->offset; } return; } static void VI_solve_lt_d( vsip_mview_d *R, vsip_mview_d *B) { vsip_length N = R->row_length; vsip_mview_d XX = *B; vsip_mview_d *X = &XX; vsip_vview_d xx, rr; vsip_vview_d *x = VI_mrowview_d(X,(vsip_index)0,&xx); vsip_vview_d *r_d = VI_mrowview_d(R,(vsip_index) 0,&rr); vsip_vview_d rr_m = rr; vsip_vview_d *r_m = &rr_m; vsip_stride d_s = R->row_stride + R->col_stride; r_d->length = 1; r_m->length = 0; X->col_length = 1; vsip_svmul_d((vsip_scalar_d) 1.0/(VI_VGET_D(r_d,0)),x,x); N--; while(N-- >0){ r_d->offset += d_s; r_m->length++; r_m->offset += R->col_stride; x->offset += X->col_stride; VI_vsubvmprodIP_d(r_m,X,x); vsip_svmul_d((vsip_scalar_d) 1.0/(VI_VGET_D(r_d,0)),x,x); X->col_length++; } return; } static void VI_qrdsolr_d( vsip_mview_d *R0, vsip_mat_op OpR, vsip_mview_d *X0) { vsip_mview_d XX = *X0, RR = *R0; vsip_mview_d *X= &XX, *R = &RR; if(OpR == VSIP_MAT_NTRANS){ VI_solve_ut_d(R,X); } else { vsip_stride t_s = R->row_stride; R->row_stride = R->col_stride; R->col_stride = t_s; VI_solve_lt_d(R,X); } return; } /*------------------------------------------------* | Algorithm 5.2.2 From GVL | *------------------------------------------------*/ /* --------------------------------------------------------- * | VU_givens_d.h | | Algorithm 5.1.3 From GVL | | calculate cosine "c" and sine "s" of a givens rotation | *-----------------------------------------------------------*/ static void VI_givens_d( vsip_scalar_d a, vsip_scalar_d b, vsip_scalar_d *c, vsip_scalar_d *s, vsip_scalar_d *r){ vsip_scalar_d t; if(b == 0){ *c = 1; *s = 0; } else { if(fabs(b) > fabs(a)){ t = -a/b; *s = (vsip_scalar_d)(1.0/sqrt(1 + t * t)); *c = *s * t; } else { t = -b/a; *c = (vsip_scalar_d)(1.0/sqrt(1 + t * t)); *s = *c * t; } } *r = *c * a - *s * b; return; } static int VI_givens_r_d( vsip_mview_d *A) { int retval = 0; vsip_length m = A->col_length; vsip_length n = A->row_length; vsip_length i,j,k; vsip_scalar_d c=0,s=0,r=0; vsip_stride r_st = A->row_stride * A->block->rstride; for(j=0; j<n; j++){ for(i=m-1; i>j; i--){ vsip_scalar_d *a0p = A->block->array + (A->offset + (i-1) * A->col_stride + j * A->row_stride) * A->block->rstride; vsip_scalar_d *a1p = A->block->array + (A->offset + i * A->col_stride + j * A->row_stride) * A->block->rstride; VI_givens_d(*a0p,*a1p,&c,&s,&r); if(r == 0) retval++; *a0p = r; *a1p = 0; a1p += r_st; a0p +=r_st; for(k=1; k<n-j; k++){ vsip_scalar_d a0 = *a0p, a1 = *a1p; *a0p = a0 * c - a1 * s; *a1p = a0 * s + a1 * c; a1p += r_st; a0p +=r_st; } } } return retval; } int vsip_covsol_d( const vsip_mview_d *A, const vsip_mview_d *XB) { int retval = 0; vsip_mview_d RR = *A; vsip_mview_d *R = &RR; vsip_mview_d XX = *XB; vsip_mview_d *X = &XX; retval += VI_givens_r_d(R); VI_qrdsolr_d(R,VSIP_MAT_TRANS,X); VI_qrdsolr_d(R,VSIP_MAT_NTRANS,X); return retval; } <file_sep>// // svd.swift // // // Created by <NAME> on 11/10/17. // import Foundation import vsip public class Svd { let type: Scalar.Types let n: Int // length of singular value vector var amSet = false fileprivate let jVsip : sv? var vecSv: Vector? public struct Attrib { let m: Int let n: Int let saveU: vsip_svd_uv let saveV: vsip_svd_uv init(columnLength: Int, rowLength: Int, saveU: vsip_svd_uv, saveV: vsip_svd_uv){ m=columnLength n=rowLength self.saveU=saveU self.saveV=saveV } var size : (Int, Int) { return (m,n) } } let attr : Attrib fileprivate class sv { var tryVsip : OpaquePointer? var tryS: OpaquePointer? var vsip: OpaquePointer { get { return tryVsip! } } var s: OpaquePointer { get { return tryS! } } let jInit : JVSIP var type : Scalar.Types? init(){ jInit = JVSIP() } } fileprivate class sv_f : sv { init(m: Int, n: Int, saveU: vsip_svd_uv, saveV: vsip_svd_uv){ super.init() type = .f if let svd = vsip_svd_create_f(vsip_length(m),vsip_length(n),saveU,saveV){ self.tryVsip = svd } else { preconditionFailure("Failed to create vsip svd object") } if let s = vsip_vcreate_f(vsip_length((m<n) ? m:n),VSIP_MEM_NONE){ self.tryS = s } else { preconditionFailure("Failed to create vsip s object") } } deinit{ /* if _isDebugAssertConfiguration(){ print("vsip_svd_destroy_f \(jInit.myId.int32Value)") print("svd s destroy") }*/ vsip_svd_destroy_f(self.vsip) vsip_valldestroy_f(self.s) } } fileprivate class sv_d : sv { init(m: Int, n: Int, saveU: vsip_svd_uv, saveV: vsip_svd_uv){ super.init() type = .f if let svd = vsip_svd_create_d(vsip_length(m),vsip_length(n),saveU,saveV){ self.tryVsip = svd } else { preconditionFailure("Failed to create vsip svd object") } if let s = vsip_vcreate_d(vsip_length((m<n) ? m:n),VSIP_MEM_NONE){ self.tryS = s } else { preconditionFailure("Failed to create vsip s object") } } deinit{ /* if _isDebugAssertConfiguration(){ print("vsip_svd_destroy_d \(jInit.myId.int32Value)") print("svd s destroy") }*/ vsip_svd_destroy_d(self.vsip) vsip_valldestroy_d(self.s) } } fileprivate class csv_f : sv { init(m: Int, n: Int, saveU: vsip_svd_uv, saveV: vsip_svd_uv){ super.init() type = .cf if let svd = vsip_csvd_create_f(vsip_length(m),vsip_length(n),saveU,saveV){ self.tryVsip = svd } else { preconditionFailure("Failed to create vsip svd object") } if let s = vsip_vcreate_f(vsip_length((m<n) ? m:n),VSIP_MEM_NONE){ self.tryS = s } else { preconditionFailure("Failed to create vsip s object") } } deinit{ /* if _isDebugAssertConfiguration(){ print("vsip_svd_destroy_f \(jInit.myId.int32Value)") print("svd s destroy") }*/ vsip_csvd_destroy_f(self.vsip) vsip_valldestroy_f(self.s) } } fileprivate class csv_d : sv { init(m: Int, n: Int, saveU: vsip_svd_uv, saveV: vsip_svd_uv){ super.init() type = .cd if let svd = vsip_csvd_create_d(vsip_length(m),vsip_length(n),saveU,saveV){ self.tryVsip = svd } else { preconditionFailure("Failed to create vsip svd object") } if let s = vsip_vcreate_d(vsip_length((m<n) ? m:n),VSIP_MEM_NONE){ self.tryS = s } else { preconditionFailure("Failed to create vsip s object") } } deinit{ /* if _isDebugAssertConfiguration(){ print("vsip_csvd_destroy_cd \(jInit.myId.int32Value)") print("svd s destroy") }*/ vsip_csvd_destroy_d(self.vsip) vsip_valldestroy_d(self.s) } } public init(type: Scalar.Types,columnLength m: Int, rowLength n: Int, saveU: vsip_svd_uv, saveV: vsip_svd_uv){ self.n = (m<n) ? m:n self.type = type self.attr = Attrib(columnLength: m, rowLength: n, saveU: saveU, saveV: saveV) switch type { case .d: self.jVsip = sv_d(m: m,n: n,saveU: saveU, saveV: saveV) case .f: self.jVsip = sv_f(m: m,n: n,saveU: saveU, saveV: saveV) case .cd: self.jVsip = csv_d(m: m,n: n,saveU: saveU, saveV: saveV) case .cf: self.jVsip = csv_f(m: m,n: n,saveU: saveU, saveV: saveV) default: self.jVsip = nil assert(false, "SVD not supported for this type") } } public convenience init(view: Matrix, saveU: vsip_svd_uv, saveV: vsip_svd_uv){ self.init(type: view.type, columnLength: view.columnLength, rowLength: view.rowLength, saveU: saveU, saveV: saveV) } public convenience init(view: Matrix){ self.init(type: view.type, columnLength: view.columnLength, rowLength: view.rowLength, saveU: VSIP_SVD_UVFULL, saveV: VSIP_SVD_UVFULL) } fileprivate var vsip: OpaquePointer? { return self.jVsip!.vsip } fileprivate var s: OpaquePointer? {// singular values return self.jVsip!.s } public func decompose(_ matrix: Matrix, singularValues: Vector){ switch (self.type, matrix.type, singularValues.type){ case (.d, .d, .d): vsip_svd_d(self.vsip, matrix.vsip, self.s!) vsip_vcopy_d_d(self.s!, singularValues.vsip) case (.f, .f, .f): vsip_svd_f(self.vsip, matrix.vsip, self.s!) vsip_vcopy_f_f(self.s!, singularValues.vsip) case (.cd, .cd, .d): vsip_csvd_d(self.vsip, matrix.vsip, self.s!) vsip_vcopy_d_d(self.s!, singularValues.vsip) case (.cf, .cf, .f): vsip_csvd_f(self.vsip, matrix.vsip, self.s!) vsip_vcopy_f_f(self.s!, singularValues.vsip) default: preconditionFailure("function not supported for input/resultsIn views") } self.vecSv = singularValues.newCopy self.amSet = true } public func decompose(_ matrix: Matrix) -> Vector { let v: Vector switch matrix.type { case .cd, .d: v = Vector(length: self.n, type: .d) case .cf, .f: v = Vector(length: self.n, type: .f) default: preconditionFailure("Case not found for decompose") } self.decompose(matrix, singularValues: v) self.vecSv = v.newCopy return v } /*! Function matU returns 0 on success Output data is stored in matrix matU in natural order starting at element index (0,0). Matrix matU must be large enough to hold the resultsIn data */ public func matU(_ lowColumn: Int, highColumn: Int, matU: Matrix) -> Int { let low = vsip_scalar_vi(lowColumn) let high = vsip_scalar_vi(highColumn) assert(low <= high, "Error in column selection") let highMax = vsip_scalar_vi((matU.rowLength)) let vsipSv = self.vsip // VSIPL pointer to singular value object let vsipC = matU.vsip // VSIPL pointer to U Matrix switch (self.attr.saveU, matU.type, self.type){ case (VSIP_SVD_UVFULL, .f, .f): return Int(vsip_svdmatu_f(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVFULL, .cf, .cf): return Int(vsip_csvdmatu_f(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVFULL, .d, .d): return Int(vsip_svdmatu_d(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVFULL, .cd, .cd): return Int(vsip_csvdmatu_d(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVPART, .f, .f): precondition(high <= highMax, "Input matrix row length to small") return Int(vsip_svdmatu_f(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVPART, .cf, .cf): precondition(high <= highMax, "Input matrix row length to small") return Int(vsip_csvdmatu_f(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVPART, .d, .d): precondition(high <= highMax, "Input matrix row length to small") return Int(vsip_svdmatu_d(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVPART, .cd, .cd): precondition(high <= highMax, "Input matrix row length to small") return Int(vsip_csvdmatu_d(vsipSv, low, high, vsipC)) default: if self.attr.saveU == VSIP_SVD_UVNOS{ preconditionFailure("SVD Created without U Matrix") } else { preconditionFailure("SVD Not supported for these types") } } } /*! Function matV returns 0 on success Output data is stored in matrix matV in natural order starting at element index (0,0). Matrix matV must be large enough to hold the resultsIn data */ public func matV(_ lowColumn: Int, highColumn: Int, matV: Matrix) -> Int { let low = vsip_scalar_vi(lowColumn) let high = vsip_scalar_vi(highColumn) assert(low <= high, "Error in column selection") let highMax = vsip_scalar_vi(matV.rowLength) let vsipSv = self.vsip // VSIPL pointer to singular value object let vsipC = matV.vsip // VSIPL pointer to V Matrix switch (self.attr.saveU, matV.type, self.type){ case (VSIP_SVD_UVFULL, .f, .f): return Int(vsip_svdmatv_f(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVFULL, .cf, .cf): return Int(vsip_csvdmatv_f(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVFULL, .d, .d): return Int(vsip_svdmatv_d(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVFULL, .cd, .cd): return Int(vsip_csvdmatv_d(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVPART, .f, .f): precondition(high <= highMax, "Input matrix row length to small") return Int(vsip_svdmatv_f(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVPART, .cf, .cf): precondition(high <= highMax, "Input matrix row length to small") return Int(vsip_csvdmatv_f(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVPART, .d, .d): precondition(high <= highMax, "Input matrix row length to small") return Int(vsip_svdmatv_d(vsipSv, low, high, vsipC)) case (VSIP_SVD_UVPART, .cd, .cd): precondition(high <= highMax, "Input matrix row length to small") return Int(vsip_csvdmatv_d(vsipSv, low, high, vsipC)) default: if self.attr.saveU == VSIP_SVD_UVNOS { preconditionFailure("SVD Created without V Matrix") } else { preconditionFailure("SVD Not supported for these types") } } } public func produ(op: vsip_mat_op, side: vsip_mat_side, matrix: Matrix) -> Int { let vsipSv = self.vsip let vsipC = matrix.vsip switch (self.attr.saveU, matrix.type, self.type){ case (VSIP_SVD_UVFULL, .f, .f): return Int(vsip_svdprodu_f(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVFULL, .cf, .cf): return Int(vsip_csvdprodu_f(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVFULL, .d, .d): return Int(vsip_svdprodu_d(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVFULL, .cd, .cd): return Int(vsip_csvdprodu_d(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVPART, .f, .f): return Int(vsip_svdprodu_f(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVPART, .cf, .cf): return Int(vsip_csvdprodu_f(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVPART, .d, .d): return Int(vsip_svdprodu_d(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVPART, .cd, .cd): return Int(vsip_csvdprodu_d(vsipSv, op, side, vsipC)) default: if self.attr.saveU == VSIP_SVD_UVNOS { preconditionFailure("SVD Created without U Matrix") } else { preconditionFailure("SVD Not supported for these types") } } } public func prodv(op: vsip_mat_op, side: vsip_mat_side, matrix: Matrix) -> Int { let vsipSv = self.vsip let vsipC = matrix.vsip switch (self.attr.saveV, matrix.type, self.type){ case (VSIP_SVD_UVFULL, .f, .f): return Int(vsip_svdprodv_f(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVFULL, .cf, .cf): return Int(vsip_csvdprodv_f(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVFULL, .d, .d): return Int(vsip_svdprodv_d(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVFULL, .cd, .cd): return Int(vsip_csvdprodv_d(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVPART, .f, .f): return Int(vsip_svdprodv_f(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVPART, .cf, .cf): return Int(vsip_csvdprodv_f(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVPART, .d, .d): return Int(vsip_svdprodv_d(vsipSv, op, side, vsipC)) case (VSIP_SVD_UVPART, .cd, .cd): return Int(vsip_csvdprodv_d(vsipSv, op, side, vsipC)) default: if self.attr.saveU == VSIP_SVD_UVNOS { preconditionFailure("SVD Created without V Matrix") } else { preconditionFailure("SVD Not supported for these types") } } } public var sizeU: (Int, Int){ get { var retval = (self.attr.m, self.attr.m) switch self.attr.saveU { case VSIP_SVD_UVFULL: return retval case VSIP_SVD_UVPART: if self.attr.m > self.attr.n { retval.1 = self.attr.n } return retval default: return (0,0) } } } public var sizeV: (Int, Int){ get { var retval = (self.attr.n, self.attr.n) switch self.attr.saveU { case VSIP_SVD_UVFULL: return retval case VSIP_SVD_UVPART: if self.attr.n > self.attr.m { retval.1 = self.attr.m } return retval default: return (0,0) } } } public var matU: Matrix? { get { if !amSet { return nil } if self.attr.saveU == VSIP_SVD_UVNOS { return nil } let (m,n) = self.sizeU let mat = Matrix(columnLength: m, rowLength: n, type: self.type, major: VSIP_ROW) let success = self.matU(0, highColumn: n-1, matU: mat) if success == 0 { return mat } else { return nil } } } public var matV: Matrix? { get { if !amSet { return nil } if self.attr.saveU == VSIP_SVD_UVNOS { return nil } let (m,n) = self.sizeV let mat = Matrix(columnLength: m, rowLength: n, type: self.type, major: VSIP_ROW) let success = self.matV(0, highColumn: n-1, matV: mat) if success == 0 { return mat } else { return nil } } } public var vecS: Vector { get { let vec = self.vecSv!.newCopy return vec } } } <file_sep>/* Created RJudd */ /* */ #include"VU_cmprintm_f.include" static void cmfreqswap_f(void){ printf("*********\nTEST cmfreqswap_f\n"); { vsip_length M=6,N=5; vsip_cmview_f *a = vsip_cmcreate_f(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_cvview_f *v = vsip_cvbind_f(vsip_cmgetblock_f(a),0,1,M*N); vsip_vview_f *v_r=vsip_vrealview_f(v); vsip_vview_f *v_i=vsip_vimagview_f(v); vsip_cmview_f *ans = vsip_cmcreate_f(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_scalar_f rdta[]={ 18.0, 19.0, 20.0, 16.0, 17.0, 23.0, 24.0, 25.0, 21.0, 22.0, 28.0, 29.0, 30.0, 26.0, 27.0, 3.0, 4.0, 5.0, 1.0, 2.0, 8.0, 9.0, 10.0, 6.0, 7.0, 13.0, 14.0, 15.0, 11.0, 12.0}; vsip_scalar_f idta[]={-18.0,-19.0,-20.0,-16.0,-17.0, -23.0,-24.0,-25.0,-21.0,-22.0, -28.0,-29.0,-30.0,-26.0,-27.0, -3.0,- 4.0,- 5.0,- 1.0,- 2.0, -8.0,- 9.0,-10.0,- 6.0,- 7.0, -13.0,-14.0,-15.0,-11.0,-12.0}; vsip_cmcopyfrom_user_f(rdta,idta,VSIP_ROW,ans); vsip_vramp_f (1,1,v_r); vsip_vramp_f (-1,-1,v_i); printf("input matrix\n"); VU_cmprintm_f("3.1",a); vsip_cmfreqswap_f(a); printf("expected output matrix\n"); VU_cmprintm_f("3.1",ans); printf("output matrix\n"); VU_cmprintm_f("3.1",a); { vsip_cmsub_f(a,ans,ans); if(vsip_mcmaxmgsqval_f(ans,NULL) > .00001){ printf("error\n"); }else{ printf("correct\n"); } } vsip_vdestroy_f(v_r); vsip_vdestroy_f(v_i); vsip_cvdestroy_f(v); vsip_cmalldestroy_f(a); vsip_cmalldestroy_f(ans); } } <file_sep>#include<vsip.h> #include<math.h> #include<assert.h> void mview_store_d(vsip_mview_d *M, char* fname); vsip_mview_d *mcenter_d(vsip_mview_d *gram); vsip_mview_d *cmscale_d(vsip_cmview_d *gram_data); vsip_mview_d *noiseGen( vsip_scalar_d alpha, vsip_length Mp, vsip_length Nn, vsip_length Ns); vsip_mview_d *narrowBandGen( vsip_mview_d *data, vsip_scalar_d alpha, void **targets, vsip_scalar_d Fs); <file_sep>/* * svd6.h * VSIP_svd_fev * * Created by <NAME> on 9/13/08. * Copyright 2008 Home. All rights reserved * */ #include"VU_vprintm_f.include" static void svd6_f(void){ printf("********\nTEST svd6 for float\n"); { vsip_index i; vsip_length M=50, N=100; vsip_randstate *state=vsip_randcreate(4,1,0,VSIP_PRNG); vsip_vview_f *s = vsip_vcreate_f(((M > N) ? N : M),VSIP_MEM_NONE); vsip_sv_f *svd = vsip_svd_create_f(M,N,VSIP_SVD_UVFULL,VSIP_SVD_UVFULL); vsip_mview_f *A0 = vsip_mcreate_f(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_vview_f *va0 = vsip_vbind_f(vsip_mgetblock_f(A0),0,1,M*N); vsip_mview_f *A = vsip_mcreate_f(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *U = vsip_mcreate_f(M,M,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *V = vsip_mcreate_f(N,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *B = vsip_mcreate_f(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_vrandn_f(state,va0); /* Numbers below using gcc from Xcode7 upgrade fail accuracy test */ /* gcc-5 using homebrew instalation in /usr/local/bin works */ vsip_svmul_f(1E-10,va0,va0); /* Numbers below pass accuracy test for Xcode7 version of gcc */ /*vsip_svmul_f(1E-8,va0,va0);*/ vsip_mcopy_f_f(A0,A); if(vsip_svd_f(svd,A,s)){ printf("svd error\n"); return; } /* create the singular value matrix */ vsip_mfill_f(0.0,B); for(i=0; i<vsip_vgetlength_f(s); i++) vsip_mput_f(B,i,i,vsip_vget_f(s,i)); vsip_svdmatu_f(svd, 0, M-1, U); vsip_svdmatv_f(svd, 0, N-1, V); VU_vprintm_f("12.10",s); { /* check that A0 = U * B * V' */ vsip_scalar_f chk = 1.0; vsip_scalar_f lim = 1E-10; vsip_mview_f *dif=vsip_mcreate_f(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *out = vsip_mcreate_f(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *Vt = vsip_mtransview_f(V); vsip_mprod_f(U,B,dif); vsip_mprod_f(dif,Vt,out); vsip_msub_f(out,A0,dif); vsip_mmag_f(dif, dif); chk = vsip_msumval_f(dif)/(2 * M * N); printf("%20.18e - %20.18e = %e\n",lim,chk, (lim - chk)); if(chk > lim){ printf("error\n"); } else { printf("correct\n"); } vsip_malldestroy_f(dif); vsip_malldestroy_f(out); vsip_mdestroy_f(Vt); } vsip_randdestroy(state); vsip_vdestroy_f(va0); vsip_svd_destroy_f(svd); vsip_malldestroy_f(A0); vsip_malldestroy_f(A); vsip_valldestroy_f(s); vsip_malldestroy_f(U); vsip_malldestroy_f(B); vsip_malldestroy_f(V); } return; } <file_sep>/* * vsip_vadd_vi.c * Created by <NAME> on 7/17/06. * Copyright 2006 * See Copyright statement in top level directory */ /* $Id: vsip_vadd_vi.c,v 2.2 2007/04/16 18:40:59 judd Exp $ */ #include"vsip.h" #include"vsip_vviewattributes_vi.h" void (vsip_vadd_vi)( const vsip_vview_vi *a, const vsip_vview_vi *b, const vsip_vview_vi *r) { vsip_length n = r->length; vsip_stride ast = a->stride, bst = b->stride, rst = r->stride; vsip_scalar_vi *ap = (a->block->array) + a->offset, *bp = (b->block->array) + b->offset, *rp = (r->block->array) + r->offset; while(n-- > 0){ *rp = *ap + *bp; ap += ast; bp += bst; rp += rst; } } <file_sep>#include<vsip.h> #include"svd.h" static void mprint_d(vsip_mview_d *A){ vsip_length n=vsip_mgetrowlength_d(A); vsip_length m=vsip_mgetcollength_d(A); vsip_index i,j; printf("["); for(i=0; i<m; i++){ for(j=0; j<n; j++){ printf("%+.5f ",vsip_mget_d(A,i,j)); } printf(";\n") ; } printf("]\n"); } static void vprint_d(vsip_vview_d *v){ vsip_index i; printf("["); for(i=0; i<vsip_vgetlength_d(v); i++) printf("%+.5f ",vsip_vget_d(v,i)); printf("]\n"); } static vsip_scalar_d mnormFro_d(vsip_mview_d *A){ return vsip_sqrt_d(vsip_msumsqval_d(A)); } static vsip_scalar_d checkBack_d(vsip_mview_d* A,vsip_mview_d* L, vsip_vview_d* d, vsip_mview_d* R){ vsip_scalar_d c; vsip_mview_d *VH=vsip_mcreate_d(vsip_mgetcollength_d(R),vsip_mgetrowlength_d(R),VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *Ac=vsip_mcreate_d(vsip_mgetcollength_d(A),vsip_mgetrowlength_d(A),VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *L0=vsip_msubview_d(L,0,0,vsip_mgetcollength_d(L),vsip_vgetlength_d(d)); vsip_mcopy_d_d(R,VH); vsip_vmmul_d(d,VH,VSIP_COL,VH); vsip_mprod_d(L0,VH,Ac); vsip_msub_d(A,Ac,Ac); c = mnormFro_d(Ac); vsip_malldestroy_d(VH);vsip_malldestroy_d(Ac);vsip_mdestroy_d(L0); return c; } int main(int argc, char* argv[]){ int init=vsip_init((void*)0); if(init) exit(0); svdObj_d s; vsip_mview_d *A = vsip_mcreate_d(8,6,VSIP_ROW,VSIP_MEM_NONE); vsip_vview_d *a = vsip_vbind_d(vsip_mgetblock_d(A),0,1,48); vsip_randstate *rnd=vsip_randcreate(5,1,1,VSIP_PRNG); vsip_vrandn_d(rnd,a); mprint_d(A); printf("\n"); s=svd_d(A); mprint_d(s.L); printf("\n"); vprint_d(s.d); printf("\n"); mprint_d(s.R); printf("Check value %f\n",checkBack_d(A,s.L,s.d,s.R)); vsip_malldestroy_d(s.L); vsip_malldestroy_d(s.R); vsip_valldestroy_d(s.d); vsip_vdestroy_d(a); vsip_malldestroy_d(A); vsip_randdestroy(rnd); vsip_finalize((void*)0); return 1; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmget_put_f.h,v 2.0 2003/02/22 15:23:32 judd Exp $ */ static void cmget_put_f(void){ printf("********\nTEST cmget_put_f\n"); { vsip_scalar_f datar_a[] = { 0, 1, 1, 0, 1, 0}; vsip_scalar_f datai_a[] = { 1, -1, -1, 1, -1, 1}; vsip_scalar_f ansr[2][3] = {{ 0, 1, 1},{ 0, 1, 0}}; vsip_scalar_f ansi[2][3] = {{ 1, -1, -1},{ 1, -1, 1}}; vsip_cblock_f *block_a = vsip_cblockbind_f(datar_a,datai_a,6,VSIP_MEM_NONE); vsip_cmview_f *a = vsip_cmbind_f(block_a,0,3,2,1,3); vsip_cblock_f *block_b = vsip_cblockcreate_f(50,VSIP_MEM_NONE); vsip_cmview_f *b = vsip_cmbind_f(block_b, 35,-8,2,-2,3); vsip_index i,j; vsip_cblockadmit_f(block_a,VSIP_TRUE); /* copy <a> into <b> */ for(j=0; j<3; j++) for(i=0; i<2; i++) vsip_cmput_f(b,i,j,vsip_cmget_f(a,i,j)); /* check <a> against ans */ printf("check unit stride compact view\n"); for(j=0; j<3; j++) for(i=0; i<2; i++){ vsip_cscalar_f chk = vsip_cmget_f(a,i,j); chk.r = chk.r - ansr[i][j]; chk.i = chk.i - ansi[i][j]; chk.r = chk.r * chk.r + chk.i * chk.i; (chk.r < 0.0001) ? printf("correct\n") : printf("error\n"); fflush(stdout); } printf("check general stride view\n"); for(j=0; j<3; j++) for(i=0; i<2; i++){ vsip_cscalar_f chk = vsip_cmget_f(b,i,j); chk.r = chk.r - ansr[i][j]; chk.i = chk.i - ansi[i][j]; chk.r = chk.r * chk.r + chk.i * chk.i; (chk.r < 0.0001) ? printf("correct\n") : printf("error\n"); fflush(stdout); } vsip_cmalldestroy_f(a); vsip_cmalldestroy_f(b); } return; } <file_sep>/* Created RJudd September 18, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vcreate_mi.c,v 2.0 2003/02/22 15:19:12 judd Exp $ */ #include"vsip.h" #include"VI_blockcreate_mi.h" #include"VI_blockdestroy_mi.h" vsip_vview_mi* (vsip_vcreate_mi)( vsip_length n, vsip_memory_hint h) { vsip_block_mi* b = VI_blockcreate_mi((vsip_length)n*2, h); vsip_vview_mi* v = (vsip_vview_mi*)NULL; if(b != (vsip_block_mi*)NULL){ v = vsip_vbind_mi(b, (vsip_offset)0, (vsip_stride)1, n); if(v == (vsip_vview_mi*)NULL) VI_blockdestroy_mi(b); } return v; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_offset_i.h,v 2.1 2007/04/18 17:05:56 judd Exp $ */ static void get_put_offset_i(void){ printf("********\nTEST get_put_offset_i\n"); { vsip_offset ivo = 3; vsip_stride ivs = 0; vsip_length ivl = 3; vsip_offset jvo = 2; vsip_stride irs = 0, ics = 0; vsip_length irl = 2, icl = 3; vsip_stride ixs = 0, iys = 0, izs = 0; vsip_length ixl = 2, iyl = 3, izl = 4; vsip_block_i *b = vsip_blockcreate_i(80,VSIP_MEM_NONE); vsip_vview_i *v = vsip_vbind_i(b,ivo,ivs,ivl); vsip_mview_i *m = vsip_mbind_i(b,ivo,ics,icl,irs,irl); vsip_tview_i *t = vsip_tbind_i(b,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_offset s; printf("test vgetoffset_i\n"); fflush(stdout); { s = vsip_vgetoffset_i(v); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputoffset_i\n"); fflush(stdout); { vsip_vputoffset_i(v,jvo); s = vsip_vgetoffset_i(v); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /*************************************************************************/ printf("test mgetoffset_i\n"); fflush(stdout); { s = vsip_mgetoffset_i(m); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputoffset_i\n"); fflush(stdout); { vsip_mputoffset_i(m,jvo); s = vsip_mgetoffset_i(m); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /*************************************************************************/ printf("test tgetoffset_i\n"); fflush(stdout); { s = vsip_tgetoffset_i(t); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputoffset_i\n"); fflush(stdout); { vsip_tputoffset_i(t,jvo); s = vsip_tgetoffset_i(t); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } vsip_vdestroy_i(v); vsip_mdestroy_i(m); vsip_talldestroy_i(t); } return; } <file_sep>//: Playground - noun: a place where people can play import Foundation let N = 16812*7*11*7*7*19*27*89*1280 let p = nuV(N: N) print(N) print(p.0) print(p.1) print(p.2) var n = pow(Double(p.1[0]), Double(p.0[0])) for i in 1..<p.0.count{ n *= pow(Double(p.1[i]), Double(p.0[i])) } print(n) <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_stride_uc.h,v 2.1 2007/04/18 17:05:56 judd Exp $ */ static void get_put_stride_uc(void){ printf("********\nTEST get_put_stride_uc\n"); { vsip_offset ivo = 3; vsip_stride ivs = 2; vsip_length ivl = 3; vsip_stride jvs = 3; vsip_stride irs = 1, ics = 3; vsip_length irl = 2, icl = 3; vsip_stride jrs = 5, jcs = 2; vsip_stride ixs = 2, iys = 4, izs = 14; vsip_length ixl = 2, iyl = 3, izl = 4; vsip_stride jxs = 4, jys = 14, jzs = 2; vsip_block_uc *b = vsip_blockcreate_uc(80,VSIP_MEM_NONE); vsip_vview_uc *v = vsip_vbind_uc(b,ivo,ivs,ivl); vsip_mview_uc *m = vsip_mbind_uc(b,ivo,ics,icl,irs,irl); vsip_tview_uc *t = vsip_tbind_uc(b,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_stride s; printf("test vgetstride_uc\n"); fflush(stdout); { s = vsip_vgetstride_uc(v); (s == ivs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputstride_uc\n"); fflush(stdout); { vsip_vputstride_uc(v,jvs); s = vsip_vgetstride_uc(v); (s == jvs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /*************************************************************************/ printf("test mgetrowstride_uc\n"); fflush(stdout); { s = vsip_mgetrowstride_uc(m); (s == irs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputrowstride_uc\n"); fflush(stdout); { vsip_mputrowstride_uc(m,jrs); s = vsip_mgetrowstride_uc(m); (s == jrs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test mgetcolstride_uc\n"); fflush(stdout); { s = vsip_mgetcolstride_uc(m); (s == ics) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputcolstride_uc\n"); fflush(stdout); { vsip_mputcolstride_uc(m,jcs); s = vsip_mgetcolstride_uc(m); (s == jcs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /*************************************************************************/ printf("test tgetxstride_uc\n"); fflush(stdout); { s = vsip_tgetxstride_uc(t); (s == ixs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputxstride_uc\n"); fflush(stdout); { vsip_tputxstride_uc(t,jxs); s = vsip_tgetxstride_uc(t); (s == jxs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test tgetystride_uc\n"); fflush(stdout); { s = vsip_tgetystride_uc(t); (s == iys) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputystride_uc\n"); fflush(stdout); { vsip_tputystride_uc(t,jys); s = vsip_tgetystride_uc(t); (s == jys) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test tgetzstride_uc\n"); fflush(stdout); { s = vsip_tgetzstride_uc(t); (s == izs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputzstride_uc\n"); fflush(stdout); { vsip_tputzstride_uc(t,jzs); s = vsip_tgetzstride_uc(t); (s == jzs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } vsip_vdestroy_uc(v); vsip_mdestroy_uc(m); vsip_talldestroy_uc(t); } return; } <file_sep>/* Created By RJudd August 3, 2002 */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_jofk.h,v 2.0 2003/02/22 15:18:32 judd Exp $ */ #ifndef VI_JOFK__H #define VI_JOFK__H #include"vsip.h" /* Index conversion routine for DFT's */ /* 2.2.3 of Van Loan, "computational Frameworks for the */ /* Fast Fourier Transform */ static vsip_scalar_vi VI_jofk(vsip_scalar_vi k, /* index to reverse */ vsip_scalar_vi *pn, vsip_scalar_vi *p0, vsip_scalar_vi pF, vsip_length fn) { vsip_scalar_vi l = (vsip_scalar_vi)fn; vsip_scalar_vi i,q; vsip_scalar_vi j = 0; vsip_scalar_vi m = k; vsip_scalar_vi aq,s,p; for(q = 0; q < l; q++){ i = pn[q] - 1; p = p0[q]; while(i-- > 0){ s = m/p; aq = m - s * p; j = p * j + aq; m = s; } } s = m/pF; aq = m - s * pF; j = pF * j + aq; return j; } #endif <file_sep>/* Created <NAME> March 12, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mprodt_d.c,v 2.1 2003/03/08 14:43:34 judd Exp $ */ /* modified to vsip_mprodt_d.c */ /* April 21, 1998 1,2 to row,col */ /* Removed Tisdale error checking Sept 00 */ #include"vsip.h" #include"vsip_mviewattributes_d.h" #include"vsip_vviewattributes_d.h" #include"VI_mrowview_d.h" void (vsip_mprodt_d)( const vsip_mview_d* A, const vsip_mview_d* B, const vsip_mview_d* R) { { vsip_length M = A->col_length, N = B->col_length; vsip_length i,j; vsip_vview_d bb,aa,rr; for(i = 0; i < M; i++){ vsip_vview_d *a = VI_mrowview_d(A, i,&aa), *r = VI_mrowview_d(R, i,&rr); vsip_scalar_d *r_p = r->block->array + r->offset * r->block->rstride; for(j =0; j < N; j++){ vsip_vview_d *b = VI_mrowview_d(B,j,&bb); *r_p = vsip_vdot_d(a,b); r_p += r->stride; } } } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mprod_f.h,v 2.2 2007/04/18 17:05:54 judd Exp $ */ #include"VU_mprintm_f.include" static void mprod_f(void){ printf("********\nTEST mprod_f\n"); { vsip_scalar_f datal[] = {1, 2.0, 3.0, 4, 5.0, 5, .1, .2, .3, .4, 4, 3.0, 2.0, 0, -1.0}; vsip_scalar_f datar[] = { .1, .2, .3, .4, 1.0, 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 2.4, -1.1, -1.2, -1.3, -1.4, 2.1, 2.2, 2.3, 3.4}; vsip_scalar_f ans_data[] = { 14.5, 15.2, 15.9, 21.6, 1.53, 2.07, 2.61, 3.55, 5.5, 6.3, 7.1, 6.90}; vsip_block_f *blockl = vsip_blockbind_f(datal,15,VSIP_MEM_NONE); vsip_block_f *blockr = vsip_blockbind_f(datar,20,VSIP_MEM_NONE); vsip_block_f *block_ans = vsip_blockbind_f(ans_data,12,VSIP_MEM_NONE); vsip_block_f *block = vsip_blockcreate_f(200,VSIP_MEM_NONE); vsip_mview_f *ml = vsip_mbind_f(blockl,0,5,3,1,5); vsip_mview_f *mr = vsip_mbind_f(blockr,0,4,5,1,4); vsip_mview_f *ans = vsip_mbind_f(block_ans,0,4,3,1,4); vsip_mview_f *a = vsip_mbind_f(block,20,-1,3,-3,5); vsip_mview_f *a_cm = vsip_mcreate_f(3,5,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *a_rm = vsip_mcreate_f(3,5,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *b_cm = vsip_mcreate_f(5,4,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *b_rm = vsip_mcreate_f(5,4,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *c_cm = vsip_mcreate_f(3,4,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *c_rm = vsip_mcreate_f(3,4,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *b = vsip_mbind_f(block,100,-2,5,-10,4); vsip_mview_f *c = vsip_mbind_f(block,150,-8,3,-2,4); vsip_mview_f *chk = vsip_mcreate_f(3,4,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *aa = vsip_mcreate_f(3,5,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *bb = vsip_mcreate_f(5,4,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *cc = vsip_mcreate_f(3,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *c_cc = vsip_cmcreate_f(3,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *c_bb = vsip_cmcreate_f(5,4,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *i_cc = vsip_mimagview_f(c_cc); vsip_mview_f *r_bb = vsip_mrealview_f(c_bb); vsip_blockadmit_f(blockl,VSIP_TRUE); vsip_blockadmit_f(blockr,VSIP_TRUE); vsip_blockadmit_f(block_ans,VSIP_TRUE); vsip_mcopy_f_f(ml,a); vsip_mcopy_f_f(ml,a_cm); vsip_mcopy_f_f(ml,a_rm); vsip_mcopy_f_f(mr,b); vsip_mcopy_f_f(mr,b_cm); vsip_mcopy_f_f(mr,b_rm); vsip_mcopy_f_f(mr,r_bb); vsip_mcopy_f_f(a,aa); vsip_mcopy_f_f(b,bb); vsip_mprod_f(a,b,c); printf("vsip_mprod_f(a,b,c)\n"); printf("a\n"); VU_mprintm_f("6.4",a); printf("b\n"); VU_mprintm_f("6.4",b); printf("c\n"); VU_mprintm_f("6.4",c); printf("right answer\n"); VU_mprintm_f("6.4",ans); vsip_msub_f(c,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_mprod_f(aa,bb,cc); printf("vsip_mprod_f(aa,bb,cc)\n"); printf("aa\n"); VU_mprintm_f("6.4",aa); printf("bb\n"); VU_mprintm_f("6.4",bb); printf("cc\n"); VU_mprintm_f("6.4",cc); printf("right answer\n"); VU_mprintm_f("6.4",ans); vsip_msub_f(cc,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_mprod_f(aa,r_bb,i_cc); printf("vsip_mprod_f(aa,bb,cc)\n"); printf("aa\n"); VU_mprintm_f("6.4",aa); printf("bb\n"); VU_mprintm_f("6.4",r_bb); printf("cc\n"); VU_mprintm_f("6.4",i_cc); printf("right answer\n"); VU_mprintm_f("6.4",ans); vsip_msub_f(i_cc,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check ccc\n"); vsip_mprod_f(a_cm,b_cm,c_cm); vsip_msub_f(c_cm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check ccr\n"); vsip_mprod_f(a_cm,b_cm,c_rm); vsip_msub_f(c_rm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check crc\n"); vsip_mprod_f(a_cm,b_rm,c_cm); vsip_msub_f(c_cm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check crr\n"); vsip_mprod_f(a_cm,b_rm,c_rm); vsip_msub_f(c_rm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check rcc\n"); vsip_mprod_f(a_rm,b_cm,c_cm); vsip_msub_f(c_cm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check rcr\n"); vsip_mprod_f(a_rm,b_cm,c_rm); vsip_msub_f(c_rm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check rrc\n"); vsip_mprod_f(a_rm,b_rm,c_cm); vsip_msub_f(c_cm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check rrr\n"); vsip_mprod_f(a_rm,b_rm,c_rm); vsip_msub_f(c_rm,ans,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_f(ml); vsip_malldestroy_f(mr); vsip_mdestroy_f(a); vsip_malldestroy_f(aa); vsip_mdestroy_f(b); vsip_malldestroy_f(bb); vsip_malldestroy_f(c); vsip_malldestroy_f(cc); vsip_malldestroy_f(ans); vsip_malldestroy_f(chk); vsip_mdestroy_f(i_cc); vsip_mdestroy_f(r_bb); vsip_cmalldestroy_f(c_cc); vsip_cmalldestroy_f(c_bb); vsip_malldestroy_f(a_cm); vsip_malldestroy_f(a_rm); vsip_malldestroy_f(b_cm); vsip_malldestroy_f(b_rm); vsip_malldestroy_f(c_cm); vsip_malldestroy_f(c_rm); } return; } <file_sep>from vsip import * #Spline, Sort, Permute; Interpolate #spline is a class in pyJvsip.py # pyJvsip Functions def linear(x0,y0,*args): major={'ROW':VSIP_ROW,'COL':VSIP_COL,0:VSIP_ROW,1:VSIP_COL} f={'vview_fvview_f':vsip_vinterp_linear_f, 'vview_dvview_d':vsip_vinterp_linear_d, 'vview_fmview_f':vsip_minterp_linear_f, 'vview_dmview_d':vsip_minterp_linear_d} n=len(args) assert n >= 2 and n <=3,'Argument list error for linear.' x=args[n-2];y=args[n-1] assert 'pyJvsip' in repr(x0) and 'pyJvsip' in repr(y0) and \ 'pyJvsip' in repr(x) and 'pyJvsip' in repr(y), 'First two and last two arguments must be pyJvsip views.' t=x0.type+y0.type assert t in f,'View types not recognized for linear interpolations' if n == 3: dim = arg[0] else: dim = x0.major if 'mview' in y0.type: assert dim in major,'Dimension flag not recognized for linear interpolation.' if major[dim]==0: assert x0.length == y0.collength,'Input data views not compliant.' assert x.length == y.collength,'Output data views not compliant.' else: assert x0.length == y0.rowlength,'Input data views not compliant.' assert x.length == y.rowlength,'Output data views not compliant.' f[t](x0.vsip,y0.vsip,major[dim],x.vsip,y.vsip) else: assert x0.length == y0.length,'Input data views not compliant.' assert y.length == x.length, 'Output data views not compliant.' f[t](x0.vsip,y0.vsip,x.vsip,y.vsip) return y def nearest(x0,y0,*args): f={'vview_fvview_f':vsip_vinterp_nearest_f, 'vview_dvview_d':vsip_vinterp_nearest_d, 'vview_fmview_f':vsip_minterp_nearest_f, 'vview_dmview_d':vsip_minterp_nearest_d} major={'ROW':VSIP_ROW,'COL':VSIP_COL,0:VSIP_ROW,1:VSIP_COL} n=len(args) assert n >= 2 and n <=3,'Argument list error for linear.' x=args[n-2];y=args[n-1] assert 'pyJvsip' in repr(x0) and 'pyJvsip' in repr(y0) and \ 'pyJvsip' in repr(x) and 'pyJvsip' in repr(y), 'First two and last two arguments must be pyJvsip views.' t=x0.type+y0.type assert t in f,'View types not recognized for nearest interpolations' if n == 3: dim = arg[0] else: dim = x0.major if 'mview' in y0.type: assert dim in major,'Dimension flag not recognized for nearest interpolation.' if major[dim]==0: assert x0.length == y0.collength,'Input data views not compliant.' assert x.length == y.collength,'Output data views not compliant.' else: assert x0.length == y0.rowlength,'Input data views not compliant.' assert x.length == y.rowlength,'Output data views not compliant.' f[t](x0.vsip,y0.vsip,major[dim],x.vsip,y.vsip) else: assert x0.length == y0.length,'Input data views not compliant.' assert y.length == x.length, 'Output data views not compliant.' f[t](x0.vsip,y0.vsip,x.vsip,y.vsip) return y def permute_once(inpt,m,indx,outpt): major={'ROW':VSIP_ROW,'COL':VSIP_COL,0:VSIP_ROW,1:VSIP_COL} f={'cmview_d':vsip_cmpermute_once_d,\ 'cmview_f':vsip_cmpermute_once_f,\ 'mview_d':vsip_mpermute_once_d,\ 'mview_f':vsip_mpermute_once_f} assert m in major,"Major argument should be one of 'ROW' or VSIP_ROW; 'COL' or VSIP_COL" assert 'vview_vi' == indx.type,'Index vector must be of type vview_vi' assert inpt.type==outpt.type,'Input and output matrix must be the same shape' assert inpt.size==outpt.size,'Input and output matrix must be the same size' assert inpt.type in f,'Input view not supported for permute once' if major[m] == VSIP_ROW: assert indx.length==inpt.collength,'error in index size' else: assert indx.length==inpt.rowlength,'error in index size' f[inpt.type](inpt.vsip,major[m],indx.vsip,outpt.vsip) return outpt <file_sep>/* Created RJudd */ /* */ #include"VU_vprintm_d.include" static void interpolate_spline_d(void) { printf("*********\nTEST spline for double\n"); { vsip_length N0 = 11; vsip_spline_d *spl = vsip_spline_create_d(N0); vsip_length N = 50; vsip_index index; vsip_vview_d *yf = vsip_vcreate_d(N,VSIP_MEM_NONE); vsip_vview_d *xf = vsip_vcreate_d(N,VSIP_MEM_NONE); vsip_vview_d *xp = vsip_vcreate_d(N0,VSIP_MEM_NONE); vsip_vview_d *yp = vsip_vcreate_d(N0,VSIP_MEM_NONE); vsip_vview_d *yf_ans=vsip_vcreate_d(N,VSIP_MEM_NONE); vsip_vramp_d(0.0,1.0,xp); vsip_vramp_d(0.0,0.204,xf); vsip_svmul_d(2.0/5.0 * M_PI,xp,yp); vsip_svmul_d(2.0/5.0 * M_PI,xf,yf_ans); vsip_vsin_d(yp,yp); vsip_vsin_d(yf_ans,yf_ans); printf("xp = \n");VU_vprintm_d("5.4",xp); printf("yp = \n");VU_vprintm_d("5.4",yp); printf("xf = \n");VU_vprintm_d("5.4",xf); vsip_vinterp_spline_d(xp,yp,spl,xf,yf); printf("spline = \n");VU_vprintm_d("5.4",yf); printf("ans = \n");VU_vprintm_d("5.4",yf_ans); vsip_vsub_d(yf_ans,yf,yf_ans); vsip_vmag_d(yf_ans,yf_ans); if(vsip_vmaxval_d(yf_ans,&index) < .01) printf("correct\n"); else printf("error\n"); vsip_spline_destroy_d(spl); vsip_valldestroy_d(xf); vsip_valldestroy_d(xp); vsip_valldestroy_d(yp); vsip_valldestroy_d(yf); vsip_valldestroy_d(yf_ans); } } <file_sep>/* Created <NAME> March 12, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mprodt_f.c,v 2.1 2003/03/08 14:43:34 judd Exp $ */ /* modified to vsip_mprodt_f.c */ /* April 21, 1998 1,2 to row,col */ /* Removed Development Mode RJudd Sept 00 */ #include"vsip.h" #include"vsip_mviewattributes_f.h" #include"vsip_vviewattributes_f.h" #include"VI_mrowview_f.h" void (vsip_mprodt_f)( const vsip_mview_f* A, const vsip_mview_f* B, const vsip_mview_f* R) { { vsip_length M = A->col_length, N = B->col_length; vsip_length i,j; vsip_vview_f bb,aa,rr; for(i = 0; i < M; i++){ vsip_vview_f *a = VI_mrowview_f(A, i,&aa), *r = VI_mrowview_f(R, i,&rr); vsip_scalar_f *r_p = r->block->array + r->offset * r->block->rstride; for(j =0; j < N; j++){ vsip_vview_f *b = VI_mrowview_f(B,j,&bb); *r_p = vsip_vdot_f(a,b); r_p += r->stride; } } } } <file_sep>#include<vsip.h> vsip_index *vindexptr(void) { vsip_index *idx=(vsip_index*) malloc(sizeof(vsip_scalar_mi)); return idx; } void vindexfree(vsip_index *idx) { if(idx) free(idx); } vsip_index vindexptrToInt(vsip_index *idx){ return *idx; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: clud_d.h,v 2.0 2003/02/22 15:23:14 judd Exp $ */ #include"VU_cmprintm_d.include" static void clud_d(void){ printf("********\nTEST clud_d\n"); { vsip_index i,j; /* make up some data space and views */ vsip_cblock_d *block = vsip_cblockcreate_d(600,VSIP_MEM_NONE); vsip_cmview_d *AC = vsip_cmbind_d(block,0,7,7,1,7); vsip_cmview_d *AG = vsip_cmbind_d(block,175,-2,7,-18,7); vsip_cmview_d *IC = vsip_cmbind_d(block,176,1,7,7,7); vsip_cmview_d *IG = vsip_cmbind_d(block,226,2,7,15,7); vsip_cmview_d *B = vsip_cmbind_d(block,335,7,7,1,7); vsip_cmview_d *A = vsip_cmbind_d(block,385,7,7,1,7); vsip_cmview_d *X = vsip_cmbind_d(block,434,5,7,1,3); vsip_cmview_d *Y = vsip_cmbind_d(block,475,3,7,1,3); vsip_clu_d* ludC = vsip_clud_create_d(7); vsip_clu_d* ludG = vsip_clud_create_d(7); vsip_scalar_d chk; vsip_scalar_d data_r[7][7] = { \ {0.5, 7.0, 10.0, 12.0, -3.0, 0.0, 0.05}, \ {2.0, 13.0, 18.0, 6.0, 0.0, 130.0, 8.0}, \ {3.0, -9.0, 2.0, 3.0, 2.0, -9.0, 6.0}, \ {4.0, 2.0, 2.0, 4.0, 1.0, 2.0, 3.0}, \ {0.2, 2.0, 9.0, 4.0, 1.0, 2.0, 3.0}, \ {0.1, 2.0, 0.3, 4.0, 1.0, 2.0, 3.0}, \ {0.0, 0.2, 3.0, 4.0, 1.0, 2.0, 3.0}}; vsip_scalar_d data_i[7][7] = { {0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1}, \ {0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1}, \ {0.1, 0.1, 0.1, 0.2, 0.2,-0.2, 0.2}, \ {0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2}, \ {0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3}, \ {0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4}, \ {0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4}}; vsip_scalar_d ydata_r[7][3] = { \ {77.85, 155.70, 311.40}, \ {942.00, 1884.00, 3768.00}, \ {1.00, 2.00, 4.00}, \ {68.00, 136.00, 272.00}, \ {85.20, 170.40, 340.80}, \ {59.00, 118.00, 236.00}, \ {5.00, 18.00, 6.00}}; vsip_scalar_d ydata_i[7][3] = { \ {4.5, 1.70, -3.40}, \ {3.7, 184.00, -2.00}, \ {1.00, 3.00, 2.00}, \ {68.00, 16.00, 272.00}, \ {85.20, 1170.40, 340.80}, \ {59.00, 18.50, 62.00}, \ {59.00, 11.60, 26.00}}; vsip_scalar_d Ident[7][7] = { \ {1, 0, 0, 0, 0, 0, 0}, \ {0, 1, 0, 0, 0, 0, 0}, \ {0, 0, 1, 0, 0, 0, 0}, \ {0, 0, 0, 1, 0, 0, 0}, \ {0, 0, 0, 0, 1, 0, 0}, \ {0, 0, 0, 0, 0, 1, 0}, \ {0, 0, 0, 0, 0, 0, 1}}; vsip_cmview_d *AH = vsip_cmcreate_d(7,7,VSIP_ROW,VSIP_MEM_NONE); for(i=0; i<7; i++){ for(j=0; j<7; j++){ vsip_cscalar_d a = vsip_cmplx_d(data_r[i][j],data_i[i][j]); vsip_cscalar_d e = vsip_cmplx_d(Ident[i][j],0); vsip_cmput_d(A, i,j,a); vsip_cmput_d(AC,i,j,a); vsip_cmput_d(AG,i,j,a); vsip_cmput_d(IC,i,j,e); vsip_cmput_d(IG,i,j,e); } } for(i=0; i<7; i++){ for(j=0; j<3; j++){ vsip_cscalar_d a = vsip_cmplx_d(ydata_r[i][j],ydata_i[i][j]); vsip_cmput_d(X,i,j,a); } } vsip_cmherm_d(A,AH); printf("Matrix A = \n");VU_cmprintm_d("7.2",A);fflush(stdout); vsip_clud_d(ludC,AC); vsip_clud_d(ludG,AG); printf("vsip_clusol(lud,VSIP_MAT_NTRANS,X)\n"); printf("Solve A X = I \n"); fflush(stdout); vsip_clusol_d(ludC,VSIP_MAT_NTRANS,IC); vsip_clusol_d(ludG,VSIP_MAT_NTRANS,IG); printf("for compact case X = \n");VU_cmprintm_d("8.4",IC); fflush(stdout); printf("for general case X = \n");VU_cmprintm_d("8.4",IG); fflush(stdout); chk = 0; for(i=0; i<7; i++) for(j=0; j<7; j++) chk += vsip_cmag_d(vsip_csub_d(vsip_cmget_d(IC,i,j) , vsip_cmget_d(IG,i,j))); (chk > .01) ? printf("error\n") : printf("agree\n"); fflush(stdout); vsip_cmprod_d(A,IC,B); chk = 0; for(i=0; i<7; i++) for(j=0; j<7; j++) chk += vsip_cmag_d( vsip_csub_d(vsip_cmget_d(B,i,j),vsip_cmplx_d(Ident[i][j],0))); vsip_cmprod_d(A,IG,B); for(i=0; i<7; i++) for(j=0; j<7; j++) chk += vsip_cmag_d( vsip_csub_d(vsip_cmget_d(B,i,j),vsip_cmplx_d(Ident[i][j],0))); printf("mprod(A,X) = \n"); VU_cmprintm_d("8.3",B); fflush(stdout); (chk > .01) ? printf("error\n") : printf("correct\n"); fflush(stdout); /************************************************/ /* check case VSIP_MAT_HERM */ printf("Matrix Hermitian A = \n");VU_cmprintm_d("7.2",AH);fflush(stdout); for(i=0; i<7; i++){ for(j=0; j<7; j++){ vsip_cmput_d(IC,i,j,vsip_cmplx_d(Ident[i][j],0)); vsip_cmput_d(IG,i,j,vsip_cmplx_d(Ident[i][j],0)); } } printf("vsip_clusol(lud,VSIP_MAT_HERM,X)\n"); printf("Solve herm(A) X = I \n"); fflush(stdout); vsip_clusol_d(ludC,VSIP_MAT_HERM,IC); vsip_clusol_d(ludG,VSIP_MAT_HERM,IG); printf("for compact case X = \n");VU_cmprintm_d("8.4",IC); fflush(stdout); printf("for general case X = \n");VU_cmprintm_d("8.4",IG); fflush(stdout); chk = 0; for(i=0; i<7; i++) for(j=0; j<7; j++) chk += vsip_cmag_d(vsip_csub_d(vsip_cmget_d(IC,i,j) , vsip_cmget_d(IG,i,j))); (chk > .01) ? printf("error\n") : printf("agree\n"); fflush(stdout); vsip_cmprod_d(AH,IC,B); chk = 0; for(i=0; i<7; i++) for(j=0; j<7; j++) chk += vsip_cmag_d( vsip_csub_d(vsip_cmget_d(B,i,j),vsip_cmplx_d(Ident[i][j],0))); vsip_cmprod_d(AH,IG,B); for(i=0; i<7; i++) for(j=0; j<7; j++) chk += vsip_cmag_d( vsip_csub_d(vsip_cmget_d(B,i,j),vsip_cmplx_d(Ident[i][j],0))); printf("mprod(herm(A),X) = \n"); VU_cmprintm_d("8.3",B); fflush(stdout); (chk > .01) ? printf("error\n") : printf("correct\n"); fflush(stdout); /************************************************/ /* check case A X = B for VSIP_MAT_NTRANS */ printf("check A X = Y; VSIP_MAT_NTRANS\n"); printf("Y = \n");VU_cmprintm_d("8.4",X); vsip_clusol_d(ludC,VSIP_MAT_NTRANS,X); printf("X = \n"); VU_cmprintm_d("8.4",X); vsip_cmprod_d(A,X,Y); printf(" Y = A X\n");VU_cmprintm_d("8.4",Y); chk = 0; for(i=0; i<7; i++) for(j=0; j<3; j++) chk += vsip_cmag_d( vsip_csub_d(vsip_cmget_d(Y,i,j), vsip_cmplx_d(ydata_r[i][j],ydata_i[i][j]))); (chk > .01) ? printf("error\n") : printf("agree\n"); fflush(stdout); /************************************************/ /* check case herm(A) X = B for VSIP_MAT_HERM */ for(i=0; i<7; i++) for(j=0; j<3; j++) vsip_cmput_d(X,i,j,vsip_cmplx_d(ydata_r[i][j],ydata_i[i][j])); printf("Y = \n");VU_cmprintm_d("8.4",X); vsip_clusol_d(ludG,VSIP_MAT_HERM,X); vsip_cmprod_d(AH,X,Y); printf("X = \n");VU_cmprintm_d("8.4",X); printf("Y = herm(A) X\n");VU_cmprintm_d("8.4",Y); chk = 0; for(i=0; i<7; i++) for(j=0; j<3; j++) chk += vsip_cmag_d( vsip_csub_d(vsip_cmget_d(Y,i,j), vsip_cmplx_d(ydata_r[i][j],ydata_i[i][j]))); (chk > .01) ? printf("error\n") : printf("agree\n"); fflush(stdout); /***************************************************/ /* destroy stuff */ vsip_cmdestroy_d(AC); vsip_cmdestroy_d(AG); vsip_cmdestroy_d(IC); vsip_cmdestroy_d(IG); vsip_cmdestroy_d(B); vsip_cmdestroy_d(A); vsip_cmdestroy_d(X); vsip_cmalldestroy_d(Y); vsip_cmalldestroy_d(AH); vsip_clud_destroy_d(ludC); vsip_clud_destroy_d(ludG); } return; } <file_sep>from numpy import complex128, complex64, float64, float32, empty from pyJvsip import getType, create from jvsipNumpyUtils import * def jvToNp(v): """ Usage: from jvsipNumpy import jvCopyToNp # get a vsip view 'V' of type (c)vview_f, (c)vview_d, (c)mview_f, (c)mview_d ar=jvCopyToNp(V) This should produce a new numpy array ar of the proper type with a copy of the data in V. """ def myarray(v): if ('cmview_d' in v.type) or ('cvview_d' in v.type): p = complex128 elif ('cmview_f' in v.type) or ('cvview_f' in v.type): p = complex64 elif ('mview_d' in v.type) or ('vview_d' in v.type): p = float64 else: p = float32 aryt='C' mjr=0 if('mview' in v.type): if 'COL' in v.major: aryt='F' mjr=1 ary=empty([v.collength,v.rowlength],p,aryt) else: ary=empty(v.length,p) return (ary,mjr) assert 'pyJvsip' in getType(v)[0], "Input does not appear to be a pyJvsip type." assert ('view_d' in v.type) or ('view_f' in v.type), \ "Type %s not supported by jvToNp"%v.type f= {'vview_f':vcopyToNParray_f,'vview_d':vcopyToNParray_d, 'cvview_f':cvcopyToNParray_f,'cvview_d':cvcopyToNParray_d, 'mview_f':mcopyToNParray_f,'mview_d':mcopyToNParray_d, 'cmview_f':cmcopyToNParray_f,'cmview_d':cmcopyToNParray_d} ary,mjr = myarray(v) if 'vview' in v.type: f[v.type](v.view,ary) else: f[v.type](v.view,mjr,ary) return ary def npToJv(a): """ Usage: from jvsipNumpy import npCopyToJv # get a numpy array 'ar' of type float32, float64, complex64, complex128 V=npCopyToJv(ar) This should produce a new pyJvsip vector or matrix 'V' with a copy of the data in ar. """ def myView(a): fv={'float32':'vview_f','float64':'vview_d','complex64':'cvview_f','complex128':'cvview_d'} fm={'float32':'mview_f','float64':'mview_d','complex64':'cmview_f','complex128':'cmview_d'} ashp=a.shape t=a.dtype.name if len(a.shape) is 1: # create a vector v=create(fv[t],ashp[0]) else: #create a matrix if a.flags.f_contiguous: v=create(fm[t],ashp[0],ashp[1],'COL') else: v=create(fm[t],ashp[0],ashp[1]) return v sptd=['float32','float64','complex64','complex128'] assert a.dtype.name in sptd, a.dtype.name + ' not supported by npToJv.' assert 0 < len(a.shape) < 3, 'Only arrays of dimension 1 or 2 supported.' assert (a.flags.c_contiguous or a.flags.f_contiguous) and a.flags.aligned, \ 'Only contiguous aligned arrays supported' v=myView(a) f= {'vview_f':vcopyFromNParray_f,'vview_d':vcopyFromNParray_d, 'cvview_f':cvcopyFromNParray_f,'cvview_d':cvcopyFromNParray_d, 'mview_f':mcopyFromNParray_f,'mview_d':mcopyFromNParray_d, 'cmview_f':cmcopyFromNParray_f,'cmview_d':cmcopyFromNParray_d} if 'vview' in v.type: f[v.type](v.view,a) else: mjr=0 if a.flags.f_contiguous: mjr=1 f[v.type](v.view,mjr,a) return v <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vcopyfrom_user_f.h,v 1.1 2007/04/18 03:59:06 judd Exp $ */ #include"VU_vprintm_f.include" static void vcopyfrom_user_f(void){ printf("********\nTEST vcopyfrom_user_f\n"); { int i; vsip_block_f *block = vsip_blockcreate_f(200,VSIP_MEM_NONE); vsip_scalar_f input[5]={0,1,2,3,4}; vsip_vview_f *view = vsip_vbind_f(block,100,3,5); vsip_vview_f *all = vsip_vbind_f(block,0,1,200); vsip_scalar_f check = 0; vsip_vfill_f(-1,all); vsip_vcopyfrom_user_f(input,view); VU_vprintm_f("3.2",view); for(i=0; i<5; i++){ check += fabs(input[i] - vsip_vget_f(view,(vsip_index)i)); } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_vdestroy_f(all); vsip_vdestroy_f(view); vsip_blockdestroy_f(block); } return; } <file_sep>/* Created RJudd September 19, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mbind_li.c,v 2.0 2003/02/22 15:18:54 judd Exp $ */ #include"vsip.h" #include"vsip_mviewattributes_li.h" vsip_mview_li* (vsip_mbind_li)( const vsip_block_li* block, vsip_offset offset, vsip_stride col_stride, vsip_length col_length, vsip_stride row_stride, vsip_length row_length) { { vsip_mview_li* mview_li = (vsip_mview_li*)malloc(sizeof(vsip_mview_li)); if(mview_li != NULL){ mview_li->block = (vsip_block_li*)block; mview_li->offset = offset; mview_li->col_stride = col_stride; mview_li->row_stride = row_stride; mview_li->col_length = col_length; mview_li->row_length = row_length; mview_li->markings = VSIP_VALID_STRUCTURE_OBJECT; } return mview_li; } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mkron_d.h,v 2.0 2003/02/22 15:23:25 judd Exp $ */ #include"VU_mprintm_d.include" static void mkron_d(void){ printf("********\nTEST mkron_d\n"); { vsip_scalar_d alpha = 1.5; vsip_scalar_d data[] = { 1, 2, 3, 4}; vsip_scalar_d ans[] = { 1.5, 3, 3, 6, 4.5, 6, 9, 12, 4.5, 9, 6, 12, 13.5, 18, 18, 24} ; vsip_block_d *block_data = vsip_blockbind_d(data,4,VSIP_MEM_NONE); vsip_block_d *ans_block = vsip_blockbind_d(ans,16,VSIP_MEM_NONE); vsip_mview_d *a = vsip_mbind_d(block_data,0,2,2,1,2); vsip_mview_d *b = vsip_mcreate_d(2,2,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *c = vsip_mcreate_d(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *ansm = vsip_mbind_d(ans_block,0,4,4,1,4); vsip_mview_d *chk = vsip_mcreate_d(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_d(block_data,VSIP_TRUE); vsip_blockadmit_d(ans_block,VSIP_TRUE); vsip_mcopy_d_d(a,b); printf("vsip_mkron_d(alpha,a,b,c)\n"); vsip_mkron_d(alpha,a,b,c); printf("alpha = %f \n",alpha); printf("matrix a\n");VU_mprintm_d("8.6",a); printf("matrix b\n");VU_mprintm_d("8.6",b); printf("matrix c\n");VU_mprintm_d("8.6",c); printf("right answer\n");VU_mprintm_d("8.4",ansm); vsip_msub_d(c,ansm,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_d(a); vsip_malldestroy_d(b); vsip_malldestroy_d(c); vsip_malldestroy_d(chk); vsip_malldestroy_d(ansm); } return; } <file_sep>import pyJvsip as pjv from math import pi as pi view=pjv.create L = 20 # A length a = view('vview_d',L).ramp(0.0,2.0*pi/float(L-1)) b = a.empty ab_bl=view('vview_bl',L) pjv.cos(a,b) a.fill(0.0) pjv.lgt(b,a,ab_bl) assert ab_bl.anytrue, 'No true values in boolean vector' ab_vi = ab_bl.indexbool pjv.gather(b,ab_vi,a.putlength(ab_vi.length)) print(repr([(ab_vi[i], a[i]) for i in range(ab_vi.length)])) <file_sep>/* Created RJudd */ /* */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* */ /* $Id: mprod4_d.h,v 2.2 2006/04/27 01:40:55 judd Exp $ */ #include"VU_mprintm_d.include" static void mprod4_d(void){ printf("********\nTEST mprod4_d\n"); { vsip_scalar_d datal[] = {1.0, 2.0, 3.0, 4.0, 5.0, 5.0, 0.1, 0.2, 0.3, 0.4, 4.0, 3.0, 2.0, 0.0, -1.0, 1.0}; vsip_scalar_d datar[] = {0.1, 0.2, 0.3, 0.4, 1.0, 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 2.4, -1.1, -1.2, -1.3, -1.4, 2.1, 2.2, 2.3, 3.4, 2.0, 3.0, 4.0, 5.0, 2.1, 2.2, 0.3, 3.2, 2.1, 2.2, 1.0, 5.1}; vsip_scalar_d ans_data[] = {19.00, 20.00, 13.00, 28.20, 13.20, 16.50, 14.60, 33.90, 11.63, 12.66, 13.29, 14.98, 0.12, 0.24, 0.10, 1.02, 15.57, 16.34, 11.11, 24.28, 14.16, 18.45, 18.84, 35.13, 0.20, 0.40, -1.40, 0.60, 2.10, 1.40, -0.60, 2.70}; vsip_block_d *blockl = vsip_blockbind_d(datal,16,VSIP_MEM_NONE); vsip_block_d *blockr = vsip_blockbind_d(datar,32,VSIP_MEM_NONE); vsip_block_d *block_ans = vsip_blockbind_d(ans_data,32,VSIP_MEM_NONE); vsip_block_d *block = vsip_blockcreate_d(200,VSIP_MEM_NONE); vsip_mview_d *ml = vsip_mbind_d(blockl,0,4,4,1,4); vsip_mview_d *mr = vsip_mbind_d(blockr,0,8,4,1,8); vsip_mview_d *ans = vsip_mbind_d(block_ans,0,8,4,1,8); vsip_mview_d *a = vsip_mbind_d(block,20,-1,4,-4,4); vsip_mview_d *a_cm = vsip_mcreate_d(4,4,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *a_rm = vsip_mcreate_d(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *b_cm = vsip_mcreate_d(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *b_rm = vsip_mcreate_d(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *c_cm = vsip_mcreate_d(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *c_rm = vsip_mcreate_d(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *b = vsip_mbind_d(block,100,-1,4,-6,8); vsip_mview_d *c = vsip_mbind_d(block,150,-8,4,-1,8); vsip_mview_d *chk = vsip_mcreate_d(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *aa = vsip_mcreate_d(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *bb = vsip_mcreate_d(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *cc = vsip_mcreate_d(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *c_cc = vsip_cmcreate_d(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *c_bb = vsip_cmcreate_d(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *i_cc = vsip_mimagview_d(c_cc); vsip_mview_d *r_bb = vsip_mrealview_d(c_bb); vsip_blockadmit_d(blockl,VSIP_TRUE); vsip_blockadmit_d(blockr,VSIP_TRUE); vsip_blockadmit_d(block_ans,VSIP_TRUE); vsip_mcopy_d_d(ml,a); vsip_mcopy_d_d(ml,a_cm); vsip_mcopy_d_d(ml,a_rm); vsip_mcopy_d_d(mr,b); vsip_mcopy_d_d(mr,b_cm); vsip_mcopy_d_d(mr,b_rm); vsip_mcopy_d_d(mr,r_bb); vsip_mcopy_d_d(a,aa); vsip_mcopy_d_d(b,bb); vsip_mprod4_d(a,b,c); printf("vsip_mprod4_d(a,b,c)\n"); printf("a\n"); VU_mprintm_d("6.4",a); printf("b\n"); VU_mprintm_d("6.4",b); printf("c\n"); VU_mprintm_d("6.4",c); printf("right answer\n"); VU_mprintm_d("6.4",ans); vsip_msub_d(c,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_mprod4_d(aa,bb,cc); printf("vsip_mprod4_d(aa,bb,cc)\n"); printf("aa\n"); VU_mprintm_d("6.4",aa); printf("bb\n"); VU_mprintm_d("6.4",bb); printf("cc\n"); VU_mprintm_d("6.4",cc); printf("right answer\n"); VU_mprintm_d("6.4",ans); vsip_msub_d(cc,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_mprod4_d(aa,r_bb,i_cc); printf("vsip_mprod4_d(aa,bb,cc)\n"); printf("aa\n"); VU_mprintm_d("6.4",aa); printf("bb\n"); VU_mprintm_d("6.4",r_bb); printf("cc\n"); VU_mprintm_d("6.4",i_cc); printf("right answer\n"); VU_mprintm_d("6.4",ans); vsip_msub_d(i_cc,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check ccc\n"); vsip_mprod4_d(a_cm,b_cm,c_cm); vsip_msub_d(c_cm,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check ccr\n"); vsip_mprod4_d(a_cm,b_cm,c_rm); vsip_msub_d(c_rm,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check crc\n"); vsip_mprod4_d(a_cm,b_rm,c_cm); vsip_msub_d(c_cm,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check crr\n"); vsip_mprod4_d(a_cm,b_rm,c_rm); vsip_msub_d(c_rm,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check rcc\n"); vsip_mprod4_d(a_rm,b_cm,c_cm); vsip_msub_d(c_cm,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check rcr\n"); vsip_mprod4_d(a_rm,b_cm,c_rm); vsip_msub_d(c_rm,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check rrc\n"); vsip_mprod4_d(a_rm,b_rm,c_cm); vsip_msub_d(c_cm,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check rrr\n"); vsip_mprod4_d(a_rm,b_rm,c_rm); vsip_msub_d(c_rm,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_d(ml); vsip_malldestroy_d(mr); vsip_mdestroy_d(a); vsip_malldestroy_d(aa); vsip_mdestroy_d(b); vsip_malldestroy_d(bb); vsip_malldestroy_d(c); vsip_malldestroy_d(cc); vsip_malldestroy_d(ans); vsip_malldestroy_d(chk); vsip_mdestroy_d(i_cc); vsip_mdestroy_d(r_bb); vsip_cmalldestroy_d(c_cc); vsip_cmalldestroy_d(c_bb); vsip_malldestroy_d(a_cm); vsip_malldestroy_d(a_rm); vsip_malldestroy_d(b_cm); vsip_malldestroy_d(b_rm); vsip_malldestroy_d(c_cm); vsip_malldestroy_d(c_rm); } return; } <file_sep>/* Created RJudd September 15, 1999*/ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #ifndef _vsip_ludattributes_d_h #define _vsip_ludattributes_d_h 1 #include"vsip.h" #include"VI.h" #include"vsip_mviewattributes_d.h" #include"vsip_vviewattributes_d.h" #include"vsip_vviewattributes_vi.h" struct vsip_ludattributes_d{ vsip_mview_d* LU; vsip_mview_d LLU; vsip_index* P; vsip_length N; }; #endif /*_vsip_ludattributes_d_h */ <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vgather_mi.c,v 2.1 2008/03/04 06:13:12 judd Exp $ */ #include"vsip.h" #include"vsip_vviewattributes_mi.h" #include"vsip_vviewattributes_vi.h" void vsip_vgather_mi( const vsip_vview_mi* a, const vsip_vview_vi* x, const vsip_vview_mi* r) { vsip_length n = x->length; vsip_stride ast = 2 * a->stride, rst = 2 * r->stride, xst = x->stride; vsip_scalar_vi *apr = (a->block->array) + 2 * a->offset, *rpr = (r->block->array) + 2 * r->offset, *apc = apr + 1, *rpc = rpr + 1, *xp = (x->block->array) + x->offset; while(n-- >0){ *rpr = *(apr + *xp * ast); *rpc = *(apc + *xp * ast); rpr += rst; rpc += rst; xp += xst; } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D881 */ #ifndef _vsip_corr1dattributes_d #define _vsip_corr1dattributes_d 1 #include"VI.h" struct vsip_corr1dattributes_d{ vsip_cvview_d *h; vsip_cvview_d *x; vsip_fft_d *fft; vsip_length n; vsip_length m; vsip_length mn; vsip_length N; vsip_length lag_len; int ntimes; vsip_support_region support; vsip_alg_hint hint; }; #endif /* _vsip_corr1dattributes_d */ <file_sep>/* RJudd For Core January 10, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vcreate_kaiser_d.c,v 2.0 2003/02/22 15:19:12 judd Exp $ */ /* Removed Tisdale error checking Sept 00 */ #include"vsip.h" #include"vsip_vviewattributes_d.h" #include"VI_vcreate_d.h" #define a1 2.2499997 #define a2 1.2656208 #define a3 0.3163866 #define a4 0.0444479 #define a5 0.0039444 #define a6 0.0002100 #define b1 0.39894228 /* 1/sqrt(2pi) */ #define b2 0.02805063 #define b3 0.029219405 #define b4 0.0447422145 static vsip_scalar_d VI_Io_d(vsip_scalar_d x) { vsip_length n; vsip_scalar_d ans,x0,x1,n0,diff; diff = 1; x1 = x * x * .25; x0 = x1; ans = 1 + x1; n = 1; n0 = 1; while(diff > .00000001){ n++; n0 *= (vsip_scalar_d) n; x1 *= x0; diff = x1/(n0 * n0); ans += diff; } return (vsip_scalar_d) ans; } vsip_vview_d* vsip_vcreate_kaiser_d( vsip_length N, vsip_scalar_d beta, vsip_memory_hint h) { vsip_vview_d *a; a = VI_vcreate_d(N,h); if(a == NULL) return (vsip_vview_d*)NULL; { vsip_length n = 0; vsip_scalar_d *ap = (a->block->array) + a->offset, Ibeta, x = beta, c1 = 2.0 / (N -1 ); if((vsip_scalar_d)fabs(x) <= 3.0){ x /= 3.0; x *= x; Ibeta = 1 + x * (a1 + x * (a2 + x * (a3 + x * (a4 + x * (a5 + x * a6))))); } else { Ibeta = VI_Io_d(x); } /* Note this is always unit stride */ while(n < N){ vsip_scalar_d c3 = c1 * n - 1; if(c3 > 1.0) c3 = 1.0; x = beta * (vsip_scalar_d)sqrt(1 - (c3 * c3)); if((vsip_scalar_d)fabs(x) <= 3.0){ x /= 3.0; x *= x; *ap++ = (1 + x * (a1 + x * (a2 + x * (a3 + x * (a4 + x * (a5 + x * a6)))))) / Ibeta; } else { *ap++ = VI_Io_d(x)/ Ibeta; } n++; } } return a; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: clud_f.h,v 2.0 2003/02/22 15:23:14 judd Exp $ */ #include"VU_cmprintm_f.include" static void clud_f(void){ printf("********\nTEST clud_f\n"); { vsip_index i,j; /* make up some data space and views */ vsip_cblock_f *block = vsip_cblockcreate_f(600,VSIP_MEM_NONE); vsip_cmview_f *AC = vsip_cmbind_f(block,0,7,7,1,7); vsip_cmview_f *AG = vsip_cmbind_f(block,175,-2,7,-18,7); vsip_cmview_f *IC = vsip_cmbind_f(block,176,1,7,7,7); vsip_cmview_f *IG = vsip_cmbind_f(block,226,2,7,15,7); vsip_cmview_f *B = vsip_cmbind_f(block,335,7,7,1,7); vsip_cmview_f *A = vsip_cmbind_f(block,385,7,7,1,7); vsip_cmview_f *X = vsip_cmbind_f(block,434,5,7,1,3); vsip_cmview_f *Y = vsip_cmbind_f(block,475,3,7,1,3); vsip_clu_f* ludC = vsip_clud_create_f(7); vsip_clu_f* ludG = vsip_clud_create_f(7); vsip_scalar_f chk; vsip_scalar_f data_r[7][7] = { \ {0.5, 7.0, 10.0, 12.0, -3.0, 0.0, 0.05}, \ {2.0, 13.0, 18.0, 6.0, 0.0, 130.0, 8.0}, \ {3.0, -9.0, 2.0, 3.0, 2.0, -9.0, 6.0}, \ {4.0, 2.0, 2.0, 4.0, 1.0, 2.0, 3.0}, \ {0.2, 2.0, 9.0, 4.0, 1.0, 2.0, 3.0}, \ {0.1, 2.0, 0.3, 4.0, 1.0, 2.0, 3.0}, \ {0.0, 0.2, 3.0, 4.0, 1.0, 2.0, 3.0}}; vsip_scalar_f data_i[7][7] = { {0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1}, \ {0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1}, \ {0.1, 0.1, 0.1, 0.2, 0.2,-0.2, 0.2}, \ {0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2}, \ {0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3}, \ {0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4}, \ {0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4}}; vsip_scalar_f ydata_r[7][3] = { \ {77.85, 155.70, 311.40}, \ {942.00, 1884.00, 3768.00}, \ {1.00, 2.00, 4.00}, \ {68.00, 136.00, 272.00}, \ {85.20, 170.40, 340.80}, \ {59.00, 118.00, 236.00}, \ {5.00, 18.00, 6.00}}; vsip_scalar_f ydata_i[7][3] = { \ {4.5, 1.70, -3.40}, \ {3.7, 184.00, -2.00}, \ {1.00, 3.00, 2.00}, \ {68.00, 16.00, 272.00}, \ {85.20, 1170.40, 340.80}, \ {59.00, 18.50, 62.00}, \ {59.00, 11.60, 26.00}}; vsip_scalar_f Ident[7][7] = { \ {1, 0, 0, 0, 0, 0, 0}, \ {0, 1, 0, 0, 0, 0, 0}, \ {0, 0, 1, 0, 0, 0, 0}, \ {0, 0, 0, 1, 0, 0, 0}, \ {0, 0, 0, 0, 1, 0, 0}, \ {0, 0, 0, 0, 0, 1, 0}, \ {0, 0, 0, 0, 0, 0, 1}}; vsip_cmview_f *AH = vsip_cmcreate_f(7,7,VSIP_ROW,VSIP_MEM_NONE); for(i=0; i<7; i++){ for(j=0; j<7; j++){ vsip_cscalar_f a = vsip_cmplx_f(data_r[i][j],data_i[i][j]); vsip_cscalar_f e = vsip_cmplx_f(Ident[i][j],0); vsip_cmput_f(A, i,j,a); vsip_cmput_f(AC,i,j,a); vsip_cmput_f(AG,i,j,a); vsip_cmput_f(IC,i,j,e); vsip_cmput_f(IG,i,j,e); } } for(i=0; i<7; i++){ for(j=0; j<3; j++){ vsip_cscalar_f a = vsip_cmplx_f(ydata_r[i][j],ydata_i[i][j]); vsip_cmput_f(X,i,j,a); } } vsip_cmherm_f(A,AH); printf("Matrix A = \n");VU_cmprintm_f("7.2",A);fflush(stdout); vsip_clud_f(ludC,AC); vsip_clud_f(ludG,AG); printf("vsip_clusol(lud,VSIP_MAT_NTRANS,X)\n"); printf("Solve A X = I \n"); fflush(stdout); vsip_clusol_f(ludC,VSIP_MAT_NTRANS,IC); vsip_clusol_f(ludG,VSIP_MAT_NTRANS,IG); printf("for compact case X = \n");VU_cmprintm_f("8.4",IC); fflush(stdout); printf("for general case X = \n");VU_cmprintm_f("8.4",IG); fflush(stdout); chk = 0; for(i=0; i<7; i++) for(j=0; j<7; j++) chk += vsip_cmag_f(vsip_csub_f(vsip_cmget_f(IC,i,j) , vsip_cmget_f(IG,i,j))); (chk > .01) ? printf("error\n") : printf("agree\n"); fflush(stdout); vsip_cmprod_f(A,IC,B); chk = 0; for(i=0; i<7; i++) for(j=0; j<7; j++) chk += vsip_cmag_f( vsip_csub_f(vsip_cmget_f(B,i,j),vsip_cmplx_f(Ident[i][j],0))); vsip_cmprod_f(A,IG,B); for(i=0; i<7; i++) for(j=0; j<7; j++) chk += vsip_cmag_f( vsip_csub_f(vsip_cmget_f(B,i,j),vsip_cmplx_f(Ident[i][j],0))); printf("mprod(A,X) = \n"); VU_cmprintm_f("8.3",B); fflush(stdout); (chk > .01) ? printf("error\n") : printf("correct\n"); fflush(stdout); /************************************************/ /* check case VSIP_MAT_HERM */ printf("Matrix Hermitian A = \n");VU_cmprintm_f("7.2",AH);fflush(stdout); for(i=0; i<7; i++){ for(j=0; j<7; j++){ vsip_cmput_f(IC,i,j,vsip_cmplx_f(Ident[i][j],0)); vsip_cmput_f(IG,i,j,vsip_cmplx_f(Ident[i][j],0)); } } printf("vsip_clusol(lud,VSIP_MAT_HERM,X)\n"); printf("Solve herm(A) X = I \n"); fflush(stdout); vsip_clusol_f(ludC,VSIP_MAT_HERM,IC); vsip_clusol_f(ludG,VSIP_MAT_HERM,IG); printf("for compact case X = \n");VU_cmprintm_f("8.4",IC); fflush(stdout); printf("for general case X = \n");VU_cmprintm_f("8.4",IG); fflush(stdout); chk = 0; for(i=0; i<7; i++) for(j=0; j<7; j++) chk += vsip_cmag_f(vsip_csub_f(vsip_cmget_f(IC,i,j) , vsip_cmget_f(IG,i,j))); (chk > .01) ? printf("error\n") : printf("agree\n"); fflush(stdout); vsip_cmprod_f(AH,IC,B); chk = 0; for(i=0; i<7; i++) for(j=0; j<7; j++) chk += vsip_cmag_f( vsip_csub_f(vsip_cmget_f(B,i,j),vsip_cmplx_f(Ident[i][j],0))); vsip_cmprod_f(AH,IG,B); for(i=0; i<7; i++) for(j=0; j<7; j++) chk += vsip_cmag_f( vsip_csub_f(vsip_cmget_f(B,i,j),vsip_cmplx_f(Ident[i][j],0))); printf("mprod(herm(A),X) = \n"); VU_cmprintm_f("8.3",B); fflush(stdout); (chk > .01) ? printf("error\n") : printf("correct\n"); fflush(stdout); /************************************************/ /* check case A X = B for VSIP_MAT_NTRANS */ printf("check A X = Y; VSIP_MAT_NTRANS\n"); printf("Y = \n");VU_cmprintm_f("8.4",X); vsip_clusol_f(ludC,VSIP_MAT_NTRANS,X); printf("X = \n"); VU_cmprintm_f("8.4",X); vsip_cmprod_f(A,X,Y); printf(" Y = A X\n");VU_cmprintm_f("8.4",Y); chk = 0; for(i=0; i<7; i++) for(j=0; j<3; j++) chk += vsip_cmag_f( vsip_csub_f(vsip_cmget_f(Y,i,j), vsip_cmplx_f(ydata_r[i][j],ydata_i[i][j]))); (chk > .01) ? printf("error\n") : printf("agree\n"); fflush(stdout); /************************************************/ /* check case herm(A) X = B for VSIP_MAT_HERM */ for(i=0; i<7; i++) for(j=0; j<3; j++) vsip_cmput_f(X,i,j,vsip_cmplx_f(ydata_r[i][j],ydata_i[i][j])); printf("Y = \n");VU_cmprintm_f("8.4",X); vsip_clusol_f(ludG,VSIP_MAT_HERM,X); vsip_cmprod_f(AH,X,Y); printf("X = \n");VU_cmprintm_f("8.4",X); printf("Y = herm(A) X\n");VU_cmprintm_f("8.4",Y); chk = 0; for(i=0; i<7; i++) for(j=0; j<3; j++) chk += vsip_cmag_f( vsip_csub_f(vsip_cmget_f(Y,i,j), vsip_cmplx_f(ydata_r[i][j],ydata_i[i][j]))); (chk > .02) ? printf("error\n") : printf("agree\n"); fflush(stdout); /***************************************************/ /* destroy stuff */ vsip_cmdestroy_f(AC); vsip_cmdestroy_f(AG); vsip_cmdestroy_f(IC); vsip_cmdestroy_f(IG); vsip_cmdestroy_f(B); vsip_cmdestroy_f(A); vsip_cmdestroy_f(X); vsip_cmalldestroy_f(Y); vsip_cmalldestroy_f(AH); vsip_clud_destroy_f(ludC); vsip_clud_destroy_f(ludG); } return; } <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cvcopyto_user_f.h,v 1.1 2007/04/18 03:59:06 judd Exp $ */ #include"VU_cvprintm_f.include" static void cvcopyto_user_f(void){ int i; printf("********\nTEST cvcopyto_user_f\n"); { /* test interleaved */ vsip_cblock_f *block = vsip_cblockcreate_f(200,VSIP_MEM_NONE); vsip_scalar_f output[10]; vsip_scalar_f ans[10]={0,1,2,3,4,5,6,7,8,9}; vsip_scalar_f check = 0; vsip_cvview_f *view = vsip_cvbind_f(block,100,-2,5); vsip_cvview_f *all = vsip_cvbind_f(block,0,1,200); vsip_cvfill_f(vsip_cmplx_f(-1,-1),all); for(i=0; i<5; i++){ vsip_cscalar_f t = vsip_cmplx_f((vsip_scalar_f)i*2, (vsip_scalar_f)i*2+1); vsip_cvput_f(view,(vsip_index)i,t); } printf("interleaved\n"); VU_cvprintm_f("3.2",view); vsip_cvcopyto_user_f(view,output,(vsip_scalar_f*)NULL); for(i=0; i<10; i++){ printf("%f\n",(float)output[i]); check += fabs(output[i]-ans[i]); } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_cvdestroy_f(all); vsip_cvdestroy_f(view); vsip_cblockdestroy_f(block); } { /* test split */ vsip_cblock_f *block = vsip_cblockcreate_f(200,VSIP_MEM_NONE); vsip_scalar_f output_r[5]; vsip_scalar_f output_i[5]; vsip_scalar_f ans_r[5]={0,2,4,6,8}; vsip_scalar_f ans_i[5]={1,3,5,7,9}; vsip_scalar_f check = 0; vsip_cvview_f *view = vsip_cvbind_f(block,100,3,5); vsip_cvview_f *all = vsip_cvbind_f(block,0,1,200); vsip_cvfill_f(vsip_cmplx_f(-1,-1),all); for(i=0; i<5; i++){ vsip_cscalar_f t = vsip_cmplx_f((vsip_scalar_f)i*2, (vsip_scalar_f)i*2+1); vsip_cvput_f(view,(vsip_index)i,t); } printf("split\n"); VU_cvprintm_f("3.2",view); vsip_cvcopyto_user_f(view,output_r,output_i); for(i=0; i<5; i++){ printf("%f\n",(float)output_r[i]); check += fabs(output_r[i]-ans_r[i]); printf("%f\n",(float)output_i[i]); check += fabs(output_i[i]-ans_i[i]); } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_cvdestroy_f(all); vsip_cvdestroy_f(view); vsip_cblockdestroy_f(block); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: crmsub_f.h,v 2.0 2003/02/22 15:23:22 judd Exp $ */ #include"VU_mprintm_f.include" #include"VU_cmprintm_f.include" static void crmsub_f(void){ printf("\n******\nTEST crmsub_f\n"); { vsip_scalar_f data1[]= {1,.1, 2,.2, 3,.3, 4,-.1, 5,-.3, 6,-.4, 7,.8, 8,.9, 9,-1}; vsip_scalar_f data2_r[]= {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9}; vsip_scalar_f data2_i[]= {-1.1, 2.2, -3.3, 4.4, -5.5, 6.6, -7.7, 8.8, -9.9}; vsip_scalar_f ans_r[] = {-0.1, -2.4, -4.7, 1.8, -0.5, -2.8, 3.7, 1.4, -0.9}; vsip_scalar_f ans_i[] = {0.1, 0.2, 0.3, -0.1, -0.3, -0.4, 0.8, 0.9, -1.0}; vsip_cmview_f *m1 = vsip_cmbind_f( vsip_cblockbind_f(data1,NDPTR_f,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_cmview_f *c_m2 = vsip_cmbind_f( vsip_cblockbind_f(data2_r,data2_i,9,VSIP_MEM_NONE),0,1,3,3,3); vsip_mview_f *m2= vsip_mrealview_f(c_m2); vsip_cmview_f *ma = vsip_cmbind_f( vsip_cblockbind_f(ans_r,ans_i,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_cmview_f *m3 = vsip_cmcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *chk = vsip_cmcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *chk_r = vsip_mrealview_f(chk); vsip_cblockadmit_f(vsip_cmgetblock_f(m1),VSIP_TRUE); vsip_cblockadmit_f(vsip_cmgetblock_f(c_m2),VSIP_TRUE); vsip_cblockadmit_f(vsip_cmgetblock_f(ma),VSIP_TRUE); printf("call vsip_crmsub_f(a,b,c)\n"); printf("a =\n");VU_cmprintm_f("8.6",m1); printf("b =\n");VU_mprintm_f("8.6",m2); vsip_crmsub_f(m1,m2,m3); printf("c =\n");VU_cmprintm_f("8.6",m3); printf("\nright answer =\n"); VU_cmprintm_f("6.4",ma); vsip_cmsub_f(ma,m3,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,0,2 * .0001,0,1,chk_r); if(fabs(vsip_msumval_f(chk_r)) > .5) printf("error\n"); else printf("correct\n"); { vsip_mview_f *b = vsip_mrealview_f(m3); vsip_mcopy_f_f(m2,b); printf(" b,c inplace with <b> realview of <c>\n"); vsip_crmsub_f(m1,b,m3); vsip_cmsub_f(ma,m3,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,0,2 * .0001,0,1,chk_r); if(fabs(vsip_msumval_f(chk_r)) > .5) printf("error\n"); else printf("correct\n"); vsip_mdestroy_f(b); } vsip_cmcopy_f_f(m1,m3); printf(" a,c inplace\n"); vsip_crmsub_f(m3,m2,m3); vsip_cmsub_f(ma,m3,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,0,2 * .0001,0,1,chk_r); if(fabs(vsip_msumval_f(chk_r)) > .5) printf("error\n"); else printf("correct\n"); vsip_mdestroy_f(m2); vsip_cmalldestroy_f(m1); vsip_cmalldestroy_f(c_m2); vsip_cmalldestroy_f(m3); vsip_cmalldestroy_f(ma); vsip_mdestroy_f(chk_r); vsip_cmalldestroy_f(chk); } return; } <file_sep># -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <markdowncell> # ### QR Decomposition # <codecell> import pyJvsip as pv f='%.5f' # <markdowncell> # Solve using QR Class # <markdowncell> # Create some data A x = b # Note we create an x and calculate a b directly # <codecell> m=7;n=5 A=pv.create('mview_d',m,n).randn(5) x=pv.create('mview_d',n,1).randn(9) print('Matrix A');A.mprint(f) print('Known x vector');x.transview.mprint(f) b=A.prod(x) print('Calculated b=Ax vector');b.transview.mprint(f) # <markdowncell> # Note QR overwrites the input matrix; so to preserve our original matrix we use a copy. The QR object will keep a reference to the copy (which means python will not garbage collect it). The QR class has a dictionary item which allows the user to query for the proper type bassed on the associated matrix. # <codecell> print('Example of QR.qrSel: %s'%pv.QR.qrSel[A.type]) qrObj = pv.QR(pv.QR.qrSel[A.type],m,n,pv.VSIP_QRD_SAVEQ) _=qrObj.decompose(A.copy) print('Solve for x estimate using b. Done in place. Here we make a copy of b first. A subview is printed since b is longer than the xestimate') xb = b.copy qrObj.solve('LLS',xb).transview[:,:A.rowlength].mprint(f) # <markdowncell> # Below we use the create function to produce a qr object with (default) save full Q. We then extract Q using prodQ and the identity matrix. We then check to see if Q is orthonormal. # <codecell> B=pv.create('cmview_d',8,3).randn(10) qr=pv.create('cqr_d',8,3) Q=qr.decompose(B).prodQ('NTRANS','RSIDE',pv.create('cmview_d',8,8).identity) Q.mprint('%.2f') Q.prodh(Q).mprint('%.1f') # <markdowncell> # Below we do the above example except we use a convenience view method to create the QR object directly from the matrix view; and we use prodQ twice to do the matrix multiply first times the identity to get Q and then Q times it's hermitian. # <codecell> qr=pv.create('cmview_d',8,3).randn(10).qr Q=qr.prodQ('NTRANS','RSIDE',pv.create('cmview_d',8,8).identity) qr.prodQ('HERM','RSIDE',Q).mprint('%.2f') # <markdowncell> # We also have a convenience view method to get the Q and R matrices explicitly. # <codecell> B=pv.create('cmview_d',8,3).randn(10) print('input B');B.mprint('%.2f') Q,R=B.copy.qrd print('Q');Q.mprint('%.2f') print('R');R.mprint('%.2f'); print('Frobenius norm of difference of B-Q * R: %.5f '%(Q.prod(R)-B).normFro) # <codecell> <file_sep>/* Created RJudd March 14, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cvmprod_f.c,v 2.0 2003/02/22 15:18:51 judd Exp $ */ /* April 20, 1998 1,2 to row,col */ /* Remove Development Mode RJudd Sept 00 */ #include"vsip.h" #include"vsip_cvviewattributes_f.h" #include"vsip_cmviewattributes_f.h" void (vsip_cvmprod_f)( const vsip_cvview_f* a, const vsip_cmview_f* B, const vsip_cvview_f* r) { { vsip_length nx = 0, mx = 0; vsip_stride cast = a->block->cstride, crst = r->block->cstride, cBst = B->block->cstride; vsip_scalar_f *ap_r = (vsip_scalar_f*)(a->block->R->array + cast * a->offset), *ap_i = (vsip_scalar_f*)(a->block->I->array + cast * a->offset), *rp_r = (vsip_scalar_f*)(r->block->R->array + crst * r->offset), *rp_i = (vsip_scalar_f*)(r->block->I->array + crst * r->offset), *Byp_r = (vsip_scalar_f*)(B->block->R->array + cBst * B->offset), *Byp_i = (vsip_scalar_f*)(B->block->I->array + cBst * B->offset), *Bxpr = Byp_r, *Bxpi = Byp_i; vsip_stride sta = cast * a->stride, str = crst * r->stride, stB = cBst * B->col_stride; while(nx++ < B->row_length){ *rp_r = 0; *rp_i = 0; mx = 0; while(mx++ < B->col_length){ *rp_r += *ap_r * *Byp_r - *ap_i * *Byp_i; *rp_i += *ap_r * *Byp_i + *ap_i * *Byp_r; ap_r += sta; Byp_r += stB; ap_i += sta; Byp_i += stB; } ap_r = (vsip_scalar_f*)(a->block->R->array + cast * a->offset); ap_i = (vsip_scalar_f*)(a->block->I->array + cast * a->offset); Byp_r = (Bxpr += (cBst * B->row_stride)); Byp_i = (Bxpi += (cBst * B->row_stride)); rp_r += str; rp_i += str; } } } <file_sep>//: Blocks are a data storage abstraction. We support Float, Double (real and complex) and Int blocks. //: Complex blocks are structures made up of two real Blocks. This is a split storage format. //: Real blocks are classes to allow for deinit and ARC to free memory. import Foundation import Accelerate //: Data types; for this implementation everything is done dynamically public enum BlockTypes: String { case f, cf, d, cd, i, ui } //: a class to handle creation and deinit for Views of type Double fileprivate class DataDouble: NSObject { let dta: UnsafeRawPointer let length: Int let derived: Bool init(length: Int){ self.length = length self.derived = false let dta = UnsafeMutablePointer<Double>.allocate(capacity: length) dta.initialize(repeating: 0.0, count: length ) self.dta = UnsafeRawPointer(dta) } init(data: UnsafeRawPointer, length: Int){ self.length = length self.dta = data self.derived = true } deinit { if !self.derived { let dta = UnsafeMutablePointer<Double>(mutating: self.dta.assumingMemoryBound(to: Double.self)) dta.deallocate() } } } //: a class to handle creation and deinit for Views of type Float fileprivate class DataFloat: NSObject { let dta: UnsafeRawPointer let length: Int let derived: Bool init(length: Int){ self.length = length self.derived = false let dta = UnsafeMutablePointer<Float>.allocate(capacity: length) dta.initialize(repeating: 0.0, count: length ) self.dta = UnsafeRawPointer(dta) } init(data: UnsafeRawPointer, length: Int){ self.length = length self.dta = data self.derived = true } deinit { if !self.derived { let dta = UnsafeMutablePointer<Float>(mutating: self.dta.assumingMemoryBound(to: Float.self)) dta.deallocate() } } } //: Accelerate uses UInt32 for indexing, offsets and length fileprivate class DataUInt32: NSObject { let dta: UnsafeRawPointer let length: Int let derived: Bool init(length: Int){ self.length = length self.derived = false let dta = UnsafeMutablePointer<UInt32>.allocate(capacity: length) dta.initialize(repeating: 0, count: length ) self.dta = UnsafeRawPointer(dta) } init(data: UnsafeRawPointer, length: Int){ self.length = length self.dta = data self.derived = true } deinit { if !self.derived { let dta = UnsafeMutablePointer<UInt32>(mutating: self.dta.assumingMemoryBound(to: UInt32.self)) dta.deallocate() } } } //: Accelerate uses Int32 for strides fileprivate class DataInt32: NSObject { let dta: UnsafeRawPointer let length: Int let derived: Bool init(length: Int){ self.length = length self.derived = false let dta = UnsafeMutablePointer<Int32>.allocate(capacity: length) dta.initialize(repeating: 0, count: length ) self.dta = UnsafeRawPointer(dta) } init(data: UnsafeRawPointer, length: Int){ self.length = length self.dta = data self.derived = true } deinit { if !self.derived { let dta = UnsafeMutablePointer<Int32>(mutating: self.dta.assumingMemoryBound(to: Int32.self)) dta.deallocate() } } } //: complex views are structures. They don't allocate any memory from the heap directly fileprivate struct DataComplexDouble { let dtaReal: DataDouble let dtaImag: DataDouble init(length: Int){ self.dtaReal = DataDouble(length: length) self.dtaImag = DataDouble(length: length) } } fileprivate struct DataComplexFloat { let dtaReal: DataFloat let dtaImag: DataFloat init(length: Int){ self.dtaReal = DataFloat(length: length) self.dtaImag = DataFloat(length: length) } } //: Blocks are data raw data containers. The type is set at create. public struct Block { public let count: Int public var dta: UnsafeRawPointer? public var imagDta: UnsafeRawPointer? public let type: BlockTypes let derived: Bool let dtaObj: Any //need to retain data object so ARC does not collect it public init(length: Int, type: BlockTypes){ self.count = length self.derived = false switch type{ case .f: let dta = DataFloat(length: length) self.dtaObj = dta self.dta = dta.dta self.type = type case .cf: let dta = DataComplexFloat(length: length) self.dtaObj = dta self.dta = dta.dtaReal.dta self.imagDta = dta.dtaImag.dta self.type = type case .d: let dta = DataDouble(length: length) self.dtaObj = dta self.dta = dta.dta self.type = type case .cd: let dta = DataComplexDouble(length: length) self.dtaObj = dta self.dta = dta.dtaReal.dta self.imagDta = dta.dtaImag.dta self.type = type case .i: let dta = DataInt32(length: length) self.dtaObj = dta self.dta = dta.dta self.type = type case .ui: let dta = DataUInt32(length: length) self.dtaObj = dta self.dta = dta.dta self.type = type } } public subscript(index: Int) -> Scalar { get { switch self.type { case .f: let dta = UnsafeMutablePointer<Float>(mutating: self.dta?.assumingMemoryBound(to: Float.self)) return Scalar((dta! + index).pointee) case .d: let dta = UnsafeMutablePointer<Double>(mutating: self.dta?.assumingMemoryBound(to: Double.self)) return Scalar((dta! + index).pointee) case .cf: let dtaReal = UnsafeMutablePointer<Float>(mutating: self.dta?.assumingMemoryBound(to: Float.self)) let dtaImag = UnsafeMutablePointer<Float>(mutating: self.imagDta?.assumingMemoryBound(to: Float.self)) return Scalar(DSPComplex(real: (dtaReal! + index).pointee, imag: (dtaImag! + index).pointee)) case .cd: let dtaReal = UnsafeMutablePointer<Double>(mutating: self.dta?.assumingMemoryBound(to: Double.self)) let dtaImag = UnsafeMutablePointer<Double>(mutating: self.imagDta?.assumingMemoryBound(to: Double.self)) return Scalar(DSPDoubleComplex(real: (dtaReal! + index).pointee, imag: (dtaImag! + index).pointee)) case .i: let dta = UnsafeMutablePointer<Int32>(mutating: self.dta?.assumingMemoryBound(to: Int32.self)) return Scalar((dta! + index).pointee) case .ui: let dta = UnsafeMutablePointer<UInt32>(mutating: self.dta?.assumingMemoryBound(to: UInt32.self)) return Scalar((dta! + index).pointee) } } set(value) { switch self.type { case .f: let dta = UnsafeMutablePointer<Float>(mutating: self.dta?.assumingMemoryBound(to: Float.self)) (dta! + index).pointee = value.realf case .d: let dta = UnsafeMutablePointer<Double>(mutating: self.dta?.assumingMemoryBound(to: Double.self)) (dta! + index).pointee = value.reald case .cf: let dtaReal = UnsafeMutablePointer<Float>(mutating: self.dta?.assumingMemoryBound(to: Float.self)) let dtaImag = UnsafeMutablePointer<Float>(mutating: self.imagDta?.assumingMemoryBound(to: Float.self)) (dtaReal! + index).pointee = value.realf (dtaImag! + index).pointee = value.imagf case .cd: let dtaReal = UnsafeMutablePointer<Double>(mutating: self.dta?.assumingMemoryBound(to: Double.self)) let dtaImag = UnsafeMutablePointer<Double>(mutating: self.imagDta?.assumingMemoryBound(to: Double.self)) (dtaReal! + index).pointee = value.reald (dtaImag! + index).pointee = value.imagd case .i: let dta = UnsafeMutablePointer<Int32>(mutating: self.dta?.assumingMemoryBound(to: Int32.self)) (dta! + index).pointee = value.int case .ui: let dta = UnsafeMutablePointer<UInt32>(mutating: self.dta?.assumingMemoryBound(to: UInt32.self)) (dta! + index).pointee = UInt32(value.int) } } } } <file_sep>/* Created by RJudd September 9, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_ccfftop_f_def.h,v 2.0 2003/02/22 15:18:30 judd Exp $ */ #include"VI_fft_building_blocks_f.h" #include"VI_ccfftip_f.h" /*========================================================*/ void vsip_ccfftop_f(const vsip_fft_f *Offt, const vsip_cvview_f *x, const vsip_cvview_f *y) { vsip_fft_f Nfft = *Offt; vsip_fft_f *fft = &Nfft; vsip_cvcopy_f_f(x,y); fft->type = VSIP_CCFFTIP; VI_ccfftip_f(fft,y); } <file_sep>#!/bin/sh rm svd_test_f csvd_test_f svd_test_d csvd_test_d <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vcloneview_uc.h,v 2.0 2003/02/22 15:23:35 judd Exp $ */ static void vcloneview_uc(void){ printf("********\nTEST vcloneview_uc\n"); { vsip_scalar_uc data[10] = { 0, 1, 2, 3, 4, 5, 7, 8, 9}; vsip_offset o = 40; vsip_stride s = -3; vsip_length n = 10; vsip_block_uc *b = vsip_blockcreate_uc(100,VSIP_MEM_NONE); vsip_vview_uc *v = vsip_vbind_uc(b,o,s,n); vsip_vview_uc *sv = vsip_vcloneview_uc(v); vsip_scalar_uc chk = 0; int i; for(i=0; i< (int)n; i++) vsip_vput_uc(v,i,data[i]); for(i=0; i< (int)n; i++) chk += abs(vsip_vget_uc(sv,i) - data[i]); (chk != 0) ? printf("error \n") : printf("correct \n"); fflush(stdout); vsip_vdestroy_uc(sv); vsip_valldestroy_uc(v); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mprod_d.h,v 2.2 2007/04/18 17:05:54 judd Exp $ */ #include"VU_mprintm_d.include" static void mprod_d(void){ printf("********\nTEST mprod_d\n"); { vsip_scalar_d datal[] = {1, 2.0, 3.0, 4, 5.0, 5, .1, .2, .3, .4, 4, 3.0, 2.0, 0, -1.0}; vsip_scalar_d datar[] = { .1, .2, .3, .4, 1.0, 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 2.4, -1.1, -1.2, -1.3, -1.4, 2.1, 2.2, 2.3, 3.4}; vsip_scalar_d ans_data[] = { 14.5, 15.2, 15.9, 21.6, 1.53, 2.07, 2.61, 3.55, 5.5, 6.3, 7.1, 6.90}; vsip_block_d *blockl = vsip_blockbind_d(datal,15,VSIP_MEM_NONE); vsip_block_d *blockr = vsip_blockbind_d(datar,20,VSIP_MEM_NONE); vsip_block_d *block_ans = vsip_blockbind_d(ans_data,12,VSIP_MEM_NONE); vsip_block_d *block = vsip_blockcreate_d(170,VSIP_MEM_NONE); vsip_mview_d *ml = vsip_mbind_d(blockl,0,5,3,1,5); vsip_mview_d *mr = vsip_mbind_d(blockr,0,4,5,1,4); vsip_mview_d *ans = vsip_mbind_d(block_ans,0,4,3,1,4); vsip_mview_d *a = vsip_mbind_d(block,15,-1,3,-3,5); vsip_mview_d *b = vsip_mbind_d(block,60,-2,5,-10,4); vsip_mview_d *c = vsip_mbind_d(block,90,-8,3,-2,4); vsip_mview_d *chk = vsip_mcreate_d(3,4,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *aa = vsip_mcreate_d(3,5,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *bb = vsip_mcreate_d(5,4,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *cc = vsip_mcreate_d(3,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *c_cc = vsip_cmcreate_d(3,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *c_bb = vsip_cmcreate_d(5,4,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *i_cc = vsip_mimagview_d(c_cc); vsip_mview_d *r_bb = vsip_mrealview_d(c_bb); vsip_mview_d *a_cm = vsip_mcreate_d(3,5,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *a_rm = vsip_mcreate_d(3,5,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *b_cm = vsip_mcreate_d(5,4,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *b_rm = vsip_mcreate_d(5,4,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *c_cm = vsip_mcreate_d(3,4,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *c_rm = vsip_mcreate_d(3,4,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_d(blockl,VSIP_TRUE); vsip_blockadmit_d(blockr,VSIP_TRUE); vsip_blockadmit_d(block_ans,VSIP_TRUE); printf("ml\n"); VU_mprintm_d("6.4",ml); printf("mr\n"); VU_mprintm_d("6.4",mr); vsip_mcopy_d_d(ml,a); vsip_mcopy_d_d(mr,b); vsip_mcopy_d_d(mr,r_bb); vsip_mcopy_d_d(a,aa); vsip_mcopy_d_d(b,bb); vsip_mprod_d(a,b,c); printf("vsip_mprod_d(a,b,c)\n"); printf("a\n"); VU_mprintm_d("6.4",a); printf("b\n"); VU_mprintm_d("6.4",b); printf("c\n"); VU_mprintm_d("6.4",c); printf("right answer\n"); VU_mprintm_d("6.4",ans); vsip_msub_d(c,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_mprod_d(aa,bb,cc); printf("vsip_mprod_d(aa,bb,cc)\n"); printf("aa\n"); VU_mprintm_d("6.4",aa); printf("bb\n"); VU_mprintm_d("6.4",bb); printf("cc\n"); VU_mprintm_d("6.4",cc); printf("right answer\n"); VU_mprintm_d("6.4",ans); vsip_msub_d(cc,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_mprod_d(aa,r_bb,i_cc); printf("vsip_mprod_d(aa,bb,cc)\n"); printf("aa\n"); VU_mprintm_d("6.4",aa); printf("bb\n"); VU_mprintm_d("6.4",r_bb); printf("cc\n"); VU_mprintm_d("6.4",i_cc); printf("right answer\n"); VU_mprintm_d("6.4",ans); vsip_msub_d(i_cc,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_mcopy_d_d(ml,a_cm); vsip_mcopy_d_d(ml,a_rm); vsip_mcopy_d_d(mr,b_cm); vsip_mcopy_d_d(mr,b_rm); printf("check rrr\n"); vsip_mprod_d(a_rm,b_rm,c_rm); printf("a_rm\n"); VU_mprintm_d("6.4",a_rm); printf("b_rm\n"); VU_mprintm_d("6.4",b_rm); printf("c_rm\n"); VU_mprintm_d("6.4",c_rm); vsip_msub_d(c_rm,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_d(ml); vsip_malldestroy_d(mr); vsip_mdestroy_d(a); vsip_malldestroy_d(aa); vsip_mdestroy_d(b); vsip_malldestroy_d(bb); vsip_malldestroy_d(c); vsip_malldestroy_d(cc); vsip_malldestroy_d(ans); vsip_malldestroy_d(chk); vsip_malldestroy_d(a_cm); vsip_malldestroy_d(a_rm); vsip_malldestroy_d(b_cm); vsip_malldestroy_d(b_rm); vsip_malldestroy_d(c_cm); vsip_malldestroy_d(c_rm); vsip_mdestroy_d(i_cc); vsip_mdestroy_d(r_bb); vsip_cmalldestroy_d(c_cc); vsip_cmalldestroy_d(c_bb); } return; } <file_sep>//: Playground - noun: a place where people can play import Foundation import vsip import SJVsip let zero = Scalar(0.0) let aMatrix = Matrix(columnLength: 5, rowLength: 4, type: .d, major: VSIP_ROW) aMatrix.randn(8, portable: true) let fmt = "%4.3f" let chk = aMatrix.empty aMatrix.mPrint(fmt) let sv = aMatrix.sv sv.mPrint(fmt) let (U,s,V) = aMatrix.svdPart U.mPrint(fmt);s.mPrint(fmt); V.mPrint(fmt) chk.fill(zero) vmmul(vector: s, matrix: U, major: VSIP_ROW, resultsIn: U) prod(U, times: V.transview, resultsIn: chk) chk.mPrint(fmt) let svd = Svd(type: .d, columnLength: aMatrix.columnLength, rowLength: aMatrix.rowLength, saveU: VSIP_SVD_UVFULL, saveV: VSIP_SVD_UVFULL) svd.decompose(aMatrix.newCopy) if checkSvd(svd, against: aMatrix) { print("svd works") } else { print("svd failed") } <file_sep>import pyJvsip as pv N=6 A = pv.create('cvview_d',N).randn(7) B = A.empty.fill(5.0) C = A.empty.fill(0.0) print('A = '+A.mstring('%+.2f')) print('B = '+B.mstring('%+.2f')) pv.add(A,B,C) print('C = A+B') print('C = '+C.mstring('%+.2f')) """ OUTPUT A = [+0.16+0.50i -0.21-0.75i -0.56-0.09i \ +1.15+0.45i +0.10+0.43i +0.63-1.05i] B = [+5.00+0.00i +5.00+0.00i +5.00+0.00i \ +5.00+0.00i +5.00+0.00i +5.00+0.00i] C = A+B C = [+5.16+0.50i +4.79-0.75i +4.44-0.09i \ +6.15+0.45i +5.10+0.43i +5.63-1.05i] """ <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D881 */ #ifndef _vsip_randobject_h #define _vsip_randobject_h 1 #include"VI.h" struct vsip_randobject{ vsip_scalar_ue32 a; /* multiplier in LCG */ vsip_scalar_ue32 c; /* adder in LCG */ vsip_scalar_ue32 a1; vsip_scalar_ue32 c1; vsip_scalar_ue32 X; /* Last or initial X */ vsip_scalar_ue32 X1; vsip_scalar_ue32 X2; int type; }; #endif /* _vsip_randobject_h */ <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmprod_f.h,v 2.1 2006/04/09 19:28:53 judd Exp $ */ #include"VU_cmprintm_f.include" static void cmprod_f(void){ printf("********\nTEST cmprod_f\n"); { vsip_scalar_f datal_r[] = {1, 2.0, 3.0, 4, 5.0, 5, .1, .2, .3, .4, 4, 3.0, 2.0, 0, -1.0}; vsip_scalar_f datal_i[] = {9, 3.0, 2.0, 4.3, 3.2, 5, .1, 1.2, .3, 1.4, 3, 2.0, -2.1, 0.1, 1.0}; vsip_scalar_f datar_r[] = { .1, .2, .3, .4, 1.0, 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 2.4, -1.1, -1.2, -1.3, -1.4, 2.1, 2.2, 2.3, 3.4}; vsip_scalar_f datar_i[] = { 1.1, 5.2, 3.3, 1.4, 2.1, 1.0, 1.2, 1.2, 4.1, 3.0, 2.3, 2.3, 1.1, -1.2, -1.3, 1.0, 1.0, 2.2, -2.3, 3.4}; vsip_scalar_f ans_data_r[] = { -17.27, -41.34, -7.85, -13.04, -7.07, -10.83, -1.88, -8.35, 5.5, -7.08, 2.06, 1.63}; vsip_scalar_f ans_data_i[] = { 40.43, 35.62, 10.73, 51.06, 5.55, -0.39, 0.66, 8.03, 17.78, 27.86, 24.34, 12.42}; vsip_cblock_f *blockl = vsip_cblockbind_f(datal_r,datal_i,15,VSIP_MEM_NONE); vsip_cblock_f *blockr = vsip_cblockbind_f(datar_r,datar_i,20,VSIP_MEM_NONE); vsip_cblock_f *block_ans = vsip_cblockbind_f(ans_data_r,ans_data_i,12,VSIP_MEM_NONE); vsip_cblock_f *block = vsip_cblockcreate_f(70,VSIP_MEM_NONE); vsip_cmview_f *ml = vsip_cmbind_f(blockl,0,5,3,1,5); vsip_cmview_f *mr = vsip_cmbind_f(blockr,0,4,5,1,4); vsip_cmview_f *ans = vsip_cmbind_f(block_ans,0,4,3,1,4); vsip_cmview_f *a = vsip_cmbind_f(block,15,-1,3,-3,5); vsip_cmview_f *b = vsip_cmbind_f(block,50,-2,5,-10,4); vsip_cmview_f *c = vsip_cmbind_f(block,49,-8,3,-2,4); vsip_cmview_f *chk = vsip_cmcreate_f(3,4,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *chk_r = vsip_mrealview_f(chk); vsip_cblockadmit_f(blockl,VSIP_TRUE); vsip_cblockadmit_f(blockr,VSIP_TRUE); vsip_cblockadmit_f(block_ans,VSIP_TRUE); vsip_cmcopy_f_f(ml,a); vsip_cmcopy_f_f(mr,b); vsip_cmprod_f(a,b,c); printf("vsip_cmprod_f(a,b,c)\n"); printf("a\n"); VU_cmprintm_f("6.4",a); printf("b\n"); VU_cmprintm_f("6.4",b); printf("c\n"); VU_cmprintm_f("6.4",c); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); { /* ccc */ vsip_cmview_f *a1 = vsip_cmcreate_f(3,5,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(5,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(3,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* ccr */ vsip_cmview_f *a1 = vsip_cmcreate_f(3,5,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(5,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(3,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* crc */ vsip_cmview_f *a1 = vsip_cmcreate_f(3,5,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(5,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(3,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* crr */ vsip_cmview_f *a1 = vsip_cmcreate_f(3,5,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(5,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(3,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* rcc */ vsip_cmview_f *a1 = vsip_cmcreate_f(3,5,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(5,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(3,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* rcr */ vsip_cmview_f *a1 = vsip_cmcreate_f(3,5,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(5,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(3,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* rrc */ vsip_cmview_f *a1 = vsip_cmcreate_f(3,5,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(5,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(3,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* rrr */ vsip_cmview_f *a1 = vsip_cmcreate_f(3,5,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(5,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(3,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } vsip_cmalldestroy_f(ml); vsip_cmalldestroy_f(mr); vsip_cmdestroy_f(a); vsip_cmdestroy_f(b); vsip_cmalldestroy_f(c); vsip_cmalldestroy_f(ans); vsip_mdestroy_f(chk_r); vsip_cmalldestroy_f(chk); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mkron_f.h,v 2.0 2003/02/22 15:23:25 judd Exp $ */ #include"VU_mprintm_f.include" static void mkron_f(void){ printf("********\nTEST mkron_f\n"); { vsip_scalar_f alpha = 1.5; vsip_scalar_f data[] = { 1, 2, 3, 4}; vsip_scalar_f ans[] = { 1.5, 3, 3, 6, 4.5, 6, 9, 12, 4.5, 9, 6, 12, 13.5, 18, 18, 24} ; vsip_block_f *block_data = vsip_blockbind_f(data,4,VSIP_MEM_NONE); vsip_block_f *ans_block = vsip_blockbind_f(ans,16,VSIP_MEM_NONE); vsip_mview_f *a = vsip_mbind_f(block_data,0,2,2,1,2); vsip_mview_f *b = vsip_mcreate_f(2,2,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *c = vsip_mcreate_f(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *ansm = vsip_mbind_f(ans_block,0,4,4,1,4); vsip_mview_f *chk = vsip_mcreate_f(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_f(block_data,VSIP_TRUE); vsip_blockadmit_f(ans_block,VSIP_TRUE); vsip_mcopy_f_f(a,b); printf("vsip_mkron_f(alpha,a,b,c)\n"); vsip_mkron_f(alpha,a,b,c); printf("alpha = %f \n",alpha); printf("matrix a\n");VU_mprintm_f("8.6",a); printf("matrix b\n");VU_mprintm_f("8.6",b); printf("matrix c\n");VU_mprintm_f("8.6",c); printf("right answer\n");VU_mprintm_f("8.4",ansm); vsip_msub_f(c,ansm,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.0001,.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_f(a); vsip_malldestroy_f(b); vsip_malldestroy_f(c); vsip_malldestroy_f(chk); vsip_malldestroy_f(ansm); } return; } <file_sep>/* Created RJudd March 5, 2002 */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vfirst_i.c,v 2.1 2007/01/30 20:24:04 judd Exp $ */ #include"vsip.h" #include"vsip_vviewattributes_i.h" #include"vsip_vviewattributes_bl.h" vsip_index (vsip_vfirst_i)( vsip_index j, vsip_bool (*f)(vsip_scalar_i,vsip_scalar_i), const vsip_vview_i* a, const vsip_vview_i* b) { { /*define variables*/ /* register */ unsigned int n = (unsigned int) a->length; /* register */ int ast = (int) a->stride, bst = (int) b->stride; vsip_scalar_i *ap = (a->block->array) + a->offset, *bp = (b->block->array) + b->offset; /*end define*/ if(j >= n) return j; n -= j; ap += j * ast; bp += j * bst; while(n-- > 0){ if(f(*ap,*bp)) return (vsip_index)(a->length - n -1); ap += ast; bp += bst; } return (vsip_index)a->length; } } <file_sep>/* Created RJudd March 4, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cmscatter_f.c,v 2.0 2003/02/22 15:18:44 judd Exp $ */ #include"vsip.h" #include"vsip_cmviewattributes_f.h" #include"vsip_cvviewattributes_f.h" #include"vsip_vviewattributes_mi.h" #include"vsip_vviewattributes_vi.h" void (vsip_cmscatter_f)( const vsip_cvview_f *r, const vsip_cmview_f *a, const vsip_vview_mi *x) { { vsip_length n = x->length; vsip_stride ast_col = a->col_stride * a->block->cstride, ast_row = a->row_stride * a->block->cstride, rst = r->stride * r->block->cstride, xst = x->stride * 2; /* stride of matrix index row or col value */ vsip_scalar_f *ap_r = (a->block->R->array) + a->offset * a->block->cstride, *rp_r = (r->block->R->array) + r->offset * r->block->cstride; vsip_scalar_f *ap_i = (a->block->I->array) + a->offset * a->block->cstride, *rp_i = (r->block->I->array) + r->offset * r->block->cstride; vsip_scalar_vi *xp_row = (x->block->array) + x->offset; /* row value */ vsip_scalar_vi *xp_col = xp_row + 1; /* col value */ /*end define*/ while(n-- > 0){ *(ap_r + *xp_row * ast_col + *xp_col * ast_row) = *rp_r; *(ap_i + *xp_row * ast_col + *xp_col * ast_row) = *rp_i; rp_i += rst; rp_r += rst; xp_row += xst; xp_col += xst; } } return; } <file_sep>/* Created RJudd */ /* RETIRED */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: svd3_d.h,v 1.5 2008/09/21 17:17:49 judd Exp $ */ #include"VU_mprintm_d.include" #include"VU_vprintm_d.include" static void svd3_d(void){ printf("********\nTEST svd3 for double\n"); { vsip_index i; vsip_length M=10, N=3; vsip_scalar_d data[30] = {-1, 1, 0, 0, \ 0, -3, 1, 0, \ 0, 0, 0, 1, \ 0, 0, 0, 100,\ 0, 0, 0, 0, \ 0,0,0,0,0,0,0,0,0,0}; vsip_vview_d *s = vsip_vcreate_d(((M > N) ? N : M),VSIP_MEM_NONE); vsip_sv_d *svd = vsip_svd_create_d(M,N,VSIP_SVD_UVFULL,VSIP_SVD_UVFULL); vsip_block_d *block = vsip_blockbind_d(data,(M * N),VSIP_MEM_NONE); vsip_mview_d *A0 = vsip_mbind_d(block,0,N,M,1,N); vsip_block_d *vblk = vsip_blockcreate_d(300,VSIP_MEM_NONE); vsip_mview_d *A = vsip_mbind_d(vblk,3,3 * N, M,2 , N); vsip_mview_d *U = vsip_mcreate_d(M,M,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *V = vsip_mcreate_d(N,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *B = vsip_mcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_d(block,VSIP_TRUE); vsip_mcopy_d_d(A0,A); printf("in = ");VU_mprintm_d("6.3",A); if(vsip_svd_d(svd,A,s)){ printf("svd error\n"); return; } /* create the singular value matrix */ vsip_mfill_d(0.0,B); for(i=0; i<vsip_vgetlength_d(s); i++) vsip_mput_d(B,i,i,vsip_vget_d(s,i)); vsip_svdmatu_d(svd, 0, M-1, U); vsip_svdmatv_d(svd, 0, N-1, V); printf("U = ");VU_mprintm_d("12.10",U); printf("B = ");VU_mprintm_d("12.10",B); printf("V = ");VU_mprintm_d("12.10",V); VU_vprintm_d("12.10",s); { /* check that A0 = U * B * V' */ vsip_scalar_d chk = 1.0; vsip_scalar_d lim = 5 * DBL_EPSILON * vsip_sqrt_d(vsip_msumsqval_d(A0)); vsip_mview_d *dif=vsip_mcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *out = vsip_mcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *Vt = vsip_mtransview_d(V); vsip_mprod_d(U,B,dif); vsip_mprod_d(dif,Vt,out); vsip_msub_d(out,A0,dif); vsip_mmag_d(dif, dif); chk = vsip_msumval_d(dif)/(2 * M * N); printf("%20.18e - %20.18e = %e\n",lim,chk, (lim - chk)); if(chk > lim){ printf("error\n"); } else { printf("correct\n"); } vsip_malldestroy_d(dif); vsip_malldestroy_d(out); vsip_mdestroy_d(Vt); } vsip_svd_destroy_d(svd); vsip_malldestroy_d(A0); vsip_malldestroy_d(A); vsip_valldestroy_d(s); vsip_malldestroy_d(U); vsip_malldestroy_d(B); vsip_malldestroy_d(V); } return; } <file_sep>def frefine(a,rs): """ % f = frefine(a,rs); % refine local minima and maxima of H using Newton's method % H : H = a(1)+a(2)*cos(w)+...+a(n+1)*cos(n*w) % rs : initial values for the extrema of H % see also : frefine.m, frefine_e.m """ w = rs.copy m = a.empty.ramp(0.0,1.0) for k in range(12): H = w.outer(m).cos.prod(a) H1 = (w.outer(m).sin.neg).prod(m * a); H2 = (w.outer(m).cos.neg).prod(m.copy.sq * a) w -= H1*H2.recip; return w <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mtan_d.h,v 2.0 2003/02/22 15:23:26 judd Exp $ */ #include"VU_mprintm_d.include" static void mtan_d(void){ printf("\n*******\nTEST mtan_d\n\n"); { vsip_scalar_d data[] = {M_PI/8.0, M_PI/4.0, M_PI/3.0, M_PI/1.5, 1.25 * M_PI, 1.75 * M_PI}; vsip_scalar_d ans[] = {0.4142, 1.0000, 1.7321,-1.7321,1.0000,-1.0000}; vsip_block_d *block = vsip_blockbind_d(data,6,VSIP_MEM_NONE); vsip_block_d *ans_block = vsip_blockbind_d(ans,6,VSIP_MEM_NONE); vsip_mview_d *a = vsip_mbind_d(block,0,2,3,1,2); vsip_mview_d *ansm = vsip_mbind_d(ans_block,0,2,3,1,2); vsip_mview_d *b = vsip_mcreate_d(3,2,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *chk = vsip_mcreate_d(3,2,VSIP_COL,VSIP_MEM_NONE); vsip_blockadmit_d(block,VSIP_TRUE); vsip_blockadmit_d(ans_block,VSIP_TRUE); printf("test out of place, compact, user \"a\", vsipl \"b\"\n"); vsip_mtan_d(a,b); printf("mtan_d(a,b)\n matrix a\n");VU_mprintm_d("8.6",a); printf("matrix b\n");VU_mprintm_d("8.6",b); printf("expected answer to 4 decimal digits\n");VU_mprintm_d("8.4",ansm); vsip_msub_d(b,ansm,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check mtan_d in place\n"); vsip_mtan_d(a,a); vsip_msub_d(a,ansm,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_d(a); vsip_malldestroy_d(b); vsip_malldestroy_d(chk); vsip_malldestroy_d(ansm); } return; } <file_sep>// // main.cpp // supportTest // // Created by <NAME> on 4/20/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #include <iostream> #include <jvsiph.h> int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; jvsip::view aView("f",10); aView.ramp(.1f, .2f); jvsip::scalar aScalar(100.0f); return 0; } <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vcopyto_user_f.h,v 1.1 2007/04/18 03:59:06 judd Exp $ */ #include"VU_vprintm_f.include" static void vcopyto_user_f(void){ printf("********\nTEST vcopyto_user_f\n"); { int i; vsip_block_f *block = vsip_blockcreate_f(200,VSIP_MEM_NONE); vsip_scalar_f ans[5]={0,1,2,3,4},output[5]; vsip_vview_f *view = vsip_vbind_f(block,100,-3,5); vsip_vview_f *all = vsip_vbind_f(block,0,1,200); vsip_scalar_f check = 0; vsip_vfill_f(-1,all); vsip_vramp_f(0,1.0,view); vsip_vcopyto_user_f(view,output); VU_vprintm_f("3.2",view); for(i=0; i<5; i++){ printf("%f\n",(float)output[i]); check += fabs(output[i] - ans[i]); } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_vdestroy_f(all); vsip_vdestroy_f(view); vsip_blockdestroy_f(block); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cvlog_d.h,v 2.0 2003/02/22 15:23:23 judd Exp $ */ #include"VU_cvprintm_d.include" static void cvlog_d(void){ printf("\n********\nTEST cvlog_d\n\n"); { /* create some space */ vsip_cscalar_d a0,a1,a2,a3,a4,a5; vsip_cvview_d *a = vsip_cvcreate_d(12,VSIP_MEM_NONE); vsip_cvview_d *ab = vsip_cvsubview_d(a,0,6); vsip_cvview_d *ac = vsip_cvsubview_d(a,1,6); vsip_cvview_d *ans = vsip_cvcreate_d(6,VSIP_MEM_NONE); vsip_cvview_d *chk = vsip_cvcreate_d(6,VSIP_MEM_NONE); vsip_vview_d *chk_r = vsip_vimagview_d(chk); vsip_scalar_d data1[12]; vsip_scalar_d data2[6]; vsip_scalar_d data3[6]; vsip_cvview_d *ua = vsip_cvbind_d( vsip_cblockbind_d(data1,(vsip_scalar_d*)NULL,6,VSIP_MEM_NONE), 0,1,6); /* interleaved */ vsip_cvview_d *ub = vsip_cvbind_d( vsip_cblockbind_d(data2,data3,6,VSIP_MEM_NONE), 0,1,6); /* split */ vsip_cblockadmit_d(vsip_cvgetblock_d(ua),VSIP_FALSE); vsip_cblockadmit_d(vsip_cvgetblock_d(ub),VSIP_FALSE); vsip_cvputstride_d(ab,2); vsip_cvputstride_d(ac,2); /* put some data in a */ a0 = vsip_cmplx_d(0,1); a1 = vsip_cmplx_d(1, 0); a2 = vsip_cmplx_d(-1,VSIP_MEM_NONE); a3 = vsip_cmplx_d(1,1); a4 = vsip_cmplx_d(1,-1); a5 = vsip_cmplx_d(0,1); vsip_cvput_d(ab,0,a0); vsip_cvput_d(ab,1,a1); vsip_cvput_d(ab,2,a2); vsip_cvput_d(ab,3,a3); vsip_cvput_d(ab,4,a4); vsip_cvput_d(ab,5,a5); a0 = vsip_cmplx_d(0,1.5708); a1 = vsip_cmplx_d(0, 0); a2 = vsip_cmplx_d(0,3.1416); a3 = vsip_cmplx_d(.3466,.7854); a4 = vsip_cmplx_d(.3466,-.7854); a5 = vsip_cmplx_d(0.0,1.5708); vsip_cvput_d(ans,0,a0); vsip_cvput_d(ans,1,a1); vsip_cvput_d(ans,2,a2); vsip_cvput_d(ans,3,a3); vsip_cvput_d(ans,4,a4); vsip_cvput_d(ans,5,a5); printf("input vector ab\n"); printf("ab from \"a\" stride 2 offset 0\n");VU_cvprintm_d("8.6",ab); vsip_cvlog_d(ab,ac); printf("ac from \"a\" stride 2 offset 1\n"); printf("output of cvlog_d(ab,ac)\n"); VU_cvprintm_d("8.6",ac); printf("expected output to four decimal\n"); VU_cvprintm_d("8.4",ans); vsip_cvsub_d(ac,ans,chk); vsip_cvmag_d(chk,chk_r); vsip_vclip_d(chk_r,.0002,.0002,0,1,chk_r); if(vsip_vsumval_d(chk_r) > .5) printf(" cvlog_d in error\n"); else { printf("cvlog_d correct to 4 decimal digits for\n"); printf("input vsipl vector of stride 2, output vsipl vector of stride 2\n"); } printf("\ntest cvlog for \"user data case\"\n"); printf("with user interleaved data on input\n"); printf("and user split data on output\n"); vsip_cvcopy_d_d(ab,ua); vsip_cvlog_d(ua,ub); vsip_cvsub_d(ub,ans,chk); vsip_cvmag_d(chk,chk_r); vsip_vclip_d(chk_r,.0002,.0002,0,1,chk_r); if(vsip_vsumval_d(chk_r) > .5) printf("cvlog_d in error for user data case \n"); else { printf("cvlog_d correct to 4 decimal digits for "); printf("user data case\n"); vsip_cvdestroy_d(ab); vsip_cvdestroy_d(ac);vsip_cvalldestroy_d(a); vsip_cvalldestroy_d(ans); vsip_vdestroy_d(chk_r); vsip_cvalldestroy_d(chk); } } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmgather_f.h,v 2.0 2003/02/22 15:23:21 judd Exp $ */ #include"VU_cmprintm_f.include" #include"VU_cvprintm_f.include" #include"VU_vprintm_mi.include" void cmgather_f(void){ printf("\n******\nTEST cmgather_f\n"); { vsip_scalar_f data1_r[]= {1, .1, 2, .2, 3,.3, 4,-.1, 5, -.3, 6,-.4, 7,.8, 8,.9, 9,-1}; vsip_scalar_f data1_i[]= {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,13,14,15,16,17,18}; vsip_scalar_vi data_index[] = {0,1 , 1,1 , 2,3 , 3,3 , 2,1}; vsip_scalar_f data_ans_r[] = {.1,.3,-.4, .9, -.3}; vsip_scalar_f data_ans_i[] = { 2, 6, 12, 16, 10}; vsip_cmview_f *a = vsip_cmbind_f( vsip_cblockbind_f(data1_r,data1_i,18,VSIP_MEM_NONE),0,4,4,1,4); vsip_vview_mi *index = vsip_vbind_mi(/* matrix index is always interleaved */ vsip_blockbind_mi(data_index,5,VSIP_MEM_NONE),0,1,5); vsip_cvview_f *ans = vsip_cvbind_f( vsip_cblockbind_f(data_ans_r,data_ans_i,9,VSIP_MEM_NONE),0,1,5); vsip_cvview_f *c = vsip_cvcreate_f(5,VSIP_MEM_NONE); vsip_cvview_f *chk = vsip_cvcreate_f(5,VSIP_MEM_NONE); vsip_vview_f *chk_i = vsip_vimagview_f(chk); vsip_cblockadmit_f(vsip_cmgetblock_f(a),VSIP_TRUE); vsip_blockadmit_mi(vsip_vgetblock_mi(index),VSIP_TRUE); vsip_cblockadmit_f(vsip_cvgetblock_f(ans),VSIP_TRUE); printf("call vsip_cmgather_f(a,index,c) \n"); vsip_cmgather_f(a,index,c); printf("a =\n");VU_cmprintm_f("8.6",a); printf("index =\n");VU_vprintm_mi("",index); printf("c=\n");VU_cvprintm_f("8.6",c); printf("\nright answer =\n"); VU_cvprintm_f("6.4",ans); vsip_cvsub_f(ans,c,chk); vsip_cvmag_f(chk,chk_i); vsip_vclip_f(chk_i,0,2 * .0001,0,1,chk_i); if(fabs(vsip_vsumval_f(chk_i)) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a); vsip_valldestroy_mi(index); vsip_cvalldestroy_f(c); vsip_cvalldestroy_f(ans); vsip_valldestroy_f(chk_i); vsip_cvalldestroy_f(chk); } return; } <file_sep>/* Created RJudd June 5, 2002 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_cblockdestroy_f_di.h,v 2.0 2003/02/22 15:18:28 judd Exp $ */ /* VI_cblockdestroy_f default interleaved */ if(NULL != b){ b->markings = VSIP_FREED_STRUCTURE_OBJECT; b->R->markings = VSIP_FREED_STRUCTURE_OBJECT; b->I->markings = VSIP_FREED_STRUCTURE_OBJECT; if(b->kind == VSIP_VSIPL_BLOCK) free((void*)b->R->array); free((void*)b->R); free((void*)b->I); free((void*)b); } <file_sep>/* Created RJudd March 14, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cmvprod_d.c,v 2.2 2006/04/18 17:04:53 judd Exp $ */ /* Modified to vsip_cmvprod_d.c */ /* Removed Tisdale error checking Sept 00 */ #include"vsip.h" #include"vsip_cvviewattributes_d.h" #include"vsip_cmviewattributes_d.h" void (vsip_cmvprod_d)( const vsip_cmview_d* A, const vsip_cvview_d* b, const vsip_cvview_d* r) { if((A->block->cstride == 2) && (b->block->cstride == 2) && (r->block->cstride == 2)){ vsip_length nx = 0, mx = 0; vsip_stride cbst = b->block->cstride, crst = b->block->cstride, cAst = A->block->cstride; vsip_scalar_d *bp_r = (vsip_scalar_d*)(b->block->R->array + cbst * b->offset), *rp_r = (vsip_scalar_d*)(r->block->R->array + crst * r->offset), *Axp_r = (vsip_scalar_d*)(A->block->R->array + cAst * A->offset), *Aypr = Axp_r; vsip_stride stb = cbst * b->stride, str = crst * r->stride, stA = cAst * A->row_stride; vsip_scalar_d dot_r, dot_i; while(nx++ < A->col_length){ mx = 0; dot_r = 0; dot_i = 0; while(mx++ < A->row_length){ vsip_scalar_d Ar = *Axp_r, Ai = *(Axp_r + 1); vsip_scalar_d br = *bp_r, bi = *(bp_r + 1); dot_r += br * Ar - bi * Ai; dot_i += br * Ai + bi * Ar; bp_r += stb; Axp_r += stA; } *rp_r = dot_r; *(rp_r + 1) = dot_i; bp_r = (vsip_scalar_d*)(b->block->R->array + cbst * b->offset); Axp_r = (Aypr += (cAst * A->col_stride)); rp_r += str; } } else { vsip_length nx = 0, mx = 0; vsip_stride cbst = b->block->cstride, crst = r->block->cstride, cAst = A->block->cstride; vsip_scalar_d *bp_r = (vsip_scalar_d*)(b->block->R->array + cbst * b->offset), *bp_i = (vsip_scalar_d*)(b->block->I->array + cbst * b->offset), *rp_r = (vsip_scalar_d*)(r->block->R->array + crst * r->offset), *rp_i = (vsip_scalar_d*)(r->block->I->array + crst * r->offset), *Axp_r = (vsip_scalar_d*)(A->block->R->array + cAst * A->offset), *Axp_i = (vsip_scalar_d*)(A->block->I->array + cAst * A->offset), *Aypr = Axp_r, *Aypi = Axp_i; vsip_stride stb = cbst * b->stride, str = crst * r->stride, stA = cAst * A->row_stride; vsip_scalar_d dot_r, dot_i; while(nx++ < A->col_length){ dot_r = 0; dot_i = 0; mx = 0; while(mx++ < A->row_length){ dot_r += *bp_r * *Axp_r - *bp_i * *Axp_i; dot_i += *bp_r * *Axp_i + *bp_i * *Axp_r; bp_r += stb; Axp_r += stA; bp_i += stb; Axp_i += stA; } *rp_r = dot_r; *rp_i = dot_i; bp_r = (vsip_scalar_d*)(b->block->R->array + cbst * b->offset); bp_i = (vsip_scalar_d*)(b->block->I->array + cbst * b->offset); Axp_r = (Aypr += (cAst * A->col_stride)); Axp_i = (Aypi += (cAst * A->col_stride)); rp_r += str; rp_i += str; } } } <file_sep>/* Created RJudd September 29, 1999*/ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cmrecip_f.c,v 2.0 2003/02/22 15:18:44 judd Exp $ */ #include"vsip.h" #include"vsip_cmviewattributes_f.h" void (vsip_cmrecip_f)( const vsip_cmview_f *a, const vsip_cmview_f *r) { { vsip_length n_mj, /* major length */ n_mn; /* minor length */ vsip_stride ast_mj, ast_mn, rst_mj, rst_mn; vsip_scalar_f *ap_r = (a->block->R->array) + a->offset * a->block->cstride, *rp_r = (r->block->R->array) + r->offset * r->block->cstride; vsip_scalar_f *ap_i = (a->block->I->array) + a->offset * a->block->cstride, *rp_i = (r->block->I->array) + r->offset * r->block->cstride; vsip_scalar_f *ap0_r = ap_r, *rp0_r = rp_r; vsip_scalar_f *ap0_i = ap_i, *rp0_i = rp_i; vsip_scalar_f rmag; /* pick direction dependent on output */ if(r->row_stride < r->col_stride){ n_mj = r->row_length; n_mn = r->col_length; rst_mj = r->row_stride; rst_mn = r->col_stride; ast_mj = a->row_stride; ast_mn = a->col_stride; rst_mj *= r->block->cstride; rst_mn *= r->block->cstride; ast_mj *= a->block->cstride; ast_mn *= a->block->cstride; } else { n_mn = r->row_length; n_mj = r->col_length; rst_mn = r->row_stride; rst_mj = r->col_stride; ast_mn = a->row_stride; ast_mj = a->col_stride; rst_mn *= r->block->cstride; rst_mj *= r->block->cstride; ast_mn *= a->block->cstride; ast_mj *= a->block->cstride; } /*end define*/ if(ap_i == rp_i){ /* inplace */ while(n_mn-- > 0){ vsip_length n = n_mj; while(n-- >0){ rmag = (*rp_r * *rp_r + *rp_i * *rp_i); *rp_r /= rmag; *rp_i /= (- rmag); rp_r += rst_mj; rp_i += rst_mj; } rp0_r += rst_mn; rp0_i += rst_mn; rp_r = rp0_r; rp_i = rp0_i; } } else { while(n_mn-- > 0){ vsip_length n = n_mj; while(n-- >0){ rmag = (*ap_r * *ap_r + *ap_i * *ap_i); *rp_r = *ap_r / rmag; *rp_i = - *ap_i / rmag; ap_r += ast_mj; rp_r += rst_mj; ap_i += ast_mj; rp_i += rst_mj; } ap0_r += ast_mn; rp0_r += rst_mn; ap0_i += ast_mn; rp0_i += rst_mn; ap_r = ap0_r; rp_r = rp0_r; ap_i = ap0_i; rp_i = rp0_i; } } } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mfill_f.h,v 2.0 2003/02/22 15:23:24 judd Exp $ */ #include"VU_mprintm_f.include" static void mfill_f(void){ printf("\n******\nTEST mfill_f\n"); { vsip_scalar_f alpha = 1.2345; vsip_scalar_f ans[] = {1.2345,1.2345,1.2345,1.2345,1.2345,1.2345,1.2345,1.2345,1.2345}; vsip_mview_f *ma = vsip_mbind_f( vsip_blockbind_f(ans,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_mview_f *chk = vsip_mcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *B = vsip_mcreate_f(9,9,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *b = vsip_msubview_f(B,2,2,3,3); vsip_blockadmit_f(vsip_mgetblock_f(ma),VSIP_TRUE); vsip_mputrowstride_f(b,4); printf("call vsip_mfill_f(alpha,b)\n"); printf("alpha = %f\n",alpha); vsip_mfill_f(alpha,b); printf("b =\n");VU_mprintm_f("8.6",b); printf("\nright answer =\n"); VU_mprintm_f("6.4",ma); vsip_msub_f(ma,b,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,0,.0001,0,1,chk); if(fabs(vsip_msumval_f(chk)) > .5) printf("error\n"); else printf("correct\n"); vsip_mdestroy_f(b); vsip_malldestroy_f(B); vsip_malldestroy_f(ma); vsip_malldestroy_f(chk); } return; } <file_sep>/* Created R Judd March 18, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mtrans_f.c,v 2.0 2003/02/22 15:19:01 judd Exp $ */ /* April 21, 1998 1,2 to row,col */ /* Removed Development Mode RJudd Sept 00 */ #include"vsip.h" #include"vsip_mviewattributes_f.h" void (vsip_mtrans_f)( const vsip_mview_f* A, const vsip_mview_f* R) { /* transpose matrix */ { vsip_length lx = A->row_length, ly = A->col_length; vsip_scalar_f tmp; vsip_scalar_f *a_p = A->block->array + A->offset * A->block->rstride, *r_p = R->block->array + R->offset * R->block->rstride; vsip_length i, j; vsip_stride stAx = A->row_stride * A->block->rstride, stAy = A->col_stride * A->block->rstride; vsip_stride stRx = R->row_stride * R->block->rstride, stRy = R->col_stride * R->block->rstride; if((lx == ly) && (a_p == r_p)){ for(i=1; i<lx; i++){ for(j=0; j<i; j++){ tmp = *(a_p + j * stAy + i * stAx); *(a_p + j * stAy + i * stAx) = *(a_p + j * stAx + i * stAy); *(a_p + j * stAx + i * stAy) = tmp; } } } else { for(i=0; i<ly; i++){ r_p = R->block->array + R->offset * R->block->rstride + i * stRx; a_p = A->block->array + A->offset * A->block->rstride + i * stAy; for(j=0; j<lx; j++){ *r_p = *a_p; r_p += stRy; a_p += stAx; } } } } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mscatter_d.h,v 2.0 2003/02/22 15:23:26 judd Exp $ */ #include"VU_mprintm_d.include" #include"VU_vprintm_d.include" #include"VU_vprintm_mi.include" static void mscatter_d(void){ printf("\n******\nTEST mscatter_d\n"); { vsip_scalar_d data1[]= {1, .1, 2, .2, 3,.3, 4,-.1, 5, -.3, 6,-.4, 7,.8, 8,.9, 9,-1}; vsip_scalar_vi data_index[] = {0,1 , 1,1 , 2,3 , 3,3 , 2,1}; vsip_scalar_d data_ans[] = { 0.0, -1.0, 0.0, 0.0, 0.0, 0.9, 0.0, 0.0, 0.0, -.3, 0.0, 0.8, 0.0, 0.0, 0.0, -.4}; vsip_vview_d *a = vsip_vbind_d( vsip_blockbind_d(data1,18,VSIP_MEM_NONE),17,-2,5); vsip_vview_mi *index = vsip_vbind_mi(/* matrix index is always interleaved */ vsip_blockbind_mi(data_index,5,VSIP_MEM_NONE),0,1,5); vsip_mview_d *ans = vsip_mbind_d( vsip_blockbind_d(data_ans,16,VSIP_MEM_NONE),0,4,4,1,4); vsip_mview_d *b = vsip_mcreate_d(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *chk = vsip_mcreate_d(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_d(vsip_vgetblock_d(a),VSIP_TRUE); vsip_blockadmit_mi(vsip_vgetblock_mi(index),VSIP_TRUE); vsip_blockadmit_d(vsip_mgetblock_d(ans),VSIP_TRUE); vsip_mfill_d(0,b); printf("call vsip_mscatter_d(a,b,index) \n"); vsip_mscatter_d(a,b,index); printf("a =\n");VU_vprintm_d("8.6",a); printf("index =\n");VU_vprintm_mi("",index); printf("b=\n");VU_mprintm_d("8.6",b); printf("\nright answer =\n"); VU_mprintm_d("6.4",ans); vsip_msub_d(ans,b,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,0,2 * .0001,0,1,chk); if(fabs(vsip_msumval_d(chk)) > .5) printf("error\n"); else printf("correct\n"); vsip_valldestroy_d(a); vsip_valldestroy_mi(index); vsip_malldestroy_d(b); vsip_malldestroy_d(chk); } return; } <file_sep>/* Created RJudd */ /* */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmprod4_d.h,v 2.1 2006/04/27 01:40:55 judd Exp $ */ #include"VU_cmprintm_d.include" static void cmprod4_d(void){ printf("********\nTEST cmprod4_d\n"); { vsip_scalar_d datal_r[] = {1.0, 2.0, 3.0, 4.0, 5.0, 5.0, 0.1, 0.2, 0.3, 0.4, 4.0, 3.0, 2.0, 0.0, -1.0, 1.0}; vsip_scalar_d datal_i[] = {9.0, 3.0, 2.0, 4.3, 3.2, 5.0, 0.1, 1.2, 0.3, 1.4, 0.3, 2.0, -2.1, 0.1, 1.0, 2.0}; vsip_scalar_d datar_r[] = {0.1, 0.2, 0.3, 0.4, 1.0, 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 2.4, -1.1, -2.2, -2.3, -1.4, 3.1, 0.2, 1.1, 1.4, -2.1, -1.0, 1.5, 2.4, 3.1, 2.2, 1.3, 0.4, -1.1, -1.3, 4.3, -1.4}; vsip_scalar_d datar_i[] = { 1.1, 5.2, 3.3, 1.4, 2.1, 1.0, 1.2, 1.2, 4.1, 3.0, 2.3, 2.3, 1.1, -6.2, -1.3, 9.3, 2.1, 2.0, 2.1, 1.3, 1.4, -0.2, -2.3, 0.5, 1.0, 2.2, -2.3, 3.4, 4.6, 5.0, 2.1, 7.3}; /* we use vsip_cmprod_d to fill up the answer data space */ vsip_scalar_d ans_data_r[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; vsip_scalar_d ans_data_i[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; vsip_cblock_d *blockl = vsip_cblockbind_d(datal_r,datal_i,16,VSIP_MEM_NONE); vsip_cblock_d *blockr = vsip_cblockbind_d(datar_r,datar_i,32,VSIP_MEM_NONE); vsip_cblock_d *block_ans = vsip_cblockbind_d(ans_data_r,ans_data_i,32,VSIP_MEM_NONE); vsip_cblock_d *block = vsip_cblockcreate_d(250,VSIP_MEM_NONE); vsip_cmview_d *ml = vsip_cmbind_d(blockl,0,4,4,1,4); vsip_cmview_d *mr = vsip_cmbind_d(blockr,0,8,4,1,8); vsip_cmview_d *ans = vsip_cmbind_d(block_ans,0,8,4,1,8); vsip_cmview_d *a = vsip_cmbind_d(block,70,-1,4,-6,4); vsip_cmview_d *b = vsip_cmbind_d(block,71, 1,4,5,8); vsip_cmview_d *c = vsip_cmbind_d(block,220,-9,4,-1,8); vsip_cmview_d *chk = vsip_cmcreate_d(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *chk_r = vsip_mrealview_d(chk); vsip_cblockadmit_d(blockl,VSIP_TRUE); vsip_cblockadmit_d(blockr,VSIP_TRUE); vsip_cblockadmit_d(block_ans,VSIP_TRUE); vsip_cmcopy_d_d(ml,a); vsip_cmcopy_d_d(mr,b); vsip_cmprod_d(a,b,ans); vsip_cmprod4_d(a,b,c); printf("vsip_cmprod4_d(a,b,c)\n"); printf("a\n"); VU_cmprintm_d("6.4",a); printf("b\n"); VU_cmprintm_d("6.4",b); printf("c\n"); VU_cmprintm_d("6.4",c); printf("right answer\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(c,ans,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); { /* ccc */ vsip_cmview_d *a1 = vsip_cmcreate_d(4,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_d *b1 = vsip_cmcreate_d(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_d *c1 = vsip_cmcreate_d(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmcopy_d_d(a,a1); vsip_cmcopy_d_d(b,b1); vsip_cmprod4_d(a1,b1,c1); printf("c1\n"); VU_cmprintm_d("6.4",c1); printf("right answer\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(c1,ans,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(a1); vsip_cmalldestroy_d(b1); vsip_cmalldestroy_d(c1); } { /* ccr */ vsip_cmview_d *a1 = vsip_cmcreate_d(4,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_d *b1 = vsip_cmcreate_d(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_d *c1 = vsip_cmcreate_d(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmcopy_d_d(a,a1); vsip_cmcopy_d_d(b,b1); vsip_cmprod4_d(a1,b1,c1); printf("c1\n"); VU_cmprintm_d("6.4",c1); printf("right answer\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(c1,ans,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(a1); vsip_cmalldestroy_d(b1); vsip_cmalldestroy_d(c1); } { /* crc */ vsip_cmview_d *a1 = vsip_cmcreate_d(4,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_d *b1 = vsip_cmcreate_d(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *c1 = vsip_cmcreate_d(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmcopy_d_d(a,a1); vsip_cmcopy_d_d(b,b1); vsip_cmprod4_d(a1,b1,c1); printf("c1\n"); VU_cmprintm_d("6.4",c1); printf("right answer\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(c1,ans,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(a1); vsip_cmalldestroy_d(b1); vsip_cmalldestroy_d(c1); } { /* crr */ vsip_cmview_d *a1 = vsip_cmcreate_d(4,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_d *b1 = vsip_cmcreate_d(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *c1 = vsip_cmcreate_d(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmcopy_d_d(a,a1); vsip_cmcopy_d_d(b,b1); vsip_cmprod4_d(a1,b1,c1); printf("c1\n"); VU_cmprintm_d("6.4",c1); printf("right answer\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(c1,ans,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(a1); vsip_cmalldestroy_d(b1); vsip_cmalldestroy_d(c1); } { /* rcc */ vsip_cmview_d *a1 = vsip_cmcreate_d(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *b1 = vsip_cmcreate_d(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_d *c1 = vsip_cmcreate_d(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmcopy_d_d(a,a1); vsip_cmcopy_d_d(b,b1); vsip_cmprod4_d(a1,b1,c1); printf("c1\n"); VU_cmprintm_d("6.4",c1); printf("right answer\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(c1,ans,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(a1); vsip_cmalldestroy_d(b1); vsip_cmalldestroy_d(c1); } { /* rcr */ vsip_cmview_d *a1 = vsip_cmcreate_d(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *b1 = vsip_cmcreate_d(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_d *c1 = vsip_cmcreate_d(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmcopy_d_d(a,a1); vsip_cmcopy_d_d(b,b1); vsip_cmprod4_d(a1,b1,c1); printf("c1\n"); VU_cmprintm_d("6.4",c1); printf("right answer\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(c1,ans,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(a1); vsip_cmalldestroy_d(b1); vsip_cmalldestroy_d(c1); } { /* rrc */ vsip_cmview_d *a1 = vsip_cmcreate_d(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *b1 = vsip_cmcreate_d(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *c1 = vsip_cmcreate_d(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmcopy_d_d(a,a1); vsip_cmcopy_d_d(b,b1); vsip_cmprod4_d(a1,b1,c1); printf("c1\n"); VU_cmprintm_d("6.4",c1); printf("right answer\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(c1,ans,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(a1); vsip_cmalldestroy_d(b1); vsip_cmalldestroy_d(c1); } { /* rrr */ vsip_cmview_d *a1 = vsip_cmcreate_d(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *b1 = vsip_cmcreate_d(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *c1 = vsip_cmcreate_d(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmcopy_d_d(a,a1); vsip_cmcopy_d_d(b,b1); vsip_cmprod4_d(a1,b1,c1); printf("c1\n"); VU_cmprintm_d("6.4",c1); printf("right answer\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(c1,ans,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(a1); vsip_cmalldestroy_d(b1); vsip_cmalldestroy_d(c1); } vsip_cmalldestroy_d(ml); vsip_cmalldestroy_d(mr); vsip_cmdestroy_d(a); vsip_cmdestroy_d(b); vsip_cmalldestroy_d(c); vsip_cmalldestroy_d(ans); vsip_mdestroy_d(chk_r); vsip_cmalldestroy_d(chk); } return; } <file_sep>/* // jvsip_svd_d.c // jvsipF // // Created by <NAME> on 4/21/13. // Copyright (c) 2013 Independent Consultant. All rights reserved. */ /********************************************************************* // This code includes no warranty, express or implied, including / // the warranties of merchantability and fitness for a particular / // purpose. / // No person or entity assumes any legal liability or responsibility / // for the accuracy, completeness, or usefulness of any information, / // apparatus, product, or process disclosed, or represents that / // its use would not infringe privately owned rights. / *********************************************************************/ /********************************************************************* // The MIT License (see copyright for jvsip in top level directory) // http://opensource.org/licenses/MIT **********************************************************************/ #include"vsip.h" #include"vsip_svdattributes_d.h" #include"VI.h" #include"vsip_blockattributes_d.h" #include"vsip_cblockattributes_d.h" #include"vsip_blockattributes_vi.h" #include"vsip_vviewattributes_d.h" #include"vsip_mviewattributes_d.h" #include"vsip_cvviewattributes_d.h" #include"vsip_cmviewattributes_d.h" #include"vsip_vviewattributes_vi.h" #define EPS DBL_EPSILON #define VI_VGET_F(v,i) (*(v->block->array + (v->offset + (vsip_stride)(i) * v->stride) * v->block->rstride)) #define scaleV(v) { \ vsip_index k;vsip_scalar_d *p = v->block->array + v->offset * v->block->rstride;\ vsip_stride std = v->stride * v->block->rstride;vsip_length n = v->length * std;\ vsip_scalar_d scl = p[0];p[0]=1.0;for(k=std; k<n; k+=std) p[k] /= scl; \ } #define CMAG_F(re,im) ((re == 0.0) ? im:(im< re) ? re * (vsip_scalar_d)sqrt(1.0 + (im/re) * (im/re)): \ im * (vsip_scalar_d)sqrt(1.0 + (re/im) * (re/im))) /* coded for this routine. Only done in place */ #define csvmul_d(alpha, b) {\ vsip_length _n = b->length; vsip_stride cbst = b->block->cstride;\ vsip_scalar_d *bpr = b->block->R->array + cbst * b->offset,*bpi = b->block->I->array + cbst * b->offset;\ register vsip_scalar_d temp; vsip_stride bst = cbst * b->stride;\ while(_n-- > 0){temp = alpha.r * *bpr - *bpi * alpha.i;*bpi = alpha.r * *bpi + alpha.i * *bpr;*bpr = temp;\ bpr += bst; bpi += bst;}} #define cvcopy_d(a, r) {\ vsip_length _n = (r)->length;vsip_stride cast = (a)->block->cstride,crst = (r)->block->cstride;\ vsip_scalar_d *apr = (a)->block->R->array + cast * (a)->offset,*rpr = (r)->block->R->array + crst * (r)->offset;\ vsip_scalar_d *api = (a)->block->I->array + cast * (a)->offset,*rpi = (r)->block->I->array + crst * (r)->offset;\ vsip_stride ast = (cast * (a)->stride),rst = (crst * (r)->stride);\ while(_n-- > 0){*rpr = *apr;*rpi = *api;apr += ast; api += ast;rpr += rst; rpi += rst;}} #define vcopy_d(a,r) {vsip_length _n = (r)->length;\ vsip_stride ast = (a)->stride * (a)->block->rstride,rst = (r)->stride * (r)->block->rstride;\ vsip_scalar_d *ap = (a)->block->array + (a)->offset * (a)->block->rstride,*rp = (r)->block->array+(r)->offset * (r)->block->rstride;\ while(_n-- > 0){*rp = *ap;ap += ast; rp += rst;}} #define vcopy_vi(a,r) {vsip_length _n = (r)->length;\ vsip_stride ast = (a)->stride,rst = (r)->stride;\ vsip_scalar_vi *ap = (a)->block->array + (a)->offset,*rp = (r)->block->array+(r)->offset;\ while(_n-- > 0){*rp = *ap;ap += ast; rp += rst;}} #define mcopy_d(a,r) {vsip_length n_mj,n_mn;vsip_stride ast_mj, ast_mn,rst_mj, rst_mn;\ vsip_scalar_d *rp = ((r)->block->array) + (r)->offset * (r)->block->rstride,\ *ap = ((a)->block->array) + (a)->offset * (a)->block->rstride;vsip_scalar_d *rp0 = rp,*ap0 = ap;\ if((r)->row_stride < (r)->col_stride){n_mj = (r)->row_length; n_mn = (r)->col_length;\ rst_mj = (r)->row_stride; rst_mn = (r)->col_stride;ast_mj = (a)->row_stride; ast_mn = (a)->col_stride;\ rst_mj *= (r)->block->rstride; rst_mn *= (r)->block->rstride;ast_mj *= (a)->block->rstride; ast_mn *= (a)->block->rstride;\ } else {n_mn = (r)->row_length; n_mj = (r)->col_length;\ rst_mn = (r)->row_stride; rst_mj = (r)->col_stride;ast_mn = (a)->row_stride; ast_mj = (a)->col_stride;\ rst_mn *= (r)->block->rstride; rst_mj *= (r)->block->rstride;ast_mn *= (a)->block->rstride; ast_mj *= (a)->block->rstride;\ } while(n_mn-- > 0){vsip_length n = n_mj;while(n-- >0){*rp = *ap;ap += ast_mj; rp += rst_mj;\ }ap0 += ast_mn; rp0 += rst_mn;ap = ap0; rp = rp0;}} #define cmcopy_d(a,r) {vsip_length n_mj, n_mn; vsip_stride ast_mj, ast_mn,rst_mj, rst_mn; \ vsip_scalar_d *ap_r = (a)->block->R->array + (a)->offset * (a)->block->cstride,*rp_r = (r)->block->R->array + (r)->offset * (r)->block->cstride;\ vsip_scalar_d *ap_i = (a)->block->I->array + (a)->offset * (a)->block->cstride,*rp_i = (r)->block->I->array + (r)->offset * (r)->block->cstride;\ vsip_scalar_d *ap0_r = ap_r,*rp0_r = rp_r,*ap0_i = ap_i,*rp0_i = rp_i;\ if((r)->row_stride < (r)->col_stride){n_mj = (r)->row_length; n_mn = (r)->col_length;\ rst_mj = (r)->row_stride; rst_mn = (r)->col_stride;ast_mj = (a)->row_stride; ast_mn = (a)->col_stride;\ rst_mj *= (r)->block->cstride; rst_mn *= (r)->block->cstride;ast_mj *= (a)->block->cstride; ast_mn *= (a)->block->cstride;\ } else {n_mn = (r)->row_length; n_mj = (r)->col_length;\ rst_mn = (r)->row_stride; rst_mj = (r)->col_stride;ast_mn = (a)->row_stride; ast_mj = (a)->col_stride;\ rst_mn *= (r)->block->cstride; rst_mj *= (r)->block->cstride;ast_mn *= (a)->block->cstride; ast_mj *= (a)->block->cstride;}\ while(n_mn-- > 0){vsip_length n = n_mj;while(n-- >0){*rp_r = *ap_r;*rp_i = *ap_i;ap_r += ast_mj; rp_r += rst_mj;\ ap_i += ast_mj; rp_i += rst_mj;}ap0_r += ast_mn; rp0_r += rst_mn;ap0_i += ast_mn; rp0_i += rst_mn;\ ap_r = ap0_r; rp_r = rp0_r; ap_i = ap0_i; rp_i = rp0_i;}} #define cmherm_d(_A,_R) { \ vsip_length lx = _A->row_length,ly = _A->col_length;vsip_stride cAst = _A->block->cstride,cRst = _R->block->cstride;\ vsip_scalar_d *a_p_r = _A->block->R->array + cAst * _A->offset,\ *a_p_i = _A->block->I->array + cAst * _A->offset,*r_p_r = _R->block->R->array + cRst * _R->offset, *r_p_i;vsip_length i, j;\ vsip_stride stAx = cAst * _A->row_stride, stAy = cAst *_A->col_stride, stRx = cRst * _R->row_stride,stRy = cRst *_R->col_stride;\ for(i=0; i<ly; i++){\ r_p_r = _R->block->R->array + cRst * _R->offset + i * stRx;r_p_i = _R->block->I->array + cRst * _R->offset + i * stRx;\ a_p_r = _A->block->R->array + cAst * _A->offset + i * stAy;a_p_i = _A->block->I->array + cAst * _A->offset + i * stAy;\ for(j=0; j<lx; j++){*r_p_r = *a_p_r;*r_p_i = - *a_p_i;r_p_r += stRy; a_p_r += stAx;r_p_i += stRy; a_p_i += stAx;}}} #define cmconj_d( a, r) { vsip_length n_mj, n_mn; vsip_stride ast_mj, ast_mn, rst_mj, rst_mn; \ vsip_scalar_d *ap_r = (a)->block->R->array + (a)->offset * (a)->block->cstride, *rp_r = (r)->block->R->array + (r)->offset * (r)->block->cstride, \ *ap_i = (a)->block->I->array + (a)->offset * (a)->block->cstride, *rp_i = (r)->block->I->array + (r)->offset * (r)->block->cstride, \ *ap0_r = ap_r, *rp0_r = rp_r, *ap0_i = ap_i, *rp0_i = rp_i; \ if((r)->row_stride < (r)->col_stride){ n_mj = (r)->row_length; n_mn = (r)->col_length; \ rst_mj = (r)->row_stride; rst_mn = (r)->col_stride; ast_mj = (a)->row_stride; ast_mn = (a)->col_stride; \ rst_mj *= (r)->block->cstride; rst_mn *= (r)->block->cstride; ast_mj *= (a)->block->cstride; ast_mn *= (a)->block->cstride; \ } else { n_mn = (r)->row_length; n_mj = (r)->col_length; \ rst_mn = (r)->row_stride; rst_mj = (r)->col_stride; ast_mn = (a)->row_stride; ast_mj = (a)->col_stride; \ rst_mn *= (r)->block->cstride; rst_mj *= (r)->block->cstride; ast_mn *= (a)->block->cstride; ast_mj *= (a)->block->cstride; \ } while(n_mn-- > 0){ vsip_length _n = n_mj; while(_n-- >0){ \ *rp_r = *ap_r; *rp_i = - *ap_i; ap_r += ast_mj; rp_r += rst_mj; ap_i += ast_mj; rp_i += rst_mj; \ } ap0_r += ast_mn; rp0_r += rst_mn; ap_r = ap0_r; rp_r = rp0_r; ap0_i += ast_mn; rp0_i += rst_mn; ap_i = ap0_i;rp_i = rp0_i;}} #define mpermute_onceCol_d(in, p){ vsip_scalar_d *ptr,t;vsip_length ndta, n_ind; vsip_stride indta_strd, in_ind_strd; \ register vsip_index to0; register vsip_index from0; vsip_index _i,_j,*b,from,to;\ ndta = in->col_length; n_ind = in->row_length; indta_strd = in->col_stride * in->block->rstride;\ in_ind_strd = in->row_stride * in->block->rstride; ptr = in->block->array + in->offset * in->block->rstride;\ b = p->block->array + p->offset; for(_i=0; _i<n_ind; _i++){ vsip_index r_or_c = b[_i * p->stride];\ from0 = b[_i * p->stride] * in_ind_strd; to0 = _i * in_ind_strd;\ if(from0 != to0) { for(_j=0; _j<ndta; _j++){to = to0 + _j * indta_strd, from = from0 + _j * indta_strd;\ t = ptr[to]; ptr[to] = ptr[from]; ptr[from] = t; } _j=_i;\ while(_i != b[_j * p->stride]){ _j++; if(_j > n_ind) exit(-1); } b[_j * p->stride] = r_or_c;}}} #define mpermute_onceRow_d(in, p) { vsip_index _i,_j,from,to; vsip_length ndta, n_ind; \ vsip_stride indta_strd=in->row_stride * in->block->rstride,in_ind_strd=in->col_stride * in->block->rstride;\ vsip_scalar_d *ptr = in->block->array + in->offset * in->block->rstride,t;\ vsip_scalar_vi *b = p->block->array + p->offset; ndta = in->row_length; n_ind = in->col_length;\ for(_i=0; _i<n_ind; _i++){ vsip_index r_or_c = b[_i * p->stride]; \ register vsip_index from0 = b[_i * p->stride] * in_ind_strd; register vsip_index to0 = _i * in_ind_strd;\ if(from0 != to0) { for(_j=0; _j<ndta; _j++){ to = to0 + _j * indta_strd; from = from0 + _j * indta_strd;\ t = ptr[to]; ptr[to] = ptr[from]; ptr[from] = t; } _j=_i; while(_i != b[_j * p->stride])\ { _j++; if(_j > n_ind) exit(-1);}b[_j * p->stride] = r_or_c; } } } #define cmpermute_onceCol_d(in, p){\ vsip_length ndta=in->col_length, n_ind=in->row_length; vsip_stride indta_strd, in_ind_strd; vsip_index _i,_j;\ vsip_scalar_d *ptr_re = in->block->R->array + in->offset * in->block->cstride, \ *ptr_im = in->block->I->array + in->offset * in->block->cstride;\ vsip_scalar_vi *b = p->block->array + p->offset;\ indta_strd = in->col_stride * in->block->cstride; in_ind_strd = in->row_stride * in->block->cstride;\ for(_i=0; _i<n_ind; _i++){vsip_index r_or_c = b[_i * p->stride]; \ register vsip_index from0 = b[_i * p->stride] * in_ind_strd; register vsip_index to0 = _i * in_ind_strd;\ if(from0 != to0) { for(_j=0; _j<ndta; _j++){ vsip_index to = to0 + _j * indta_strd; \ vsip_index from = from0 + _j * indta_strd;vsip_scalar_d t = ptr_re[to]; ptr_re[to] = ptr_re[from];\ ptr_re[from] = t; t = ptr_im[to];ptr_im[to] = ptr_im[from]; ptr_im[from] = t;\ }_j=_i; while(_i != b[_j * p->stride]){ _j++; if(_j > n_ind) exit(-1); } b[_j * p->stride] = r_or_c; } } } #define cmpermute_onceRow_d( in, p){\ vsip_length ndta, n_ind; vsip_stride indta_strd, in_ind_strd; vsip_index _i,_j;\ vsip_scalar_d *ptr_re = in->block->R->array + in->offset * in->block->cstride, \ *ptr_im = in->block->I->array + in->offset * in->block->cstride;\ vsip_scalar_vi *b = p->block->array + p->offset; ndta = in->row_length; n_ind = in->col_length;\ indta_strd = in->row_stride * in->block->cstride; in_ind_strd = in->col_stride * in->block->cstride;\ for(_i=0; _i<n_ind; _i++){ vsip_index r_or_c = b[_i * p->stride]; \ register vsip_index from0 = b[_i * p->stride] * in_ind_strd; register vsip_index to0 = _i * in_ind_strd;\ if(from0 != to0) { for(_j=0; _j<ndta; _j++){ vsip_index to = to0 + _j * indta_strd; \ vsip_index from = from0 + _j * indta_strd;vsip_scalar_d t = ptr_re[to]; ptr_re[to] = ptr_re[from]; \ ptr_re[from] = t; t = ptr_im[to]; ptr_im[to] = ptr_im[from]; ptr_im[from] = t;\ }_j=_i; while(_i != b[_j * p->stride]){ _j++; if(_j > n_ind) exit(-1); } b[_j * p->stride] = r_or_c;}}} #define vmprod_d(a,B,r) {vsip_length nx=0,mx=0;\ vsip_scalar_d *ap=(a)->block->array+(a)->offset * (a)->block->rstride,*ap0=ap,\ *rp=(r)->block->array+(r)->offset * (r)->block->rstride, *Byp=(B)->block->array+(B)->offset * (B)->block->rstride,*Bxp = Byp;\ vsip_stride BCst = (B)->col_stride * (B)->block->rstride,BRst=(B)->row_stride * (B)->block->rstride,\ rst = (r)->stride * (r)->block->rstride; while(nx++ < (B)->row_length){*rp=0;mx=0;\ while(mx++ < (B)->col_length){ *rp += *ap * *Byp; ap += (a)->stride; Byp += BCst; }ap = ap0; Byp = (Bxp += BRst); rp += rst;}} #define mvprod_d(_A, _b, _r) {vsip_length nx=0, mx=0;\ vsip_scalar_d *bp=(_b)->block->array+(_b)->offset * (_b)->block->rstride,\ *rp=(_r)->block->array+(_r)->offset * (_r)->block->rstride, *Ayp=(_A)->block->array+(_A)->offset * (_A)->block->rstride, *Axp=Ayp;\ vsip_stride rst=(_r)->stride * (_r)->block->rstride, ARst=(_A)->row_stride * (_A)->block->rstride,\ ACst=(_A)->col_stride * (_A)->block->rstride, bst=(_b)->stride * (_b)->block->rstride;\ while(nx++ < (_A)->col_length){ *rp=0; mx=0; while(mx++ < (_A)->row_length){ *rp += *bp * *Axp; bp += bst; Axp += ARst; }\ bp=(_b)->block->array+(_b)->offset * (_b)->block->rstride; Axp=(Ayp += ACst); rp += rst; } } #define cvmprod_d(_a,_B,_r) { vsip_length nx = 0, mx = 0; \ vsip_stride cast = (_a)->block->cstride, crst = (_r)->block->cstride, cBst = (_B)->block->cstride;\ vsip_scalar_d *ap_r = (vsip_scalar_d*)((_a)->block->R->array + cast * (_a)->offset),\ *ap_i = (vsip_scalar_d*)((_a)->block->I->array + cast * (_a)->offset),\ *rp_r = (vsip_scalar_d*)((_r)->block->R->array + crst * (_r)->offset),\ *rp_i = (vsip_scalar_d*)((_r)->block->I->array + crst * (_r)->offset),\ *Byp_r = (vsip_scalar_d*)((_B)->block->R->array + cBst * (_B)->offset),\ *Byp_i = (vsip_scalar_d*)((_B)->block->I->array + cBst * (_B)->offset),\ *Bxpr = Byp_r, *Bxpi = Byp_i; vsip_stride sta = cast * (_a)->stride, str = crst * (_r)->stride, stB = cBst * (_B)->col_stride;\ while(nx++ < (_B)->row_length){ *rp_r = 0; *rp_i = 0; mx = 0;\ while(mx++ < (_B)->col_length){\ *rp_r += *ap_r * *Byp_r - *ap_i * *Byp_i; \ *rp_i += *ap_i * *Byp_r + *ap_r * *Byp_i;\ ap_r += sta; Byp_r += stB; ap_i += sta; Byp_i += stB; } \ ap_r = (vsip_scalar_d*)((_a)->block->R->array + cast * (_a)->offset); ap_i = (vsip_scalar_d*)((_a)->block->I->array + cast * (_a)->offset);\ Byp_r = (Bxpr += (cBst * (_B)->row_stride)); Byp_i = (Bxpi += (cBst * (_B)->row_stride)); rp_r += str; rp_i += str;}} #define cvmprodj_d(_a,_B,_r) { vsip_length nx = 0, mx = 0; \ vsip_stride cast = (_a)->block->cstride, crst = (_r)->block->cstride, cBst = (_B)->block->cstride;\ vsip_scalar_d *ap_r = (vsip_scalar_d*)((_a)->block->R->array + cast * (_a)->offset),\ *ap_i = (vsip_scalar_d*)((_a)->block->I->array + cast * (_a)->offset),\ *rp_r = (vsip_scalar_d*)((_r)->block->R->array + crst * (_r)->offset),\ *rp_i = (vsip_scalar_d*)((_r)->block->I->array + crst * (_r)->offset),\ *Byp_r = (vsip_scalar_d*)((_B)->block->R->array + cBst * (_B)->offset),\ *Byp_i = (vsip_scalar_d*)((_B)->block->I->array + cBst * (_B)->offset),\ *Bxpr = Byp_r, *Bxpi = Byp_i; vsip_stride sta = cast * (_a)->stride, str = crst * (_r)->stride, stB = cBst * (_B)->col_stride;\ while(nx++ < (_B)->row_length){ *rp_r = 0; *rp_i = 0; mx = 0;\ while(mx++ < (_B)->col_length){ \ *rp_r += *ap_r * *Byp_r + *ap_i * *Byp_i; \ *rp_i += *ap_i * *Byp_r - *ap_r * *Byp_i;\ ap_r += sta; Byp_r += stB; ap_i += sta; Byp_i += stB; } \ ap_r = (vsip_scalar_d*)((_a)->block->R->array + cast * (_a)->offset); ap_i = (vsip_scalar_d*)((_a)->block->I->array + cast * (_a)->offset);\ Byp_r = (Bxpr += (cBst * (_B)->row_stride)); Byp_i = (Bxpi += (cBst * (_B)->row_stride)); rp_r += str; rp_i += str;}} #define cmvprod_d(_A,_b,_r){ \ if(((_A)->block->cstride == 2) && ((_b)->block->cstride == 2) && ((_r)->block->cstride == 2)){\ vsip_length nx = 0, mx = 0; vsip_stride cbst = (_b)->block->cstride, crst = (_b)->block->cstride, cAst = (_A)->block->cstride;\ vsip_scalar_d *bp_r = (vsip_scalar_d*)((_b)->block->R->array + cbst * (_b)->offset),\ *rp_r = (vsip_scalar_d*)((_r)->block->R->array + crst * (_r)->offset),\ *Axp_r = (vsip_scalar_d*)((_A)->block->R->array + cAst * (_A)->offset),\ *Aypr = Axp_r; vsip_stride stb = cbst * (_b)->stride, str = crst * (_r)->stride, stA = cAst * (_A)->row_stride;\ vsip_scalar_d dot_r, dot_i; while(nx++ < (_A)->col_length){ mx = 0; dot_r = 0; dot_i = 0;\ while(mx++ < (_A)->row_length){ vsip_scalar_d Ar = *Axp_r, Ai = *(Axp_r + 1); vsip_scalar_d br = *bp_r, bi = *(bp_r + 1);\ dot_r += br * Ar - bi * Ai; \ dot_i += bi * Ar + br * Ai; \ bp_r += stb; Axp_r += stA; } *rp_r = dot_r; *(rp_r + 1) = dot_i;\ bp_r = (vsip_scalar_d*)((_b)->block->R->array + cbst * (_b)->offset); Axp_r = (Aypr += (cAst * (_A)->col_stride));rp_r += str;}\ } else { vsip_length nx = 0, mx = 0;\ vsip_stride cbst = (_b)->block->cstride, crst = (_r)->block->cstride, cAst = (_A)->block->cstride;\ vsip_scalar_d *bp_r = (vsip_scalar_d*)((_b)->block->R->array + cbst * (_b)->offset),\ *bp_i = (vsip_scalar_d*)((_b)->block->I->array + cbst * (_b)->offset),\ *rp_r = (vsip_scalar_d*)((_r)->block->R->array + crst * (_r)->offset),\ *rp_i = (vsip_scalar_d*)((_r)->block->I->array + crst * (_r)->offset),\ *Axp_r = (vsip_scalar_d*)((_A)->block->R->array + cAst * (_A)->offset),\ *Axp_i = (vsip_scalar_d*)((_A)->block->I->array + cAst * (_A)->offset),\ *Aypr = Axp_r, *Aypi = Axp_i; vsip_stride stb = cbst * (_b)->stride, str = crst * (_r)->stride, stA = cAst * (_A)->row_stride;\ vsip_scalar_d dot_r, dot_i; while(nx++ < (_A)->col_length){ dot_r = 0; dot_i = 0; mx = 0;\ while(mx++ < (_A)->row_length){ \ dot_r += *bp_r * *Axp_r - *bp_i * *Axp_i; \ dot_i += *bp_i * *Axp_r + *bp_r * *Axp_i;\ bp_r += stb; Axp_r += stA; bp_i += stb; Axp_i += stA; }\ *rp_r = dot_r; *rp_i = dot_i; bp_r = (vsip_scalar_d*)((_b)->block->R->array + cbst * (_b)->offset);\ bp_i = (vsip_scalar_d*)((_b)->block->I->array + cbst * (_b)->offset); Axp_r = (Aypr += (cAst * (_A)->col_stride));\ Axp_i = (Aypi += (cAst * (_A)->col_stride)); rp_r += str; rp_i += str; }}} #define cmvjprod_d(_A,_b,_r){ \ if(((_A)->block->cstride == 2) && ((_b)->block->cstride == 2) && ((_r)->block->cstride == 2)){\ vsip_length nx = 0, mx = 0; vsip_stride cbst = (_b)->block->cstride, crst = (_b)->block->cstride, cAst = (_A)->block->cstride;\ vsip_scalar_d *bp_r = (vsip_scalar_d*)((_b)->block->R->array + cbst * (_b)->offset),\ *rp_r = (vsip_scalar_d*)((_r)->block->R->array + crst * (_r)->offset),\ *Axp_r = (vsip_scalar_d*)((_A)->block->R->array + cAst * (_A)->offset),\ *Aypr = Axp_r; vsip_stride stb = cbst * (_b)->stride, str = crst * (_r)->stride, stA = cAst * (_A)->row_stride;\ vsip_scalar_d dot_r, dot_i; while(nx++ < (_A)->col_length){ mx = 0; dot_r = 0; dot_i = 0;\ while(mx++ < (_A)->row_length){ vsip_scalar_d Ar = *Axp_r, Ai = *(Axp_r + 1); vsip_scalar_d br = *bp_r, bi = *(bp_r + 1);\ dot_r += br * Ar + bi * Ai; \ dot_i += bi * Ar - br * Ai ; \ bp_r += stb; Axp_r += stA; } *rp_r = dot_r; *(rp_r + 1) = dot_i;\ bp_r = (vsip_scalar_d*)((_b)->block->R->array + cbst * (_b)->offset); Axp_r = (Aypr += (cAst * (_A)->col_stride));rp_r += str;}\ } else { vsip_length nx = 0, mx = 0;\ vsip_stride cbst = (_b)->block->cstride, crst = (_r)->block->cstride, cAst = (_A)->block->cstride;\ vsip_scalar_d *bp_r = (vsip_scalar_d*)((_b)->block->R->array + cbst * (_b)->offset),\ *bp_i = (vsip_scalar_d*)((_b)->block->I->array + cbst * (_b)->offset),\ *rp_r = (vsip_scalar_d*)((_r)->block->R->array + crst * (_r)->offset),\ *rp_i = (vsip_scalar_d*)((_r)->block->I->array + crst * (_r)->offset),\ *Axp_r = (vsip_scalar_d*)((_A)->block->R->array + cAst * (_A)->offset),\ *Axp_i = (vsip_scalar_d*)((_A)->block->I->array + cAst * (_A)->offset),\ *Aypr = Axp_r, *Aypi = Axp_i; vsip_stride stb = cbst * (_b)->stride, str = crst * (_r)->stride, stA = cAst * (_A)->row_stride;\ vsip_scalar_d dot_r, dot_i; while(nx++ < (_A)->col_length){ dot_r = 0; dot_i = 0; mx = 0;\ while(mx++ < (_A)->row_length){ \ dot_r += *bp_r * *Axp_r + *bp_i * *Axp_i; \ dot_i += *bp_i * *Axp_r - *bp_r * *Axp_i; \ bp_r += stb; Axp_r += stA; bp_i += stb; Axp_i += stA; }\ *rp_r = dot_r; *rp_i = dot_i; bp_r = (vsip_scalar_d*)((_b)->block->R->array + cbst * (_b)->offset);\ bp_i = (vsip_scalar_d*)((_b)->block->I->array + cbst * (_b)->offset); Axp_r = (Aypr += (cAst * (_A)->col_stride));\ Axp_i = (Aypi += (cAst * (_A)->col_stride)); rp_r += str; rp_i += str; }}} #define svmul_d(alpha, _b, _r) {vsip_length n = (_r)->length;\ vsip_stride bst=(_b)->stride * (_b)->block->rstride, rst = (_r)->stride * (_r)->block->rstride;\ vsip_scalar_d *bp=(_b)->block->array+(_b)->offset * (_b)->block->rstride, *rp=(_r)->block->array+(_r)->offset * (_r)->block->rstride;\ while(n-- > 0){ *rp = alpha * *bp; bp += bst; rp += rst;}} #define mtrans_d(A, R) { vsip_length lx = (A)->row_length, ly = (A)->col_length; vsip_index i, j; vsip_scalar_d tmp;\ vsip_scalar_d *a_p = (A)->block->array + (A)->offset * (A)->block->rstride, *r_p = R->block->array + R->offset * R->block->rstride;\ vsip_stride stAx = (A)->row_stride * (A)->block->rstride, stAy = (A)->col_stride * (A)->block->rstride,\ stRx = R->row_stride * R->block->rstride, stRy = R->col_stride * R->block->rstride;\ if((lx == ly) && (a_p == r_p)){ for(i=1; i<lx; i++){ for(j=0; j<i; j++){ tmp = *(a_p + j * stAy + i * stAx);\ *(a_p + j * stAy + i * stAx) = *(a_p + j * stAx + i * stAy); *(a_p + j * stAx + i * stAy) = tmp; } }\ } else { for(i=0; i<ly; i++){ r_p = R->block->array + R->offset * R->block->rstride + i * stRx;\ a_p = (A)->block->array + (A)->offset * (A)->block->rstride + i * stAy; for(j=0; j<lx; j++){ *r_p = *a_p;\ r_p += stRy; a_p += stAx; } } } } typedef struct {vsip_index i; vsip_index j;} svdCorner; typedef struct {vsip_scalar_d c; vsip_scalar_d s; vsip_scalar_d r;}givensObj_d ; static svdObj_d *svdInit_d(vsip_length, vsip_length,int,int); static void svdFinalize_d(svdObj_d*); static void svd_d(svdObj_d*,int,int); static csvdObj_d *csvdInit_d(vsip_length, vsip_length,int,int); static void csvdFinalize_d(csvdObj_d*); static void csvd_d(csvdObj_d*,int,int); static vsip_scalar_d hypot_d(vsip_scalar_d a0,vsip_scalar_d b0){ vsip_scalar_d a = (a0 < 0.0) ? -a0:a0; vsip_scalar_d b = (b0 < 0.0) ? -b0:b0; if (a == 0.0) return b; else if (b == 0.0) return a; else if (b < a) return a * (vsip_scalar_d)sqrt(1.0 + (b/a) * (b/a)); else return b * (vsip_scalar_d)sqrt(1.0 + (a/b) * (a/b)); } static vsip_vview_d *vsv_d(vsip_vview_d *v, vsip_vview_d *vs, vsip_index i) { *vs=*v; vs->offset += i * vs->stride; vs->length -= i; return vs; } static vsip_mview_d* msv_d(vsip_mview_d *B,vsip_mview_d *BS, vsip_index i,vsip_index j) { *BS = *B; BS->row_length -= j; BS->col_length -= i; BS->offset += j * BS->row_stride + i * BS->col_stride; return BS; } static vsip_mview_d* imsv_d( vsip_mview_d *B, vsip_mview_d *BS, vsip_index i1,vsip_index j1, vsip_index i2, vsip_index j2) { *BS=*B; if(j1 == 0) j1 =(B)->col_length; if(j2 == 0) j2 =(B)->row_length; BS->col_length = (j1 - i1); BS->row_length = (j2 - i2); BS->offset += i2 * B->row_stride + i1 * B->col_stride; return BS; } static vsip_vview_d *ivsv_d( vsip_vview_d *v, vsip_vview_d *vs, vsip_index i,vsip_index j) { *vs=*v; if(j==0) j=v->length; vs->offset += i * v->stride; vs->length = j-i; return vs; } static vsip_vview_d *col_sv_d(vsip_mview_d*Am,vsip_vview_d* vv,vsip_index col) { vv->block = Am->block; vv->offset = Am->offset + col * Am->row_stride; vv->stride = Am->col_stride; vv->length = Am->col_length; return vv; } static vsip_vview_d *row_sv_d(vsip_mview_d*Am,vsip_vview_d* vv,vsip_index row) { vv->block = Am->block; vv->offset = Am->offset + row * Am->col_stride; vv->stride = Am->row_stride; vv->length = Am->row_length; return vv; } static vsip_vview_d *diag_sv_d(vsip_mview_d* Am,vsip_vview_d* a, vsip_stride i) { a->block = Am->block; a->stride=Am->row_stride + Am->col_stride; if(i==0){ a->length = Am->row_length; a->offset = Am->offset; } else if (i == 1){ a->offset = Am->offset + Am->row_stride; a->length = Am->row_length - 1; } else { printf("Failed in diag_sv_d\n"); exit(0); } return a; } static vsip_cmview_d* cimsv_d( vsip_cmview_d *B, vsip_cmview_d *BS, vsip_index i1,vsip_index j1, vsip_index i2, vsip_index j2) { *BS=*B; if(j1 == 0) j1 =B->col_length; if(j2 == 0) j2 =B->row_length; BS->col_length = (j1 - i1); BS->row_length = (j2 - i2); BS->offset += i2 * B->row_stride + i1 * B->col_stride; return BS; } static vsip_cvview_d *ccol_sv_d(vsip_cmview_d*Am,vsip_cvview_d* vv,vsip_index col) { vv->block = Am->block; vv->offset = Am->offset + col * Am->row_stride; vv->stride = Am->col_stride; vv->length = Am->col_length; return vv; } static vsip_cvview_d *crow_sv_d(vsip_cmview_d*Am,vsip_cvview_d* vv,vsip_index row) { vv->block=Am->block; vv->offset = Am->offset + row * Am->col_stride; vv->stride = Am->row_stride; vv->length = Am->row_length; return vv; } static vsip_cvview_d *cdiag_sv_d(vsip_cmview_d* Am,vsip_cvview_d* a, vsip_stride i) { a->block = Am->block; a->stride=Am->row_stride + Am->col_stride; if(i==0){ a->length = Am->row_length; a->offset = Am->offset; } else if (i == 1){ a->offset = Am->offset + Am->row_stride; a->length = Am->row_length - 1; } else { printf("Failed in diag_sv_d\n"); exit(0); } return a; } static vsip_scalar_d vnorm2_d(vsip_vview_d *a) { vsip_length n = a->length; vsip_stride ast = a->stride * a->block->rstride; vsip_scalar_d *ap = (a->block->array) + a->offset * a->block->rstride,t = 0; while(n-- > 0){ t += (*ap * *ap); ap += ast; } return (vsip_scalar_d)sqrt(t); } static vsip_scalar_d mnormFro_d(vsip_mview_d *v) { vsip_length m=v->col_length,n=v->row_length; vsip_index i,j; vsip_stride rstrd=v->row_stride*v->block->rstride; vsip_stride cstrd=v->col_stride*v->block->rstride; vsip_scalar_d *vre=v->block->array+v->offset*v->block->rstride; vsip_scalar_d re=0.0; for(i=0; i<m; i++){ vsip_offset o=i*cstrd; vsip_scalar_d *rp=vre+o; for(j=0; j<n; j++){ re += *rp * *rp; rp += rstrd; } } return sqrt(re); } static void meye_d(vsip_mview_d *v) { vsip_length m=v->col_length,n=v->row_length; vsip_index i,j; vsip_stride rstrd=v->row_stride*v->block->rstride; vsip_stride cstrd=v->col_stride*v->block->rstride; vsip_scalar_d *vre=v->block->array+v->offset*v->block->rstride; for(i=0; i<m; i++){ vsip_offset o=i*cstrd; vsip_scalar_d *rp=vre+o; for(j=0; j<n; j++){ *rp = (i==j) ? 1.0:0.0; rp += rstrd; } } } /* sign function as defined in http://www.netlib.org/lapack/lawnspdf/lawn148.pdf */ static vsip_scalar_d sign_d(vsip_scalar_d a_in) { return (a_in < 0.0) ? -1.0:1.0; } static vsip_cscalar_d csign_d(vsip_cscalar_d a_in) { vsip_scalar_d re = a_in.r < 0.0 ? -a_in.r:a_in.r; vsip_scalar_d im = a_in.i < 0.0 ? -a_in.i:a_in.i; vsip_scalar_d t= (re==0.0) ? im: ((im==0.0) ? re:((re<im) ? im*sqrt(1.0 + re/im*re/im):re*sqrt(1.0+im/re*im/re))); vsip_cscalar_d retval; retval.r=0.0; retval.i = 0.0; if(t == 0.0){ retval.r = 1.0; return retval; } else if (im==0.0) { retval.r = (a_in.r < 0.0) ? -1.0:1.0; return retval; } else { retval.r = a_in.r/t; retval.i = a_in.i/t; return retval; } } static void phaseCheck_d(svdObj_d *svd) { vsip_scalar_d *fptr, *dptr; vsip_mview_d *L = svd->L; vsip_vview_d *d = svd->d; vsip_vview_d *f = svd->f; vsip_scalar_d eps0 = svd->eps0; vsip_length nd=d->length; vsip_length nf=f->length; vsip_index i; vsip_scalar_d ps; vsip_scalar_d m; vsip_vview_d *l = &svd->ls_one; vsip_stride fstrd=f->stride * d->block->rstride; vsip_stride dstrd=d->stride * d->block->rstride; dptr=d->block->array +d->offset * d->block->rstride; fptr=f->block->array + f->offset * f->block->rstride; for(i=0; i<nd; i++){ ps=*dptr; m = (ps<0) ? -ps:ps; ps=sign_d(ps); if(m > eps0){ col_sv_d(L,l,i); { vsip_scalar_d *p = l->block->array + l->offset * l->block->rstride; vsip_stride std = l->stride * l->block->rstride; vsip_length n = l->length * std; vsip_index k; for(k=0; k<n; k+=std) p[k] *= ps; } *dptr=m; if (i < nf) *fptr *= ps; } else { *dptr = 0.0; } dptr+=dstrd;fptr+=fstrd; } dptr=d->block->array +d->offset * d->block->rstride; fptr=f->block->array + f->offset * f->block->rstride; for(i=0; i<nf; i++){ vsip_scalar_f f_i= fabs(*fptr); m = (*dptr + *(dptr+dstrd)) * eps0; if (f_i < m) *fptr = 0.0; dptr+=dstrd;fptr+=fstrd; } } static void phaseCheck2_d(svdObj_d *svd) /* save U */ { vsip_scalar_d *fptr, *dptr; vsip_mview_d *L = svd->L; vsip_vview_d *d = svd->d; vsip_vview_d *f = svd->f; vsip_scalar_d eps0 = svd->eps0; vsip_length nd=d->length; vsip_length nf=f->length; vsip_index i; vsip_scalar_d ps; vsip_scalar_d m; vsip_vview_d *l = &svd->ls_one; vsip_stride fstrd=f->stride * d->block->rstride; vsip_stride dstrd=d->stride * d->block->rstride; dptr=d->block->array +d->offset * d->block->rstride; fptr=f->block->array + f->offset * f->block->rstride; for(i=0; i<nd; i++){ ps=*dptr; m = (ps<0) ? -ps:ps; ps=sign_d(ps); if(m > eps0){ col_sv_d(L,l,i); { vsip_scalar_d *p = l->block->array + l->offset * l->block->rstride; vsip_stride std = l->stride * l->block->rstride; vsip_length n = l->length * std; vsip_index k; for(k=0; k<n; k+=std) p[k] *= ps; } *dptr=m; if (i < nf) *fptr *= ps; } else { *dptr = 0.0; } dptr+=dstrd;fptr+=fstrd; } dptr=d->block->array +d->offset * d->block->rstride; fptr=f->block->array + f->offset * f->block->rstride; for(i=0; i<nf; i++){ vsip_scalar_f f_i= fabs(*fptr); m = (*dptr + *(dptr+dstrd)) * eps0; if (f_i < m) *fptr = 0.0; dptr+=dstrd;fptr+=fstrd; } } static void phaseCheck1_d(svdObj_d *svd) /* save V */ { vsip_scalar_d *fptr, *dptr; vsip_vview_d *d = svd->d; vsip_vview_d *f = svd->f; vsip_scalar_d eps0 = svd->eps0; vsip_length nd=d->length; vsip_length nf=f->length; vsip_index i; vsip_scalar_d ps; vsip_scalar_d m; vsip_stride fstrd=f->stride * d->block->rstride; vsip_stride dstrd=d->stride * d->block->rstride; dptr=d->block->array +d->offset * d->block->rstride; fptr=f->block->array + f->offset * f->block->rstride; for(i=0; i<nd; i++){ ps=*dptr; m = (ps<0) ? -ps:ps; ps=sign_d(ps); if(m > eps0){ *dptr=m; if (i < nf) *fptr *= ps; } else { *dptr = 0.0; } dptr+=dstrd;fptr+=fstrd; } dptr=d->block->array +d->offset * d->block->rstride; fptr=f->block->array + f->offset * f->block->rstride; for(i=0; i<nf; i++){ vsip_scalar_f f_i= fabs(*fptr); m = (*dptr + *(dptr+dstrd)) * eps0; if (f_i < m) *fptr = 0.0; dptr+=dstrd;fptr+=fstrd; } } static void phaseCheck0_d(svdObj_d *svd) { vsip_scalar_d *fptr, *dptr; vsip_vview_d *d = svd->d; vsip_vview_d *f = svd->f; vsip_scalar_d eps0 = svd->eps0; vsip_length nd=d->length; vsip_length nf=f->length; vsip_index i; vsip_scalar_d ps; vsip_scalar_d m; vsip_stride fstrd=f->stride * d->block->rstride; vsip_stride dstrd=d->stride * d->block->rstride; dptr=d->block->array +d->offset * d->block->rstride; fptr=f->block->array + f->offset * f->block->rstride; for(i=0; i<nd; i++){ ps=*dptr; m = (ps<0) ? -ps:ps; ps=sign_d(ps); if(m > eps0){ *dptr=m; if (i < nf) *fptr *= ps; } else { *dptr = 0.0; } dptr+=dstrd;fptr+=fstrd; } dptr=d->block->array +d->offset * d->block->rstride; fptr=f->block->array + f->offset * f->block->rstride; for(i=0; i<nf; i++){ vsip_scalar_f f_i= fabs(*fptr); m = (*dptr + *(dptr+dstrd)) * eps0; if (f_i < m) *fptr = 0.0; dptr+=dstrd;fptr+=fstrd; } } static void biDiagPhaseToZero_d( svdObj_d *svd) { vsip_vview_d *x=&svd->bs,*v=svd->d; diag_sv_d(&svd->B,x,0); vcopy_d(x,v); diag_sv_d(&svd->B,x,1); v=svd->f; vcopy_d(x,v); phaseCheck_d(svd); } static void biDiagPhaseToZero2_d( svdObj_d *svd) { vsip_vview_d *x=&svd->bs,*v=svd->d; diag_sv_d(&svd->B,x,0); vcopy_d(x,v); diag_sv_d(&svd->B,x,1); v=svd->f; vcopy_d(x,v); phaseCheck2_d(svd); } static void biDiagPhaseToZero1_d( svdObj_d *svd) { vsip_vview_d *x=&svd->bs,*v=svd->d; diag_sv_d(&svd->B,x,0); vcopy_d(x,v); diag_sv_d(&svd->B,x,1); v=svd->f; vcopy_d(x,v); phaseCheck1_d(svd); } static void biDiagPhaseToZero0_d( svdObj_d *svd) { vsip_vview_d *x=&svd->bs,*v=svd->d; diag_sv_d(&svd->B,x,0); vcopy_d(x,v); diag_sv_d(&svd->B,x,1); v=svd->f; vcopy_d(x,v); phaseCheck0_d(svd); } #define opu_d(A,x,y) {\ vsip_length m = (A)->col_length,n = (A)->row_length;vsip_index i,ii,j,jj;\ vsip_scalar_d *ap=(A)->block->array + (A)->offset * (A)->block->rstride, \ *xp=x->block->array + x->offset * x->block->rstride,*yp=y->block->array + y->offset * y->block->rstride;\ vsip_stride xstd = x->block->rstride * x->stride,ystd = y->block->rstride * y->stride,\ r_std = (A)->block->rstride * (A)->row_stride,c_std = (A)->block->rstride * (A)->col_stride;\ m *= c_std; n *= r_std;\ for(i=0, ii=0; i<m; i+=c_std, ii+=xstd){vsip_scalar_d c = xp[ii], *app=ap+i;\ for(j=0, jj=0; j<n; j+=r_std, jj+=ystd){ app[j] = app[j] + c * yp[jj];}}} static void houseProd_d(vsip_vview_d *v, vsip_mview_d *A,vsip_vview_d *w) { vsip_scalar_d *vptr = v->block->array + v->offset*v->block->rstride; vsip_stride vstd = v->stride*v->block->rstride; vsip_scalar_d beta = 0.0; vsip_length n=v->length; while(n-- > 0){ beta += *vptr * *vptr;vptr+=vstd;} beta=2.0/beta; w->length = A->row_length; vmprod_d(v,A,w) svmul_d(-beta,w,w) opu_d(A,v,w) } static void prodHouse_d(vsip_mview_d *A, vsip_vview_d *v, vsip_vview_d *w) { vsip_scalar_d *vptr = v->block->array + v->offset*v->block->rstride; vsip_stride vstd = v->stride*v->block->rstride; vsip_scalar_d beta = 0.0; vsip_length n=v->length; while(n-- > 0){ beta += *vptr * *vptr;vptr+=vstd;} beta=2.0/beta; w->length = A->col_length; mvprod_d(A,v,w) svmul_d(-beta,w,w) opu_d(A,w,v) } static vsip_vview_d *houseVector_d(vsip_vview_d* x) { vsip_scalar_d *x0=x->block->array + x->offset * x->block->rstride; vsip_scalar_d nrm=vnorm2_d(x); vsip_scalar_d t = *x0; vsip_scalar_d s = t + sign_d(t) * nrm; *x0=s; nrm = vnorm2_d(x); if (nrm == 0.0) *x0=1.0; else { vsip_stride std = x->stride * x->block->rstride; vsip_length n = x->length * std; vsip_index k; for(k=0; k<n; k+=std) x0[k] /= nrm; } return x; } static void VHmatExtract_d(svdObj_d *svd) { vsip_mview_d* B = &svd->B; vsip_index i,j; vsip_length n = B->row_length; vsip_mview_d *Bs=&svd->Bs; vsip_mview_d *V=svd->R; vsip_mview_d *Vs=&svd->Rs; vsip_vview_d *v=&svd->bs; vsip_scalar_d t; vsip_scalar_d *vptr; if(n < 3) return; for(i=n-3; i>0; i--){ j=i+1; row_sv_d(msv_d(B,Bs,i,j),v,0); vptr=v->block->array+v->offset*v->block->rstride; t=*vptr; *vptr = 1.0; prodHouse_d(msv_d(V,Vs,j,j),v,svd->w); *vptr = t; } row_sv_d(msv_d(B,Bs,0,1),v,0); vptr=v->block->array+v->offset*v->block->rstride; t=*vptr; *vptr = 1.0; prodHouse_d(msv_d(V,Vs,1,1),v,svd->w); *vptr = t; } static void UmatExtract_d(svdObj_d *svd) { vsip_mview_d* B=&svd->B; vsip_mview_d *U=svd->L; vsip_index i; vsip_length m = B->col_length; vsip_length n = B->row_length; vsip_mview_d *Bs=&svd->Bs; vsip_mview_d *Us=&svd->Ls; vsip_vview_d *v=&svd->bs; vsip_scalar_d t; vsip_scalar_d *vptr; if (m > n){ i=n-1; col_sv_d(msv_d(B,Bs,i,i),v,0); vptr=v->block->array+v->offset*v->block->rstride; t=*vptr; *vptr = 1.0; houseProd_d(v,msv_d(U,Us,i,i),svd->w); *vptr = t; } for(i=n-2; i>0; i--){ col_sv_d(msv_d(B,Bs,i,i),v,0); vptr=v->block->array+v->offset*v->block->rstride; t=*vptr; *vptr = 1.0; houseProd_d(v,msv_d(U,Us,i,i),svd->w); *vptr = t; } col_sv_d(msv_d(B,Bs,0,0),v,0); vptr=v->block->array+v->offset*v->block->rstride; t=*vptr; *vptr = 1.0; houseProd_d(v,msv_d(U,Us,0,0),svd->w); *vptr= t; } static void bidiag_d(svdObj_d *svd) { vsip_mview_d *B = &svd->B; vsip_mview_d *Bs = &svd->Bs; vsip_length m = B->col_length; vsip_length n = B->row_length; vsip_vview_d *x=col_sv_d(B,&svd->bs,0); vsip_vview_d *v=svd->t; vsip_vview_d *vs = &svd->ts; vsip_index i,j; for(i=0; i<n-1; i++){ v->length=m-i; col_sv_d(msv_d(B,Bs,i,i),x,0); vcopy_d(x,v);/*0*/ houseVector_d(v); scaleV(v) houseProd_d(v,Bs,svd->w); vsv_d(v,vs,1);vsv_d(x,x,1); vcopy_d(vs,x);/*1*/ if(i < n-2){ j = i+1; v->length = n-j; row_sv_d(msv_d(B,Bs,i,j),x,0); vcopy_d(x,v);/*2*/ houseVector_d(v); scaleV(v) prodHouse_d(Bs,v,svd->w); vsv_d(v,vs,1);vsv_d(x,x,1); vcopy_d(vs,x);/*3*/ } } if(m > n){ i=n-1; v->length=m-i; col_sv_d(msv_d(B,Bs,i,i),x,0); vcopy_d(x,v); /*4*/ houseVector_d(v); scaleV(v) houseProd_d(v,Bs,svd->w); vsv_d(v,vs,1);vsv_d(x,x,1); vcopy_d(vs,x);/*5*/ } } static void gtProd_d(vsip_index i, vsip_index j, vsip_scalar_d c,vsip_scalar_d s, svdObj_d* svd) { vsip_mview_d* R = &svd->Rs; vsip_vview_d *a1= row_sv_d(R,&svd->rs_one, i); vsip_vview_d *a2= row_sv_d(R,&svd->rs_two, j); vsip_index k; vsip_scalar_d *t1 = a1->block->array + (a1->offset) * a1->block->rstride; vsip_scalar_d *t2 = a2->block->array + (a2->offset) * a2->block->rstride; vsip_stride std = a1->stride * a1->block->rstride; vsip_length n = a1->length * std; for(k=0; k<n; k+=std){ register vsip_scalar_d b1 = t1[k]; register vsip_scalar_d b2 = t2[k]; t1[k] = c * b1 + s * b2; t2[k] = c * b2 - s * b1; } } static void prodG_d(svdObj_d* svd,vsip_index i, vsip_index j,vsip_scalar_d c, vsip_scalar_d s) { vsip_mview_d* L = &svd->Ls; vsip_vview_d *a1= col_sv_d(L,&svd->ls_one,i); vsip_vview_d *a2= col_sv_d(L,&svd->ls_two,j); vsip_index k; vsip_scalar_d *t1 = a1->block->array + (a1->offset) * a1->block->rstride; vsip_scalar_d *t2 = a2->block->array + (a2->offset) * a2->block->rstride; vsip_stride std = a1->stride * a1->block->rstride; vsip_length n = a1->length * std; for(k=0; k<n; k+=std){ register vsip_scalar_d b1 = t1[k]; register vsip_scalar_d b2 = t2[k]; t1[k] = c * b1 + s * b2; t2[k] = c * b2 - s * b1; } } static givensObj_d givensCoef_d(vsip_scalar_d x1, vsip_scalar_d x2) { givensObj_d retval; vsip_scalar_d t = hypot_d(x1,x2); if (x2 == 0.0 ){ retval.c=1.0;retval.s=0.0;retval.r=x1; } else if (x1 == 0.0 || t == 0.0) { retval.c=0.0;retval.s=sign_d(x2);retval.r=t; }else{ vsip_scalar_d sn = sign_d(x1); retval.c=((x1 < 0.0) ? -x1:x1)/t;retval.s=sn*x2/t; retval.r=sn*t; } return retval; } static void zeroCol_d(svdObj_d *svd) { vsip_vview_d *d=&svd->ds; vsip_vview_d *f=&svd->fs; vsip_length n = f->length; givensObj_d g; vsip_scalar_d xd,xf,t; vsip_index i,j,k; if (n == 1){ xd=*(d->block->array + d->offset * d->block->rstride); xf=*(f->block->array + f->offset * f->block->rstride); g=givensCoef_d(xd,xf); *(d->block->array + d->offset * d->block->rstride)=g.r; *(f->block->array + f->offset * f->block->rstride)=0.0; gtProd_d(0,1,g.c,g.s,svd); }else if (n == 2){ xd=VI_VGET_F(d,1); xf=VI_VGET_F(f,1); g=givensCoef_d(xd,xf); *(d->block->array + (d->offset+1) * d->block->rstride)=g.r; *(f->block->array + (f->offset+1) * f->block->rstride)=0.0; xf=VI_VGET_F(f,0); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset) * f->block->rstride)=xf; gtProd_d(1,2,g.c,g.s,svd); xd=VI_VGET_F(d,0); g=givensCoef_d(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; gtProd_d(0,2,g.c,g.s,svd); }else{ i=n-1; j=i-1; k=i; xd=*(d->block->array + (d->offset+i) * d->block->rstride); xf=*(f->block->array + (f->offset+i) * f->block->rstride); g=givensCoef_d(xd,xf); xf=*(f->block->array + (f->offset+j) * f->block->rstride); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; *(f->block->array + (f->offset+i) * f->block->rstride)=0.0; t=-xf*g.s; xf*=g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; gtProd_d(i,k+1,g.c,g.s,svd); while (i > 1){ i = j; j = i-1; xd=*(d->block->array + (d->offset+i) * d->block->rstride); g=givensCoef_d(xd,t); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; xf=*(f->block->array + (f->offset+j) * f->block->rstride); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; gtProd_d(i,k+1,g.c,g.s,svd); } xd=*(d->block->array + d->offset * d->block->rstride); g=givensCoef_d(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; gtProd_d(0,k+1,g.c,g.s,svd); } } static void zeroRow_d(svdObj_d *svd) { vsip_vview_d *d = &svd->ds; vsip_vview_d *f = &svd->fs; vsip_scalar_d *dptr=d->block->array+d->offset*d->block->rstride; vsip_scalar_d *fptr=f->block->array + f->offset*d->block->rstride; vsip_stride dstd=d->stride*d->block->rstride; vsip_stride fstd=f->stride*f->block->rstride; vsip_length n = d->length; givensObj_d g; vsip_scalar_d xd,xf,t; vsip_index i; xd=*dptr; xf=*fptr; g=givensCoef_d(xd,xf); if (n == 1){ *dptr=g.r; *fptr=0.0; prodG_d(svd,n,0,g.c,g.s); }else{ *dptr=g.r; *fptr=0.0; xf=*(fptr+fstd); t= -xf * g.s; xf *= g.c; *(fptr+fstd)=xf; prodG_d(svd,1,0,g.c,g.s); for(i=1; i<n-1; i++){ xd=*(dptr+dstd*i); g=givensCoef_d(xd,t); prodG_d(svd,i+1,0,g.c,g.s); *(dptr+dstd*i)=g.r; xf=*(fptr+fstd*(i+1)); t=-xf * g.s; xf *= g.c; *(fptr+fstd*(i+1))=xf; } xd=*(dptr+dstd*(n-1)); g=givensCoef_d(xd,t); *(dptr+dstd*(n-1))=g.r; prodG_d(svd,n,0,g.c,g.s); } } static void zeroCol2_d(svdObj_d *svd) /* save U */ { vsip_vview_d *d=&svd->ds; vsip_vview_d *f=&svd->fs; vsip_length n = f->length; givensObj_d g; vsip_scalar_d xd,xf,t; vsip_index i,j,k; if (n == 1){ xd=*(d->block->array + d->offset * d->block->rstride); xf=*(f->block->array + f->offset * f->block->rstride); g=givensCoef_d(xd,xf); *(d->block->array + d->offset * d->block->rstride)=g.r; *(f->block->array + f->offset * f->block->rstride)=0.0; }else if (n == 2){ xd=VI_VGET_F(d,1); xf=VI_VGET_F(f,1); g=givensCoef_d(xd,xf); *(d->block->array + (d->offset+1) * d->block->rstride)=g.r; *(f->block->array + (f->offset+1) * f->block->rstride)=0.0; xf=VI_VGET_F(f,0); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset) * f->block->rstride)=xf; xd=VI_VGET_F(d,0); g=givensCoef_d(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; }else{ i=n-1; j=i-1; k=i; xd=*(d->block->array + (d->offset+i) * d->block->rstride); xf=*(f->block->array + (f->offset+i) * f->block->rstride); g=givensCoef_d(xd,xf); xf=*(f->block->array + (f->offset+j) * f->block->rstride); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; *(f->block->array + (f->offset+i) * f->block->rstride)=0.0; t=-xf*g.s; xf*=g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; while (i > 1){ i = j; j = i-1; xd=*(d->block->array + (d->offset+i) * d->block->rstride); g=givensCoef_d(xd,t); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; xf=*(f->block->array + (f->offset+j) * f->block->rstride); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; gtProd_d(i,k+1,g.c,g.s,svd); } xd=*(d->block->array + d->offset * d->block->rstride); g=givensCoef_d(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; } } static void zeroRow2_d(svdObj_d *svd) /* save U */ { vsip_vview_d *d = &svd->ds; vsip_vview_d *f = &svd->fs; vsip_scalar_d *dptr=d->block->array+d->offset*d->block->rstride; vsip_scalar_d *fptr=f->block->array + f->offset*d->block->rstride; vsip_stride dstd=d->stride*d->block->rstride; vsip_stride fstd=f->stride*f->block->rstride; vsip_length n = d->length; givensObj_d g; vsip_scalar_d xd,xf,t; vsip_index i; xd=*dptr; xf=*fptr; g=givensCoef_d(xd,xf); if (n == 1){ *dptr=g.r; *fptr=0.0; prodG_d(svd,n,0,g.c,g.s); }else{ *dptr=g.r; *fptr=0.0; xf=*(fptr+fstd); t= -xf * g.s; xf *= g.c; *(fptr+fstd)=xf; prodG_d(svd,1,0,g.c,g.s); for(i=1; i<n-1; i++){ xd=*(dptr+dstd*i); g=givensCoef_d(xd,t); prodG_d(svd,i+1,0,g.c,g.s); *(dptr+dstd*i)=g.r; xf=*(fptr+fstd*(i+1)); t=-xf * g.s; xf *= g.c; *(fptr+fstd*(i+1))=xf; } xd=*(dptr+dstd*(n-1)); g=givensCoef_d(xd,t); *(dptr+dstd*(n-1))=g.r; prodG_d(svd,n,0,g.c,g.s); } } static void zeroCol1_d(svdObj_d *svd) /* save V */ { vsip_vview_d *d=&svd->ds; vsip_vview_d *f=&svd->fs; vsip_length n = f->length; givensObj_d g; vsip_scalar_d xd,xf,t; vsip_index i,j,k; if (n == 1){ xd=*(d->block->array + d->offset * d->block->rstride); xf=*(f->block->array + f->offset * f->block->rstride); g=givensCoef_d(xd,xf); *(d->block->array + d->offset * d->block->rstride)=g.r; *(f->block->array + f->offset * f->block->rstride)=0.0; gtProd_d(0,1,g.c,g.s,svd); }else if (n == 2){ xd=VI_VGET_F(d,1); xf=VI_VGET_F(f,1); g=givensCoef_d(xd,xf); *(d->block->array + (d->offset+1) * d->block->rstride)=g.r; *(f->block->array + (f->offset+1) * f->block->rstride)=0.0; xf=VI_VGET_F(f,0); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset) * f->block->rstride)=xf; gtProd_d(1,2,g.c,g.s,svd); xd=VI_VGET_F(d,0); g=givensCoef_d(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; gtProd_d(0,2,g.c,g.s,svd); }else{ i=n-1; j=i-1; k=i; xd=*(d->block->array + (d->offset+i) * d->block->rstride); xf=*(f->block->array + (f->offset+i) * f->block->rstride); g=givensCoef_d(xd,xf); xf=*(f->block->array + (f->offset+j) * f->block->rstride); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; *(f->block->array + (f->offset+i) * f->block->rstride)=0.0; t=-xf*g.s; xf*=g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; gtProd_d(i,k+1,g.c,g.s,svd); while (i > 1){ i = j; j = i-1; xd=*(d->block->array + (d->offset+i) * d->block->rstride); g=givensCoef_d(xd,t); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; xf=*(f->block->array + (f->offset+j) * f->block->rstride); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; gtProd_d(i,k+1,g.c,g.s,svd); } xd=*(d->block->array + d->offset * d->block->rstride); g=givensCoef_d(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; gtProd_d(0,k+1,g.c,g.s,svd); } } static void zeroRow1_d(svdObj_d *svd) /* save V */ { vsip_vview_d *d = &svd->ds; vsip_vview_d *f = &svd->fs; vsip_scalar_d *dptr=d->block->array+d->offset*d->block->rstride; vsip_scalar_d *fptr=f->block->array + f->offset*d->block->rstride; vsip_stride dstd=d->stride*d->block->rstride; vsip_stride fstd=f->stride*f->block->rstride; vsip_length n = d->length; givensObj_d g; vsip_scalar_d xd,xf,t; vsip_index i; xd=*dptr; xf=*fptr; g=givensCoef_d(xd,xf); if (n == 1){ *dptr=g.r; *fptr=0.0; }else{ *dptr=g.r; *fptr=0.0; xf=*(fptr+fstd); t= -xf * g.s; xf *= g.c; *(fptr+fstd)=xf; for(i=1; i<n-1; i++){ xd=*(dptr+dstd*i); g=givensCoef_d(xd,t); *(dptr+dstd*i)=g.r; xf=*(fptr+fstd*(i+1)); t=-xf * g.s; xf *= g.c; *(fptr+fstd*(i+1))=xf; } xd=*(dptr+dstd*(n-1)); g=givensCoef_d(xd,t); *(dptr+dstd*(n-1))=g.r; } } static void zeroCol0_d(svdObj_d *svd) { vsip_vview_d *d=&svd->ds; vsip_vview_d *f=&svd->fs; vsip_length n = f->length; givensObj_d g; vsip_scalar_d xd,xf,t; vsip_index i,j; if (n == 1){ xd=*(d->block->array + d->offset * d->block->rstride); xf=*(f->block->array + f->offset * f->block->rstride); g=givensCoef_d(xd,xf); *(d->block->array + d->offset * d->block->rstride)=g.r; *(f->block->array + f->offset * f->block->rstride)=0.0; }else if (n == 2){ xd=VI_VGET_F(d,1); xf=VI_VGET_F(f,1); g=givensCoef_d(xd,xf); *(d->block->array + (d->offset+1) * d->block->rstride)=g.r; *(f->block->array + (f->offset+1) * f->block->rstride)=0.0; xf=VI_VGET_F(f,0); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset) * f->block->rstride)=xf; xd=VI_VGET_F(d,0); g=givensCoef_d(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; }else{ i=n-1; j=i-1; xd=*(d->block->array + (d->offset+i) * d->block->rstride); xf=*(f->block->array + (f->offset+i) * f->block->rstride); g=givensCoef_d(xd,xf); xf=*(f->block->array + (f->offset+j) * f->block->rstride); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; *(f->block->array + (f->offset+i) * f->block->rstride)=0.0; t=-xf*g.s; xf*=g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; while (i > 1){ i = j; j = i-1; xd=*(d->block->array + (d->offset+i) * d->block->rstride); g=givensCoef_d(xd,t); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; xf=*(f->block->array + (f->offset+j) * f->block->rstride); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; } xd=*(d->block->array + d->offset * d->block->rstride); g=givensCoef_d(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; } } static void zeroRow0_d(svdObj_d *svd) { vsip_vview_d *d = &svd->ds; vsip_vview_d *f = &svd->fs; vsip_scalar_d *dptr=d->block->array+d->offset*d->block->rstride; vsip_scalar_d *fptr=f->block->array + f->offset*d->block->rstride; vsip_stride dstd=d->stride*d->block->rstride; vsip_stride fstd=f->stride*f->block->rstride; vsip_length n = d->length; givensObj_d g; vsip_scalar_d xd,xf,t; vsip_index i; xd=*dptr; xf=*fptr; g=givensCoef_d(xd,xf); if (n == 1){ *dptr=g.r; *fptr=0.0; }else{ *dptr=g.r; *fptr=0.0; xf=*(fptr+fstd); t= -xf * g.s; xf *= g.c; *(fptr+fstd)=xf; for(i=1; i<n-1; i++){ xd=*(dptr+dstd*i); g=givensCoef_d(xd,t); *(dptr+dstd*i)=g.r; xf=*(fptr+fstd*(i+1)); t=-xf * g.s; xf *= g.c; *(fptr+fstd*(i+1))=xf; } xd=*(dptr+dstd*(n-1)); g=givensCoef_d(xd,t); *(dptr+dstd*(n-1))=g.r; } } static vsip_scalar_d svdMu_d(vsip_scalar_d d2,vsip_scalar_d f1,vsip_scalar_d d3,vsip_scalar_d* f2, vsip_scalar_d eps0) { vsip_scalar_d mu; vsip_scalar_d cu=d2 * d2 + f1 * f1; vsip_scalar_d cl=d3 * d3 + *f2 * *f2; vsip_scalar_d cd = d2 * *f2; vsip_scalar_d T = (cu + cl); vsip_scalar_d D = (cu * cl - cd * cd)/(T*T); vsip_scalar_d root = T * (vsip_scalar_d) sqrt(1.0 - ((4 * D)>1.0 ? 1.0:4*D)); vsip_scalar_d lambda1 = (T + root)/(2.); vsip_scalar_d lambda2 = (T - root)/(2.); vsip_scalar_d c1=lambda1-cl,c2=lambda2-cl; c1=(c1<0) ? -c1:c1; c2=(c2<0) ? -c2:c2; if(root == 0.0) if(fabs(*f2) < (d2 + d3) * eps0) *f2=0.0; if(c1 < c2) mu = lambda1; else mu = lambda2; return mu; } static vsip_index zeroFind_d(vsip_vview_d* d, vsip_scalar_d eps0) { vsip_scalar_d *dptr=d->block->array + d->offset*d->block->rstride; vsip_stride dstrd=d->stride*d->block->rstride; vsip_index j = d->length; vsip_scalar_d xd=*(dptr+(j-1)*dstrd); while(xd > eps0){ if (j > 1){ j -= 1; xd=*(dptr+(j-1)*dstrd); }else if(j==1) return 0; } *(dptr+(j-1)*dstrd)=0.0; return j; } static svdCorner svdCorners_d(vsip_vview_d* f) { svdCorner crnr; vsip_scalar_d *fptr=f->block->array + f->offset*f->block->rstride; vsip_stride fstrd=f->stride*f->block->rstride; vsip_index j=f->length-1; vsip_index i; while((j > 0) && *(fptr+j*fstrd) == 0.0) j-=1; if(j == 0 && *fptr == 0.0){ crnr.i=0; crnr.j=0; } else { i = j; while((i > 0) && *(fptr+i*fstrd) != 0.0) i -= 1; if(i==0 && *fptr == 0.0){ crnr.i = 1; crnr.j = j+2; } else if(i == 0 && *fptr != 0.0){ crnr.i = 0; crnr.j= j+2; }else{ crnr.i = i+1; crnr.j = j+2; } } /* index and length of f != 0 */ return crnr; } static void svdStep_d(svdObj_d *svd) { vsip_vview_d *d = &svd->ds; vsip_vview_d *f = &svd->fs; givensObj_d g; vsip_length n = d->length; vsip_scalar_d mu=0.0, x1=0.0, x2=0.0; vsip_scalar_d t=0.0; vsip_index i,j,k; vsip_scalar_d d2=0.0,f1=0.0,d3=0.0,f2=0.0; vsip_scalar_d *fptr,*dptr; vsip_stride fstd=f->stride*f->block->rstride, dstd=d->stride*d->block->rstride; dptr=d->block->array+d->offset*d->block->rstride; fptr=f->block->array+f->offset*f->block->rstride; if(n >= 3){ d2=*(dptr+dstd*(n-2));f1= *(fptr+fstd*(n-3));d3 = *(dptr+dstd*(n-1));f2= *(fptr+fstd*(n-2)); } else if(n == 2){ d2=*dptr; d3=*(dptr+dstd); f1=0; f2=*fptr; } else { printf("should not be here (see svdStep_d)\n"); exit(-1); } mu = svdMu_d(d2,f1,d3,&f2,svd->eps0); if(f2 == 0.0) *(fptr+fstd*(n-2)) = 0.0; x1=*dptr; x2 = x1 * *fptr; x1 *= x1; x1 -= mu; g=givensCoef_d(x1,x2); x1=*dptr;x2=*fptr; *fptr=g.c*x2-g.s*x1; *dptr=g.c*x1+g.s*x2; t=*(dptr+dstd); *(dptr+dstd) *= g.c; t*=g.s; gtProd_d(0,1,g.c,g.s,svd); for(i=0; i<n-2; i++){ j=i+1; k=i+2; g = givensCoef_d(*(dptr+i*dstd),t); *(dptr+i*dstd)=g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t= x1 - x2; x1=*(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s ; *(f->block->array+(i*f->stride+f->offset)*f->block->rstride) = x1+x2; *(d->block->array+(j*d->stride+d->offset)*d->block->rstride) = t; x1=*(fptr+j*fstd); t=g.s * x1; *(fptr+j*fstd)=x1*g.c; prodG_d(svd,i, j, g.c, g.s); g=givensCoef_d(*(fptr+i*fstd),t); *(fptr+i*fstd)=g.r; x1=*(dptr+j*dstd); x2=*(fptr+j*fstd); *(dptr+j*dstd)=g.c * x1 + g.s * x2; *(fptr+j*fstd)=g.c * x2 - g.s * x1; x1=*(dptr+k*dstd); t=g.s * x1; *(dptr+k*dstd)=x1*g.c; gtProd_d(j,k, g.c, g.s,svd); } i=n-2; j=n-1; g = givensCoef_d(*(dptr+i*dstd),t); *(d->block->array+(i*d->stride+d->offset)*d->block->rstride) = g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t=x1 - x2; x1 = *(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s; *(f->block->array+(i*f->stride+f->offset)*f->block->rstride) = x1+x2; *(d->block->array+(j*d->stride+d->offset)*d->block->rstride) = t; prodG_d(svd,i, j, g.c, g.s); } static void svdStep2_d(svdObj_d *svd) /* save U */ { vsip_vview_d *d = &svd->ds; vsip_vview_d *f = &svd->fs; givensObj_d g; vsip_length n = d->length; vsip_scalar_d mu=0.0, x1=0.0, x2=0.0; vsip_scalar_d t=0.0; vsip_index i,j,k; vsip_scalar_d d2=0.0,f1=0.0,d3=0.0,f2=0.0; vsip_scalar_d *fptr,*dptr; vsip_stride fstd=f->stride*f->block->rstride, dstd=d->stride*d->block->rstride; dptr=d->block->array+d->offset*d->block->rstride; fptr=f->block->array+f->offset*f->block->rstride; if(n >= 3){ d2=*(dptr+dstd*(n-2));f1= *(fptr+fstd*(n-3));d3 = *(dptr+dstd*(n-1));f2= *(fptr+fstd*(n-2)); } else if(n == 2){ d2=*dptr; d3=*(dptr+dstd); f1=0; f2=*fptr; } else { printf("should not be here (see svdStep_d)\n"); exit(-1); } mu = svdMu_d(d2,f1,d3,&f2,svd->eps0); if(f2 == 0.0) *(fptr+fstd*(n-2)) = 0.0; x1=*dptr; x2 = x1 * *fptr; x1 *= x1; x1 -= mu; g=givensCoef_d(x1,x2); x1=*dptr;x2=*fptr; *fptr=g.c*x2-g.s*x1; *dptr=g.c*x1+g.s*x2; t=*(dptr+dstd); *(dptr+dstd) *= g.c; t*=g.s; for(i=0; i<n-2; i++){ j=i+1; k=i+2; g = givensCoef_d(*(dptr+i*dstd),t); *(dptr+i*dstd)=g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t= x1 - x2; x1=*(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s ; *(f->block->array+(i*f->stride+f->offset)*f->block->rstride) = x1+x2; *(d->block->array+(j*d->stride+d->offset)*d->block->rstride) = t; x1=*(fptr+j*fstd); t=g.s * x1; *(fptr+j*fstd)=x1*g.c; prodG_d(svd,i, j, g.c, g.s); g=givensCoef_d(*(fptr+i*fstd),t); *(fptr+i*fstd)=g.r; x1=*(dptr+j*dstd); x2=*(fptr+j*fstd); *(dptr+j*dstd)=g.c * x1 + g.s * x2; *(fptr+j*fstd)=g.c * x2 - g.s * x1; x1=*(dptr+k*dstd); t=g.s * x1; *(dptr+k*dstd)=x1*g.c; } i=n-2; j=n-1; g = givensCoef_d(*(dptr+i*dstd),t); *(d->block->array+(i*d->stride+d->offset)*d->block->rstride) = g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t=x1 - x2; x1 = *(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s; *(f->block->array+(i*f->stride+f->offset)*f->block->rstride) = x1+x2; *(d->block->array+(j*d->stride+d->offset)*d->block->rstride) = t; prodG_d(svd,i, j, g.c, g.s); } static void svdStep1_d(svdObj_d *svd) /* save V */ { vsip_vview_d *d = &svd->ds; vsip_vview_d *f = &svd->fs; givensObj_d g; vsip_length n = d->length; vsip_scalar_d mu=0.0, x1=0.0, x2=0.0; vsip_scalar_d t=0.0; vsip_index i,j,k; vsip_scalar_d d2=0.0,f1=0.0,d3=0.0,f2=0.0; vsip_scalar_d *fptr,*dptr; vsip_stride fstd=f->stride*f->block->rstride, dstd=d->stride*d->block->rstride; dptr=d->block->array+d->offset*d->block->rstride; fptr=f->block->array+f->offset*f->block->rstride; if(n >= 3){ d2=*(dptr+dstd*(n-2));f1= *(fptr+fstd*(n-3));d3 = *(dptr+dstd*(n-1));f2= *(fptr+fstd*(n-2)); } else if(n == 2){ d2=*dptr; d3=*(dptr+dstd); f1=0; f2=*fptr; } else { printf("should not be here (see svdStep_d)\n"); exit(-1); } mu = svdMu_d(d2,f1,d3,&f2,svd->eps0); if(f2 == 0.0) *(fptr+fstd*(n-2)) = 0.0; x1=*dptr; x2 = x1 * *fptr; x1 *= x1; x1 -= mu; g=givensCoef_d(x1,x2); x1=*dptr;x2=*fptr; *fptr=g.c*x2-g.s*x1; *dptr=g.c*x1+g.s*x2; t=*(dptr+dstd); *(dptr+dstd) *= g.c; t*=g.s; gtProd_d(0,1,g.c,g.s,svd); for(i=0; i<n-2; i++){ j=i+1; k=i+2; g = givensCoef_d(*(dptr+i*dstd),t); *(dptr+i*dstd)=g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t= x1 - x2; x1=*(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s ; *(f->block->array+(i*f->stride+f->offset)*f->block->rstride) = x1+x2; *(d->block->array+(j*d->stride+d->offset)*d->block->rstride) = t; x1=*(fptr+j*fstd); t=g.s * x1; *(fptr+j*fstd)=x1*g.c; g=givensCoef_d(*(fptr+i*fstd),t); *(fptr+i*fstd)=g.r; x1=*(dptr+j*dstd); x2=*(fptr+j*fstd); *(dptr+j*dstd)=g.c * x1 + g.s * x2; *(fptr+j*fstd)=g.c * x2 - g.s * x1; x1=*(dptr+k*dstd); t=g.s * x1; *(dptr+k*dstd)=x1*g.c; gtProd_d(j,k, g.c, g.s,svd); } i=n-2; j=n-1; g = givensCoef_d(*(dptr+i*dstd),t); *(d->block->array+(i*d->stride+d->offset)*d->block->rstride) = g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t=x1 - x2; x1 = *(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s; *(f->block->array+(i*f->stride+f->offset)*f->block->rstride) = x1+x2; *(d->block->array+(j*d->stride+d->offset)*d->block->rstride) = t; } static void svdStep0_d(svdObj_d *svd) { vsip_vview_d *d = &svd->ds; vsip_vview_d *f = &svd->fs; givensObj_d g; vsip_length n = d->length; vsip_scalar_d mu=0.0, x1=0.0, x2=0.0; vsip_scalar_d t=0.0; vsip_index i,j,k; vsip_scalar_d d2=0.0,f1=0.0,d3=0.0,f2=0.0; vsip_scalar_d *fptr,*dptr; vsip_stride fstd=f->stride*f->block->rstride, dstd=d->stride*d->block->rstride; dptr=d->block->array+d->offset*d->block->rstride; fptr=f->block->array+f->offset*f->block->rstride; if(n >= 3){ d2=*(dptr+dstd*(n-2));f1= *(fptr+fstd*(n-3));d3 = *(dptr+dstd*(n-1));f2= *(fptr+fstd*(n-2)); } else if(n == 2){ d2=*dptr; d3=*(dptr+dstd); f1=0; f2=*fptr; } else { printf("should not be here (see svdStep_d)\n"); exit(-1); } mu = svdMu_d(d2,f1,d3,&f2,svd->eps0); if(f2 == 0.0) *(fptr+fstd*(n-2)) = 0.0; x1=*dptr; x2 = x1 * *fptr; x1 *= x1; x1 -= mu; g=givensCoef_d(x1,x2); x1=*dptr;x2=*fptr; *fptr=g.c*x2-g.s*x1; *dptr=g.c*x1+g.s*x2; t=*(dptr+dstd); *(dptr+dstd) *= g.c; t*=g.s; for(i=0; i<n-2; i++){ j=i+1; k=i+2; g = givensCoef_d(*(dptr+i*dstd),t); *(dptr+i*dstd)=g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t= x1 - x2; x1=*(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s ; *(f->block->array+(i*f->stride+f->offset)*f->block->rstride) = x1+x2; *(d->block->array+(j*d->stride+d->offset)*d->block->rstride) = t; x1=*(fptr+j*fstd); t=g.s * x1; *(fptr+j*fstd)=x1*g.c; g=givensCoef_d(*(fptr+i*fstd),t); *(fptr+i*fstd)=g.r; x1=*(dptr+j*dstd); x2=*(fptr+j*fstd); *(dptr+j*dstd)=g.c * x1 + g.s * x2; *(fptr+j*fstd)=g.c * x2 - g.s * x1; x1=*(dptr+k*dstd); t=g.s * x1; *(dptr+k*dstd)=x1*g.c; } i=n-2; j=n-1; g = givensCoef_d(*(dptr+i*dstd),t); *(d->block->array+(i*d->stride+d->offset)*d->block->rstride) = g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t=x1 - x2; x1 = *(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s; *(f->block->array+(i*f->stride+f->offset)*f->block->rstride) = x1+x2; *(d->block->array+(j*d->stride+d->offset)*d->block->rstride) = t; } static vsip_cvview_d *cvsv_d(vsip_cvview_d *v,vsip_cvview_d *vs,vsip_index i) { *vs=*v; vs->offset += i * vs->stride; vs->length -= i; return vs; } static vsip_cmview_d* cmsv_d(vsip_cmview_d *B, vsip_cmview_d *BS, vsip_index i,vsip_index j) { *BS=*B; BS->row_length -= j; BS->col_length -= i; BS->offset += j * BS->row_stride + i * BS->col_stride; return BS; } static vsip_vview_d *vreal_sv_d(vsip_cvview_d *cv,vsip_vview_d*v) { v->block=cv->block->R; v->offset = cv->offset; v->length=cv->length;v->stride= cv->stride; v->markings = VSIP_VALID_STRUCTURE_OBJECT; return v; } static vsip_scalar_d cvnorm2_d(vsip_cvview_d *a) { vsip_length n = a->length; vsip_stride cast = a->block->cstride; vsip_scalar_d *apr = (vsip_scalar_d*) ((a->block->R->array) + cast * a->offset); vsip_scalar_d *api = (vsip_scalar_d*) ((a->block->I->array) + cast * a->offset); vsip_stride ast = (cast * a->stride); vsip_scalar_d t1=0,t2=0; while(n-- > 0){ t1 += *apr * *apr; t2 += *api * *api; apr += ast; api += ast; } return (vsip_scalar_d)sqrt(t1+t2); } static vsip_scalar_d cmnormFro_d(vsip_cmview_d *v) { vsip_length m=v->col_length,n=v->row_length; vsip_index i,j; vsip_stride rstrd=v->row_stride*v->block->R->rstride; vsip_stride cstrd=v->col_stride*v->block->R->rstride; vsip_scalar_d *vre=v->block->R->array+v->offset*v->block->R->rstride; vsip_scalar_d *vim=v->block->I->array+v->offset*v->block->I->rstride; vsip_scalar_d re=0.0; vsip_scalar_d im=0.0; for(i=0; i<m; i++){ vsip_offset o=i*cstrd; vsip_scalar_d *rp=vre+o; vsip_scalar_d *ip=vim+o; for(j=0; j<n; j++){ re += *rp * *rp; im += *ip * *ip; rp += rstrd; ip += rstrd; } } return (vsip_scalar_d)sqrt(re+im); } static void cmeye_d(vsip_cmview_d *v) { vsip_length m=v->col_length,n=v->row_length; vsip_index i,j; vsip_stride rstrd=v->row_stride*v->block->R->rstride; vsip_stride cstrd=v->col_stride*v->block->R->rstride; vsip_scalar_d *vre=v->block->R->array+v->offset*v->block->R->rstride; vsip_scalar_d *vim=v->block->I->array+v->offset*v->block->I->rstride; for(i=0; i<m; i++){ vsip_offset o=i*cstrd; vsip_scalar_d *rp=vre+o; vsip_scalar_d *ip=vim+o; for(j=0; j<n; j++){ *rp = (i==j) ? 1.0:0.0; *ip = 0.0; rp += rstrd; ip += rstrd; } } } static void cbiDiagPhaseToZero_d( csvdObj_d *svd) { vsip_cmview_d *L = svd->L; vsip_cvview_d *d = cdiag_sv_d(&svd->B,&svd->bs,0); vsip_cvview_d *f = cdiag_sv_d(&svd->B,&svd->bfs,1); vsip_cmview_d *R = svd->R; vsip_scalar_d eps0 = svd->eps0; vsip_length nd=d->length; vsip_length nf=f->length; vsip_index i,j; vsip_cscalar_d ps; vsip_scalar_d m; vsip_cvview_d *l = &svd->ls_one; vsip_cvview_d *r = &svd->rs_one; vsip_scalar_d *dptr_r=d->block->R->array+d->block->R->rstride*d->offset; vsip_scalar_d *dptr_i=d->block->I->array+d->block->R->rstride*d->offset; vsip_scalar_d *fptr_r=f->block->R->array+f->block->R->rstride*f->offset; vsip_scalar_d *fptr_i=f->block->I->array+f->block->R->rstride*f->offset; vsip_stride dstrd=d->stride*d->block->R->rstride; vsip_stride fstrd=f->stride*f->block->R->rstride; vsip_scalar_d re,im; for(i=0; i<nd; i++){ ps.r=*(dptr_r+i*dstrd); ps.i=*(dptr_i+i*dstrd); if(ps.i == 0.0){ m = ps.r; if (m < 0.0) ps.r=-1.0; else ps.r=1.0; m = (m<0) ? -m:m; } else { re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } if(m > eps0){ ccol_sv_d(L,l,i);csvmul_d(ps,l); *(d->block->R->array+(d->offset+i*d->stride)*d->block->cstride)=m; *(d->block->I->array+(d->offset+i*d->stride)*d->block->cstride)=0.0; if (i < nf){ vsip_scalar_d *fr=fptr_r+i*fstrd; vsip_scalar_d *fi=fptr_i+i*fstrd; re=*fr; im=*fi; *fr=re*ps.r+im*ps.i; *fi=-ps.i*re+ps.r*im; } }else{ *(dptr_r+i*dstrd)=0.0; *(dptr_i+i*dstrd)=0.0; } } for (i=0; i<nf-1; i++){ j=i+1; ps.r=*(fptr_r+i*fstrd); ps.i=*(fptr_i+i*fstrd); if (ps.i == 0.0){ m = ps.r; if (m < 0.0) ps.r =-1.0; else ps.r = 1.0; m = (m < 0.0) ? -m:m; }else{ re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } ccol_sv_d(L, l, j); ps.i=-ps.i;csvmul_d(ps,l);ps.i=-ps.i; crow_sv_d(R,r,j); csvmul_d(ps,r); *(fptr_r+i*fstrd)=m; *(fptr_i+i*fstrd)=0.0; re=*(fptr_r+ j * fstrd); im=*(fptr_i+ j * fstrd); *(fptr_r+ j * fstrd)=re*ps.r-im*ps.i; *(fptr_i+ j * fstrd)=re*ps.i+im*ps.r; } j=nf; i=j-1; ps.r=*(fptr_r+i*fstrd); ps.i=*(fptr_i+i*fstrd); if (ps.i == 0.0){ m = ps.r; if(m < 0.0) ps.r =-1.0; else ps.r = 1.0; m = (m<0) ? -m:m; }else{ re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } *(fptr_r+i*fstrd)=m; *(fptr_i+i*fstrd)=0.0; ccol_sv_d(L, l, j); ps.i=-ps.i;csvmul_d(ps,l);ps.i=-ps.i; crow_sv_d(R,r,j); csvmul_d(ps,r); } static void cbiDiagPhaseToZero2_d( csvdObj_d *svd) /* save U only */ { vsip_cmview_d *L = svd->L; vsip_cvview_d *d = cdiag_sv_d(&svd->B,&svd->bs,0); vsip_cvview_d *f = cdiag_sv_d(&svd->B,&svd->bfs,1); vsip_scalar_d eps0 = svd->eps0; vsip_length nd=d->length; vsip_length nf=f->length; vsip_index i,j; vsip_cscalar_d ps; vsip_scalar_d m; vsip_cvview_d *l = &svd->ls_one; vsip_scalar_d *dptr_r=d->block->R->array+d->block->R->rstride*d->offset; vsip_scalar_d *dptr_i=d->block->I->array+d->block->R->rstride*d->offset; vsip_scalar_d *fptr_r=f->block->R->array+f->block->R->rstride*f->offset; vsip_scalar_d *fptr_i=f->block->I->array+f->block->R->rstride*f->offset; vsip_stride dstrd=d->stride*d->block->R->rstride; vsip_stride fstrd=f->stride*f->block->R->rstride; vsip_scalar_d re,im; for(i=0; i<nd; i++){ ps.r=*(dptr_r+i*dstrd); ps.i=*(dptr_i+i*dstrd); if(ps.i == 0.0){ m = ps.r; if (m < 0.0) ps.r=-1.0; else ps.r=1.0; m = (m<0) ? -m:m; } else { re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } if(m > eps0){ ccol_sv_d(L,l,i);csvmul_d(ps,l); *(d->block->R->array+(d->offset+i*d->stride)*d->block->cstride)=m; *(d->block->I->array+(d->offset+i*d->stride)*d->block->cstride)=0.0; if (i < nf){ vsip_scalar_d *fr=fptr_r+i*fstrd; vsip_scalar_d *fi=fptr_i+i*fstrd; re=*fr; im=*fi; *fr=re*ps.r+im*ps.i; *fi=-ps.i*re+ps.r*im; } }else{ *(dptr_r+i*dstrd)=0.0; *(dptr_i+i*dstrd)=0.0; } } for (i=0; i<nf-1; i++){ j=i+1; ps.r=*(fptr_r+i*fstrd); ps.i=*(fptr_i+i*fstrd); if (ps.i == 0.0){ m = ps.r; if (m < 0.0) ps.r =-1.0; else ps.r = 1.0; m = (m < 0.0) ? -m:m; }else{ re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } ccol_sv_d(L, l, j); ps.i=-ps.i;csvmul_d(ps,l);ps.i=-ps.i; *(fptr_r+i*fstrd)=m; *(fptr_i+i*fstrd)=0.0; re=*(fptr_r+ j * fstrd); im=*(fptr_i+ j * fstrd); *(fptr_r+ j * fstrd)=re*ps.r-im*ps.i; *(fptr_i+ j * fstrd)=re*ps.i+im*ps.r; } j=nf; i=j-1; ps.r=*(fptr_r+i*fstrd); ps.i=*(fptr_i+i*fstrd); if (ps.i == 0.0){ m = ps.r; if(m < 0.0) ps.r =-1.0; else ps.r = 1.0; m = (m<0) ? -m:m; }else{ re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } *(fptr_r+i*fstrd)=m; *(fptr_i+i*fstrd)=0.0; ccol_sv_d(L, l, j); ps.i=-ps.i;csvmul_d(ps,l);ps.i=-ps.i; } static void cbiDiagPhaseToZero1_d( csvdObj_d *svd) /* save V only */ { vsip_cvview_d *d = cdiag_sv_d(&svd->B,&svd->bs,0); vsip_cvview_d *f = cdiag_sv_d(&svd->B,&svd->bfs,1); vsip_cmview_d *R = svd->R; vsip_scalar_d eps0 = svd->eps0; vsip_length nd=d->length; vsip_length nf=f->length; vsip_index i,j; vsip_cscalar_d ps; vsip_scalar_d m; vsip_cvview_d *r = &svd->rs_one; vsip_scalar_d *dptr_r=d->block->R->array+d->block->R->rstride*d->offset; vsip_scalar_d *dptr_i=d->block->I->array+d->block->R->rstride*d->offset; vsip_scalar_d *fptr_r=f->block->R->array+f->block->R->rstride*f->offset; vsip_scalar_d *fptr_i=f->block->I->array+f->block->R->rstride*f->offset; vsip_stride dstrd=d->stride*d->block->R->rstride; vsip_stride fstrd=f->stride*f->block->R->rstride; vsip_scalar_d re,im; for(i=0; i<nd; i++){ ps.r=*(dptr_r+i*dstrd); ps.i=*(dptr_i+i*dstrd); if(ps.i == 0.0){ m = ps.r; if (m < 0.0) ps.r=-1.0; else ps.r=1.0; m = (m<0) ? -m:m; } else { re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } if(m > eps0){ *(d->block->R->array+(d->offset+i*d->stride)*d->block->cstride)=m; *(d->block->I->array+(d->offset+i*d->stride)*d->block->cstride)=0.0; if (i < nf){ vsip_scalar_d *fr=fptr_r+i*fstrd; vsip_scalar_d *fi=fptr_i+i*fstrd; re=*fr; im=*fi; *fr=re*ps.r+im*ps.i; *fi=-ps.i*re+ps.r*im; } }else{ *(dptr_r+i*dstrd)=0.0; *(dptr_i+i*dstrd)=0.0; } } for (i=0; i<nf-1; i++){ j=i+1; ps.r=*(fptr_r+i*fstrd); ps.i=*(fptr_i+i*fstrd); if (ps.i == 0.0){ m = ps.r; if (m < 0.0) ps.r =-1.0; else ps.r = 1.0; m = (m < 0.0) ? -m:m; }else{ re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } crow_sv_d(R,r,j); csvmul_d(ps,r); *(fptr_r+i*fstrd)=m; *(fptr_i+i*fstrd)=0.0; re=*(fptr_r+ j * fstrd); im=*(fptr_i+ j * fstrd); *(fptr_r+ j * fstrd)=re*ps.r-im*ps.i; *(fptr_i+ j * fstrd)=re*ps.i+im*ps.r; } j=nf; i=j-1; ps.r=*(fptr_r+i*fstrd); ps.i=*(fptr_i+i*fstrd); if (ps.i == 0.0){ m = ps.r; if(m < 0.0) ps.r =-1.0; else ps.r = 1.0; m = (m<0) ? -m:m; }else{ re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } *(fptr_r+i*fstrd)=m; *(fptr_i+i*fstrd)=0.0; crow_sv_d(R,r,j); csvmul_d(ps,r); } static void cbiDiagPhaseToZero0_d( csvdObj_d *svd) { vsip_cvview_d *d = cdiag_sv_d(&svd->B,&svd->bs,0); vsip_cvview_d *f = cdiag_sv_d(&svd->B,&svd->bfs,1); vsip_scalar_d eps0 = svd->eps0; vsip_length nd=d->length; vsip_length nf=f->length; vsip_index i,j; vsip_cscalar_d ps; vsip_scalar_d m; vsip_scalar_d *dptr_r=d->block->R->array+d->block->R->rstride*d->offset; vsip_scalar_d *dptr_i=d->block->I->array+d->block->R->rstride*d->offset; vsip_scalar_d *fptr_r=f->block->R->array+f->block->R->rstride*f->offset; vsip_scalar_d *fptr_i=f->block->I->array+f->block->R->rstride*f->offset; vsip_stride dstrd=d->stride*d->block->R->rstride; vsip_stride fstrd=f->stride*f->block->R->rstride; vsip_scalar_d re,im; for(i=0; i<nd; i++){ ps.r=*(dptr_r+i*dstrd); ps.i=*(dptr_i+i*dstrd); if(ps.i == 0.0){ m = ps.r; if (m < 0.0) ps.r=-1.0; else ps.r=1.0; m = (m<0) ? -m:m; } else { re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } if(m > eps0){ *(d->block->R->array+(d->offset+i*d->stride)*d->block->cstride)=m; *(d->block->I->array+(d->offset+i*d->stride)*d->block->cstride)=0.0; if (i < nf){ vsip_scalar_d *fr=fptr_r+i*fstrd; vsip_scalar_d *fi=fptr_i+i*fstrd; re=*fr; im=*fi; *fr=re*ps.r+im*ps.i; *fi=-ps.i*re+ps.r*im; } }else{ *(dptr_r+i*dstrd)=0.0; *(dptr_i+i*dstrd)=0.0; } } for (i=0; i<nf-1; i++){ j=i+1; ps.r=*(fptr_r+i*fstrd); ps.i=*(fptr_i+i*fstrd); if (ps.i == 0.0){ m = ps.r; if (m < 0.0) ps.r =-1.0; else ps.r = 1.0; m = (m < 0.0) ? -m:m; }else{ re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } *(fptr_r+i*fstrd)=m; *(fptr_i+i*fstrd)=0.0; re=*(fptr_r+ j * fstrd); im=*(fptr_i+ j * fstrd); *(fptr_r+ j * fstrd)=re*ps.r-im*ps.i; *(fptr_i+ j * fstrd)=re*ps.i+im*ps.r; } j=nf; i=j-1; ps.r=*(fptr_r+i*fstrd); ps.i=*(fptr_i+i*fstrd); if (ps.i == 0.0){ m = ps.r; if(m < 0.0) ps.r =-1.0; else ps.r = 1.0; m = (m<0) ? -m:m; }else{ re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } *(fptr_r+i*fstrd)=m; *(fptr_i+i*fstrd)=0.0; } static void cphaseCheck_d(csvdObj_d *svd) { vsip_cmview_d *L = &svd->Ls; vsip_vview_d *d = &svd->ds; vsip_vview_d *f = &svd->fs; vsip_scalar_d eps0 = svd->eps0; vsip_length nf=f->length; vsip_index i,k; vsip_scalar_d ps; vsip_scalar_d m; vsip_cvview_d *l = &svd->ls_one; vsip_scalar_d *fptr=f->block->array + f->offset * f->block->rstride; vsip_scalar_d *dptr=d->block->array + d->offset * d->block->rstride; vsip_scalar_d *re,*im; vsip_stride strd; for(i=0; i<d->length; i++){ ps=dptr[i]; m = (ps<0) ? -ps:ps; ps=sign_d(ps); if(m > eps0){ ccol_sv_d(L,l,i); strd=l->stride*l->block->R->rstride; re=l->block->R->array+l->offset*l->block->R->rstride; im=l->block->I->array+l->offset*l->block->R->rstride; for(k=0; k<l->length*strd; k+=strd){ re[k]*=ps; im[k]*=ps; } dptr[i]=m; if (i < nf) fptr[i]*=ps; } else { dptr[i]=0.0; } } for(i=0; i<nf; i++){ vsip_scalar_f f_i= fptr[i]; if(f_i < 0.0) f_i = -f_i; m = (dptr[i] + dptr[i+1]) * eps0; if (f_i < m) fptr[i] = 0.0; } } static void cphaseCheck2_d(csvdObj_d *svd) /* save U */ { vsip_cmview_d *L = &svd->Ls; vsip_vview_d *d = &svd->ds; vsip_vview_d *f = &svd->fs; vsip_scalar_d eps0 = svd->eps0; vsip_length nf=f->length; vsip_index i,k; vsip_scalar_d ps; vsip_scalar_d m; vsip_cvview_d *l = &svd->ls_one; vsip_scalar_d *fptr=f->block->array + f->offset * f->block->rstride; vsip_scalar_d *dptr=d->block->array + d->offset * d->block->rstride; vsip_scalar_d *re,*im; vsip_stride strd; for(i=0; i<d->length; i++){ ps=dptr[i]; m = (ps<0) ? -ps:ps; ps=sign_d(ps); if(m > eps0){ ccol_sv_d(L,l,i); strd=l->stride*l->block->R->rstride; re=l->block->R->array+l->offset*l->block->R->rstride; im=l->block->I->array+l->offset*l->block->R->rstride; for(k=0; k<l->length*strd; k+=strd){ re[k]*=ps; im[k]*=ps; } dptr[i]=m; if (i < nf) fptr[i]*=ps; } else { dptr[i]=0.0; } } for(i=0; i<nf; i++){ vsip_scalar_f f_i= fptr[i]; if(f_i < 0.0) f_i = -f_i; m = (dptr[i] + dptr[i+1]) * eps0; if (f_i < m) fptr[i] = 0.0; } } static void cphaseCheck1_d(csvdObj_d *svd) /* save V */ { vsip_vview_d *d = &svd->ds; vsip_vview_d *f = &svd->fs; vsip_scalar_d eps0 = svd->eps0; vsip_length nf=f->length; vsip_index i; vsip_scalar_d ps; vsip_scalar_d m; vsip_scalar_d *fptr=f->block->array + f->offset * f->block->rstride; vsip_scalar_d *dptr=d->block->array + d->offset * d->block->rstride; for(i=0; i<d->length; i++){ ps=dptr[i]; m = (ps<0) ? -ps:ps; ps=sign_d(ps); if(m > eps0){ dptr[i]=m; if (i < nf) fptr[i]*=ps; } else { dptr[i]=0.0; } } for(i=0; i<nf; i++){ vsip_scalar_f f_i= fptr[i]; if(f_i < 0.0) f_i = -f_i; m = (dptr[i] + dptr[i+1]) * eps0; if (f_i < m) fptr[i] = 0.0; } } static void chouseProd_d(vsip_cvview_d *v, vsip_cmview_d *A, vsip_cvview_d*w) { vsip_scalar_d *Aptr_r = A->block->R->array+A->offset * A->block->R->rstride; vsip_scalar_d *Aptr_i = A->block->I->array+A->offset * A->block->R->rstride; vsip_scalar_d *vptr_r = v->block->R->array+v->offset * v->block->R->rstride; vsip_scalar_d *vptr_i = v->block->I->array+v->offset * v->block->R->rstride; vsip_scalar_d *wptr_r = w->block->R->array+w->offset * w->block->R->rstride; vsip_scalar_d *wptr_i = w->block->I->array+w->offset * w->block->R->rstride; vsip_stride vstrd=v->stride * v->block->R->rstride; vsip_stride wstrd=w->stride * w->block->R->rstride; vsip_stride AcStrd=A->col_stride*A->block->R->rstride; vsip_stride ArStrd=A->row_stride*A->block->R->rstride; vsip_index i,j,vi,wi; vsip_length M = A->col_length * A->col_stride * A->block->R->rstride; vsip_length N = A->row_length * A->row_stride * A->block->R->rstride; vsip_scalar_d beta = 0.0; vsip_scalar_d t1=0,t2=0; for(i=0;i<v->length;i++){ vsip_scalar_d re=vptr_r[i*vstrd],im=vptr_i[i*vstrd]; t1 += re*re; t2 += im*im; } beta=2.0/(t1+t2); w->length = A->row_length; wi = 0; for(i=0; i<N; i+=ArStrd){ vsip_scalar_d *ar_r=&Aptr_r[i], *ar_i=&Aptr_i[i]; vsip_scalar_d re=0.0,im=0.0; vi = 0; for(j=0; j<M; j+=AcStrd){ re += ar_r[j] * vptr_r[vi] + ar_i[j] * vptr_i[vi]; im += -ar_r[j] * vptr_i[vi] + ar_i[j] * vptr_r[vi]; vi += vstrd; } wptr_r[wi] = re; wptr_i[wi] = -im; wi += wstrd; } vi = 0; for(i=0; i<M; i+=AcStrd){ vsip_scalar_d cr = beta * vptr_r[vi]; vsip_scalar_d ci = beta * vptr_i[vi]; vsip_scalar_d *aprp=Aptr_r+i; vsip_scalar_d *apip=Aptr_i+i; wi = 0; for(j=0; j<N; j+=ArStrd){ vsip_scalar_d yr = wptr_r[wi]; vsip_scalar_d yi = -wptr_i[wi]; aprp[j] -= (cr * yr - ci * yi); apip[j] -= (cr * yi + ci * yr); wi += wstrd; } vi += vstrd; } } static void cprodHouse_d(vsip_cmview_d *A, vsip_cvview_d *v, vsip_cvview_d *w) { vsip_scalar_d *Aptr_r = A->block->R->array+A->offset * A->block->R->rstride; vsip_scalar_d *Aptr_i = A->block->I->array+A->offset * A->block->R->rstride; vsip_scalar_d *vptr_r = v->block->R->array+v->offset * v->block->R->rstride; vsip_scalar_d *vptr_i = v->block->I->array+v->offset * v->block->R->rstride; vsip_scalar_d *wptr_r = w->block->R->array+w->offset * w->block->R->rstride; vsip_scalar_d *wptr_i = w->block->I->array+w->offset * w->block->R->rstride; vsip_stride vstrd=v->stride * v->block->R->rstride; vsip_stride wstrd=w->stride * w->block->R->rstride; vsip_stride AcStrd=A->col_stride*A->block->R->rstride; vsip_stride ArStrd=A->row_stride*A->block->R->rstride; vsip_index i,j,vi,wi; vsip_length M = A->col_length * A->col_stride * A->block->R->rstride; vsip_length N = A->row_length * A->row_stride * A->block->R->rstride; vsip_scalar_d beta = 0.0; vsip_scalar_d t1=0,t2=0; for(i=0;i<v->length;i++){ vsip_scalar_d re=vptr_r[i*vstrd],im=vptr_i[i*vstrd]; t1 += re*re; t2 += im*im; } beta=2.0/(t1+t2); w->length = A->col_length; wi = 0; for(i=0; i<M; i+=AcStrd){ vsip_scalar_d *ac_r=&Aptr_r[i], *ac_i=&Aptr_i[i]; vsip_scalar_d re=0.0,im=0.0; vi = 0; for(j=0; j<N; j+=ArStrd){ re += ac_r[j] * vptr_r[vi] - ac_i[j] * vptr_i[vi]; im += ac_r[j] * vptr_i[vi] + ac_i[j] * vptr_r[vi]; vi += vstrd; } wptr_r[wi] = -beta * re; wptr_i[wi] = -beta * im; wi += wstrd; } wi = 0; for(i=0; i<M; i+=AcStrd){ vsip_scalar_d cr = wptr_r[wi]; vsip_scalar_d ci = wptr_i[wi]; vsip_scalar_d *aprp=Aptr_r+i; vsip_scalar_d *apip=Aptr_i+i; vi = 0; for(j=0; j<N; j+=ArStrd){ vsip_scalar_d yr = vptr_r[vi]; vsip_scalar_d yi = -vptr_i[vi]; aprp[j] += (cr * yr - ci * yi); apip[j] += (cr * yi + ci * yr); vi += vstrd; } wi += wstrd; } } static vsip_cvview_d *chouseVector_d(vsip_cvview_d* x) { vsip_scalar_d *x0r=x->block->R->array + x->offset * x->block->R->rstride; vsip_scalar_d *x0i=x->block->I->array + x->offset * x->block->R->rstride; vsip_scalar_d nrm=cvnorm2_d(x); vsip_cscalar_d t,s; t.r=*x0r;t.i=*x0i; s=csign_d(t); s.r *= nrm; s.i *= nrm; s.r += t.r; s.i +=t.i; *x0r = s.r;*x0i=s.i; nrm = cvnorm2_d(x); if (nrm == 0.0){ *x0r=1.0;*x0i=0.0; }else{ vsip_index i; vsip_stride str=x->stride * x->block->R->rstride; vsip_length n = x->length * str; for(i=0; i<n; i+=str){ x0r[i] /= nrm; x0i[i] /= nrm; } } return x; } static void cVHmatExtract_d(csvdObj_d *svd) { vsip_cmview_d *B = &svd->B; vsip_index i,j; vsip_length n = B->row_length; vsip_cmview_d *Bs=&svd->Bs; vsip_cmview_d *V=svd->R; vsip_cmview_d *Vs=&svd->Rs; vsip_cvview_d *v=&svd->bs; vsip_cscalar_d t; if(n < 3) return; for(i=n-3; i>0; i--){ j=i+1; crow_sv_d(cmsv_d(B,Bs,i,j),v,0); t.r=*(v->block->R->array+v->offset*v->block->cstride); t.i=*(v->block->I->array+v->offset*v->block->cstride); *(v->block->R->array+v->offset*v->block->cstride)=1.0; *(v->block->I->array+v->offset*v->block->cstride)=0.0; cprodHouse_d(cmsv_d(V,Vs,j,j),v,svd->w); *(v->block->R->array+v->offset*v->block->cstride)=t.r; *(v->block->I->array+v->offset*v->block->cstride)=t.i; } crow_sv_d(cmsv_d(B,Bs,0,1),v,0); t.r=*(v->block->R->array+v->offset*v->block->cstride); t.i=*(v->block->I->array+v->offset*v->block->cstride); *(v->block->R->array+v->offset*v->block->cstride)=1.0; *(v->block->I->array+v->offset*v->block->cstride)=0.0; cprodHouse_d(cmsv_d(V,Vs,1,1),v,svd->w); *(v->block->R->array+v->offset*v->block->cstride)=t.r; *(v->block->I->array+v->offset*v->block->cstride)=t.i; } static void cUmatExtract_d(csvdObj_d *svd) { vsip_cmview_d* B=&svd->B; vsip_cmview_d* U=svd->L; vsip_index i; vsip_length m = B->col_length; vsip_length n = B->row_length; vsip_cmview_d *Bs=&svd->Bs; vsip_cmview_d *Us=&svd->Ls; vsip_cvview_d *v=&svd->bs; vsip_cscalar_d t; if (m > n){ i=n-1; ccol_sv_d(cmsv_d(B,Bs,i,i),v,0); t.r=*(v->block->R->array+v->offset*v->block->cstride); t.i=*(v->block->I->array+v->offset*v->block->cstride); *(v->block->R->array+v->offset*v->block->cstride)=1.0; *(v->block->I->array+v->offset*v->block->cstride)=0.0; chouseProd_d(v,cmsv_d(U,Us,i,i),svd->w); *(v->block->R->array+v->offset*v->block->cstride)=t.r; *(v->block->I->array+v->offset*v->block->cstride)=t.i; } for(i=n-2; i>0; i--){ ccol_sv_d(cmsv_d(B,Bs,i,i),v,0); t.r=*(v->block->R->array+v->offset*v->block->cstride); t.i=*(v->block->I->array+v->offset*v->block->cstride); *(v->block->R->array+v->offset*v->block->cstride)=1.0; *(v->block->I->array+v->offset*v->block->cstride)=0.0; chouseProd_d(v,cmsv_d(U,Us,i,i),svd->w); *(v->block->R->array+v->offset*v->block->cstride)=t.r; *(v->block->I->array+v->offset*v->block->cstride)=t.i; } ccol_sv_d(cmsv_d(B,Bs,0,0),v,0); t.r=*(v->block->R->array+v->offset*v->block->cstride); t.i=*(v->block->I->array+v->offset*v->block->cstride); *(v->block->R->array+v->offset*v->block->cstride)=1.0; *(v->block->I->array+v->offset*v->block->cstride)=0.0; chouseProd_d(v,cmsv_d(U,Us,0,0),svd->w); *(v->block->R->array+v->offset*v->block->cstride)=t.r; *(v->block->I->array+v->offset*v->block->cstride)=t.i; } static void cbidiag_d(csvdObj_d *svd) { vsip_cmview_d *B = &svd->B; vsip_cmview_d *Bs = &svd->Bs; vsip_length m = B->col_length; vsip_length n = B->row_length; vsip_cvview_d *x=ccol_sv_d(B,&svd->bs,0); vsip_cvview_d *v=svd->t; vsip_cvview_d *vs = &svd->ts; vsip_index i,j; vsip_cscalar_d z; vsip_scalar_d re,im; v->length = x->length; cvcopy_d(x,v); for(i=0; i<n-1; i++){ v->length=m-i; ccol_sv_d(cmsv_d(B,Bs,i,i),x,0); cvcopy_d(x,v);/*0*/ chouseVector_d(v); re=*(v->block->R->array+v->offset*v->block->cstride); im=*(v->block->I->array+v->offset*v->block->cstride); z.i=(re*re+im*im);z.r=re/z.i;z.i=-im/z.i; csvmul_d(z,v); chouseProd_d(v,Bs,svd->w); cvsv_d(v,vs,1);cvsv_d(x,x,1); cvcopy_d(vs,x);/*1*/ if(i < n-2){ j = i+1; v->length=n-j; crow_sv_d(cmsv_d(B,Bs,i,j),x,0); cvcopy_d(x,v);/*2*/ chouseVector_d(v); { vsip_length _n = v->length; vsip_scalar_d *vpi = v->block->I->array + v->block->cstride * v->offset; vsip_stride vst = v->block->cstride * v->stride; while(_n-- > 0){ *vpi = - *vpi; vpi += vst; } }/*v.conj*/ re=*(v->block->R->array+v->offset*v->block->cstride); im=*(v->block->I->array+v->offset*v->block->cstride); z.i=(re*re+im*im);z.r=re/z.i;z.i=-im/z.i; csvmul_d(z,v); cprodHouse_d(Bs,v,svd->w); cvsv_d(v,vs,1);cvsv_d(x,x,1); cvcopy_d(vs,x);/*3*/ } } if(m > n){ i=n-1; v->length=m-i; ccol_sv_d(cmsv_d(B,Bs,i,i),x,0); cvcopy_d(x,v);/*4*/ chouseVector_d(v); re=*(v->block->R->array+v->offset*v->block->cstride); im=*(v->block->I->array+v->offset*v->block->cstride); z.i=(re*re+im*im);z.r=re/z.i;z.i=-im/z.i; csvmul_d(z,v); chouseProd_d(v,Bs,svd->w); cvsv_d(v,vs,1);cvsv_d(x,x,1); cvcopy_d(vs,x);/*5*/ } } static void cgtProd_d(vsip_index i, vsip_index j,vsip_scalar_d c, vsip_scalar_d s,csvdObj_d *svd) { vsip_cmview_d* R=&svd->Rs; vsip_cvview_d *a1= crow_sv_d(R,&svd->rs_one,i); vsip_cvview_d *a2= crow_sv_d(R,&svd->rs_two,j); vsip_index k; vsip_offset o = a1->block->R->rstride * a1->offset; vsip_stride std=a1->stride * a1->block->R->rstride; vsip_length n = a1->length; register vsip_scalar_d *a1r= a1->block->R->array; register vsip_scalar_d *a1i= a1->block->I->array; register vsip_scalar_d *a2r= a1r; register vsip_scalar_d *a2i= a1i; register vsip_scalar_d b1r,b1i,b2r,b2i; a1r+=o; a1i+=o; o=a2->block->R->rstride * a2->offset; a2r+=o; a2i+=o; for(k=0; k<n; k++){ b1r = *a1r; b1i=*a1i; b2r=*a2r; b2i=*a2i; *a1r =c * b1r + s * b2r; *a1i =c * b1i + s * b2i; *a2r =c * b2r - s * b1r; *a2i =c * b2i - s * b1i; a1r+=std;a1i+=std;a2r+=std;a2i+=std; } } static void cprodG_d(csvdObj_d *svd,vsip_index i, vsip_index j,vsip_scalar_d c, vsip_scalar_d s) { vsip_cmview_d* L=&svd->Ls; vsip_cvview_d *a1= ccol_sv_d(L,&svd->ls_one,i); vsip_cvview_d *a2= ccol_sv_d(L,&svd->ls_two,j); vsip_index k; vsip_offset o = a1->block->R->rstride * a1->offset; register vsip_stride std=a1->stride * a1->block->R->rstride; vsip_length n = a1->length; register vsip_scalar_d *a1r= a1->block->R->array; register vsip_scalar_d *a1i= a1->block->I->array; register vsip_scalar_d *a2r= a1r; register vsip_scalar_d *a2i= a1i; register vsip_scalar_d b1r,b1i,b2r,b2i; a1r+=o; a1i+=o; o=a2->block->R->rstride * a2->offset; a2r+=o; a2i+=o; for(k=0; k<n; k++){ b1r = *a1r; b1i=*a1i; b2r=*a2r; b2i=*a2i; *a1r = c * b1r + s * b2r; *a1i = c * b1i + s * b2i; *a2r = c * b2r - s * b1r; *a2i = c * b2i - s * b1i; a1r+=std;a1i+=std;a2r+=std;a2i+=std; } } static void czeroCol_d(csvdObj_d *svd) { vsip_vview_d *d=&svd->ds; vsip_vview_d *f=&svd->fs; vsip_length n = f->length; givensObj_d g; vsip_scalar_d xd,xf,t; vsip_index i,j,k; if (n == 1){ xd=*(d->block->array + d->offset * d->block->rstride); xf=*(f->block->array + f->offset * f->block->rstride); g=givensCoef_d(xd,xf); *(d->block->array + d->offset * d->block->rstride)=g.r; *(f->block->array + f->offset * f->block->rstride)=0.0; cgtProd_d(0,1,g.c,g.s,svd); }else if (n == 2){ xd=VI_VGET_F(d,1); xf=VI_VGET_F(f,1); g=givensCoef_d(xd,xf); *(d->block->array + (d->offset+1) * d->block->rstride)=g.r; *(f->block->array + (f->offset+1) * f->block->rstride)=0.0; xf=VI_VGET_F(f,0); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset) * f->block->rstride)=xf; cgtProd_d(1,2,g.c,g.s,svd); xd=VI_VGET_F(d,0); g=givensCoef_d(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; cgtProd_d(0,2,g.c,g.s,svd); }else{ i=n-1; j=i-1; k=i; xd=*(d->block->array + (d->offset+i) * d->block->rstride); xf=*(f->block->array + (f->offset+i) * f->block->rstride); g=givensCoef_d(xd,xf); xf=*(f->block->array + (f->offset+j) * f->block->rstride); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; *(f->block->array + (f->offset+i) * f->block->rstride)=0.0; t=-xf*g.s; xf*=g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; cgtProd_d(i,k+1,g.c,g.s,svd); while (i > 1){ i = j; j = i-1; xd=*(d->block->array + (d->offset+i) * d->block->rstride); g=givensCoef_d(xd,t); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; xf=*(f->block->array + (f->offset+j) * f->block->rstride); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; cgtProd_d(i,k+1,g.c,g.s,svd); } xd=*(d->block->array + d->offset * d->block->rstride); g=givensCoef_d(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; cgtProd_d(0,k+1,g.c,g.s,svd); } } static void czeroRow_d(csvdObj_d *svd) { vsip_vview_d *d = &svd->ds; vsip_vview_d *f = &svd->fs; vsip_length n = d->length; givensObj_d g; vsip_scalar_d xd,xf,t; vsip_index i; vsip_scalar_d *dptr=d->block->array+d->block->rstride*d->offset; vsip_scalar_d *fptr=f->block->array+f->block->rstride*f->offset; vsip_stride dstrd=d->stride*d->block->rstride; vsip_stride fstrd=f->stride*f->block->rstride; xd=*dptr; xf=*fptr; g=givensCoef_d(xd,xf); if (n == 1){ *dptr=g.r; *fptr=0.0; cprodG_d(svd,1,0,g.c,g.s); }else{ *dptr=g.r; *fptr=0.0; xf=*(fptr+fstrd); t= -xf * g.s; xf *= g.c; *(fptr+fstrd)=xf; cprodG_d(svd,1,0,g.c,g.s); for(i=1; i<n-1; i++){ xd=*(dptr+i*dstrd); g=givensCoef_d(xd,t); cprodG_d(svd,i+1,0,g.c,g.s); *(dptr+i*dstrd)=g.r; xf=*(fptr+(i+1)*fstrd); t=-xf * g.s; xf *= g.c; *(fptr+(i+1)*fstrd)=xf; } xd=*(dptr+(n-1)*dstrd); g=givensCoef_d(xd,t); *(dptr+(n-1)*dstrd)=g.r; cprodG_d(svd,n,0,g.c,g.s); } } static void czeroCol2_d(csvdObj_d *svd) /* save U */ { vsip_vview_d *d=&svd->ds; vsip_vview_d *f=&svd->fs; vsip_length n = f->length; givensObj_d g; vsip_scalar_d xd,xf,t; vsip_index i,j; if (n == 1){ xd=*(d->block->array + d->offset * d->block->rstride); xf=*(f->block->array + f->offset * f->block->rstride); g=givensCoef_d(xd,xf); *(d->block->array + d->offset * d->block->rstride)=g.r; *(f->block->array + f->offset * f->block->rstride)=0.0; }else if (n == 2){ xd=VI_VGET_F(d,1); xf=VI_VGET_F(f,1); g=givensCoef_d(xd,xf); *(d->block->array + (d->offset+1) * d->block->rstride)=g.r; *(f->block->array + (f->offset+1) * f->block->rstride)=0.0; xf=VI_VGET_F(f,0); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset) * f->block->rstride)=xf; xd=VI_VGET_F(d,0); g=givensCoef_d(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; }else{ i=n-1; j=i-1; xd=*(d->block->array + (d->offset+i) * d->block->rstride); xf=*(f->block->array + (f->offset+i) * f->block->rstride); g=givensCoef_d(xd,xf); xf=*(f->block->array + (f->offset+j) * f->block->rstride); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; *(f->block->array + (f->offset+i) * f->block->rstride)=0.0; t=-xf*g.s; xf*=g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; while (i > 1){ i = j; j = i-1; xd=*(d->block->array + (d->offset+i) * d->block->rstride); g=givensCoef_d(xd,t); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; xf=*(f->block->array + (f->offset+j) * f->block->rstride); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; } xd=*(d->block->array + d->offset * d->block->rstride); g=givensCoef_d(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; } } static void czeroRow2_d(csvdObj_d *svd) /* save U */ { vsip_vview_d *d = &svd->ds; vsip_vview_d *f = &svd->fs; vsip_length n = d->length; givensObj_d g; vsip_scalar_d xd,xf,t; vsip_index i; vsip_scalar_d *dptr=d->block->array+d->block->rstride*d->offset; vsip_scalar_d *fptr=f->block->array+f->block->rstride*f->offset; vsip_stride dstrd=d->stride*d->block->rstride; vsip_stride fstrd=f->stride*f->block->rstride; xd=*dptr; xf=*fptr; g=givensCoef_d(xd,xf); if (n == 1){ *dptr=g.r; *fptr=0.0; cprodG_d(svd,1,0,g.c,g.s); }else{ *dptr=g.r; *fptr=0.0; xf=*(fptr+fstrd); t= -xf * g.s; xf *= g.c; *(fptr+fstrd)=xf; cprodG_d(svd,1,0,g.c,g.s); for(i=1; i<n-1; i++){ xd=*(dptr+i*dstrd); g=givensCoef_d(xd,t); cprodG_d(svd,i+1,0,g.c,g.s); *(dptr+i*dstrd)=g.r; xf=*(fptr+(i+1)*fstrd); t=-xf * g.s; xf *= g.c; *(fptr+(i+1)*fstrd)=xf; } xd=*(dptr+(n-1)*dstrd); g=givensCoef_d(xd,t); *(dptr+(n-1)*dstrd)=g.r; cprodG_d(svd,n,0,g.c,g.s); } } static void czeroCol1_d(csvdObj_d *svd) /* save V */ { vsip_vview_d *d=&svd->ds; vsip_vview_d *f=&svd->fs; vsip_length n = f->length; givensObj_d g; vsip_scalar_d xd,xf,t; vsip_index i,j,k; if (n == 1){ xd=*(d->block->array + d->offset * d->block->rstride); xf=*(f->block->array + f->offset * f->block->rstride); g=givensCoef_d(xd,xf); *(d->block->array + d->offset * d->block->rstride)=g.r; *(f->block->array + f->offset * f->block->rstride)=0.0; cgtProd_d(0,1,g.c,g.s,svd); }else if (n == 2){ xd=VI_VGET_F(d,1); xf=VI_VGET_F(f,1); g=givensCoef_d(xd,xf); *(d->block->array + (d->offset+1) * d->block->rstride)=g.r; *(f->block->array + (f->offset+1) * f->block->rstride)=0.0; xf=VI_VGET_F(f,0); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset) * f->block->rstride)=xf; cgtProd_d(1,2,g.c,g.s,svd); xd=VI_VGET_F(d,0); g=givensCoef_d(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; cgtProd_d(0,2,g.c,g.s,svd); }else{ i=n-1; j=i-1; k=i; xd=*(d->block->array + (d->offset+i) * d->block->rstride); xf=*(f->block->array + (f->offset+i) * f->block->rstride); g=givensCoef_d(xd,xf); xf=*(f->block->array + (f->offset+j) * f->block->rstride); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; *(f->block->array + (f->offset+i) * f->block->rstride)=0.0; t=-xf*g.s; xf*=g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; cgtProd_d(i,k+1,g.c,g.s,svd); while (i > 1){ i = j; j = i-1; xd=*(d->block->array + (d->offset+i) * d->block->rstride); g=givensCoef_d(xd,t); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; xf=*(f->block->array + (f->offset+j) * f->block->rstride); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; cgtProd_d(i,k+1,g.c,g.s,svd); } xd=*(d->block->array + d->offset * d->block->rstride); g=givensCoef_d(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; cgtProd_d(0,k+1,g.c,g.s,svd); } } static void czeroRow1_d(csvdObj_d *svd) /* save V */ { vsip_vview_d *d = &svd->ds; vsip_vview_d *f = &svd->fs; vsip_length n = d->length; givensObj_d g; vsip_scalar_d xd,xf,t; vsip_index i; vsip_scalar_d *dptr=d->block->array+d->block->rstride*d->offset; vsip_scalar_d *fptr=f->block->array+f->block->rstride*f->offset; vsip_stride dstrd=d->stride*d->block->rstride; vsip_stride fstrd=f->stride*f->block->rstride; xd=*dptr; xf=*fptr; g=givensCoef_d(xd,xf); if (n == 1){ *dptr=g.r; *fptr=0.0; }else{ *dptr=g.r; *fptr=0.0; xf=*(fptr+fstrd); t= -xf * g.s; xf *= g.c; *(fptr+fstrd)=xf; for(i=1; i<n-1; i++){ xd=*(dptr+i*dstrd); g=givensCoef_d(xd,t); *(dptr+i*dstrd)=g.r; xf=*(fptr+(i+1)*fstrd); t=-xf * g.s; xf *= g.c; *(fptr+(i+1)*fstrd)=xf; } xd=*(dptr+(n-1)*dstrd); g=givensCoef_d(xd,t); *(dptr+(n-1)*dstrd)=g.r; } } static void csvdStep_d(csvdObj_d *svd) { vsip_vview_d *d = &svd->ds; vsip_vview_d *f = &svd->fs; givensObj_d g; vsip_length n = d->length; vsip_scalar_d mu=0.0, x1=0.0, x2=0.0; vsip_scalar_d t=0.0; vsip_index i,j,k; vsip_scalar_d d2=0.0,f1=0.0,d3=0.0,f2=0.0; vsip_scalar_d *fptr,*dptr,*tdptr,*tfptr; vsip_stride fstd=f->stride*f->block->rstride, dstd=d->stride*d->block->rstride; dptr=d->block->array+d->offset*d->block->rstride; fptr=f->block->array+f->offset*f->block->rstride; if(n >= 3){ d2=*(dptr+dstd*(n-2));f1= *(fptr+fstd*(n-3));d3 = *(dptr+dstd*(n-1));f2= *(fptr+fstd*(n-2)); } else if(n == 2){ d2=*dptr; d3=*(dptr+dstd); f1=0; f2=*fptr; } else { printf("should not be here (see svdStep_d"); exit(-1); } mu = svdMu_d(d2,f1,d3,&f2,svd->eps0); if(f2 == 0.0) *(fptr+fstd*(n-2)) = 0.0; x1=*dptr; x2 = x1 * *fptr; x1 *= x1; x1 -= mu; g=givensCoef_d(x1,x2); x1=*dptr;x2=*fptr; *fptr=g.c * x2 - g.s * x1; *dptr=x1 * g.c + x2 * g.s; tdptr=dptr+dstd; t=*tdptr; *tdptr=t*g.c; t*=g.s; cgtProd_d(0,1,g.c,g.s,svd); for(i=0; i<n-2; i++){ j=i+1; k=i+2; tdptr=dptr+i*dstd; tfptr=fptr+i*fstd; g = givensCoef_d(*tdptr,t); *tdptr=g.r; x1 = *(tdptr+dstd)*g.c; x2=*tfptr*g.s; t= x1 - x2; x1=*(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s ; *(fptr+i*fstd)= x1+x2; *(dptr+j*dstd) = t; x1=*(fptr+j*fstd); t=g.s * x1; *(fptr+j*fstd) = x1*g.c; cprodG_d(svd,i, j, g.c, g.s); g=givensCoef_d(*(fptr+i*fstd),t); *(fptr+i*fstd)=g.r; x1=*(dptr+j*dstd); x2=*(fptr+j*fstd); *(dptr+j*dstd)=g.c * x1 + g.s * x2; *(fptr+j*fstd)=g.c * x2 - g.s * x1; x1=*(dptr+k*dstd); t=g.s * x1; *(dptr+k*dstd)=x1*g.c; cgtProd_d(j,k, g.c, g.s,svd); } i=n-2; j=n-1; g = givensCoef_d(*(dptr+i*dstd),t); *(dptr+i*dstd)=g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t=x1 - x2; x1 = *(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s; *(fptr+i*fstd)=x1+x2; *(dptr+j*dstd)=t; cprodG_d(svd,i, j, g.c, g.s); } static void csvdStep2_d(csvdObj_d *svd) /* save U */ { vsip_vview_d *d = &svd->ds; vsip_vview_d *f = &svd->fs; givensObj_d g; vsip_length n = d->length; vsip_scalar_d mu=0.0, x1=0.0, x2=0.0; vsip_scalar_d t=0.0; vsip_index i,j,k; vsip_scalar_d d2=0.0,f1=0.0,d3=0.0,f2=0.0; vsip_scalar_d *fptr,*dptr,*tdptr,*tfptr; vsip_stride fstd=f->stride*f->block->rstride, dstd=d->stride*d->block->rstride; dptr=d->block->array+d->offset*d->block->rstride; fptr=f->block->array+f->offset*f->block->rstride; if(n >= 3){ d2=*(dptr+dstd*(n-2));f1= *(fptr+fstd*(n-3));d3 = *(dptr+dstd*(n-1));f2= *(fptr+fstd*(n-2)); } else if(n == 2){ d2=*dptr; d3=*(dptr+dstd); f1=0; f2=*fptr; } else { printf("should not be here (see svdStep_d"); exit(-1); } mu = svdMu_d(d2,f1,d3,&f2,svd->eps0); if(f2 == 0.0) *(fptr+fstd*(n-2)) = 0.0; x1=*dptr; x2 = x1 * *fptr; x1 *= x1; x1 -= mu; g=givensCoef_d(x1,x2); x1=*dptr;x2=*fptr; *fptr=g.c * x2 - g.s * x1; *dptr=x1 * g.c + x2 * g.s; tdptr=dptr+dstd; t=*tdptr; *tdptr=t*g.c; t*=g.s; for(i=0; i<n-2; i++){ j=i+1; k=i+2; tdptr=dptr+i*dstd; tfptr=fptr+i*fstd; g = givensCoef_d(*tdptr,t); *tdptr=g.r; x1 = *(tdptr+dstd)*g.c; x2=*tfptr*g.s; t= x1 - x2; x1=*(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s ; *(fptr+i*fstd)= x1+x2; *(dptr+j*dstd) = t; x1=*(fptr+j*fstd); t=g.s * x1; *(fptr+j*fstd) = x1*g.c; cprodG_d(svd,i, j, g.c, g.s); g=givensCoef_d(*(fptr+i*fstd),t); *(fptr+i*fstd)=g.r; x1=*(dptr+j*dstd); x2=*(fptr+j*fstd); *(dptr+j*dstd)=g.c * x1 + g.s * x2; *(fptr+j*fstd)=g.c * x2 - g.s * x1; x1=*(dptr+k*dstd); t=g.s * x1; *(dptr+k*dstd)=x1*g.c; } i=n-2; j=n-1; g = givensCoef_d(*(dptr+i*dstd),t); *(dptr+i*dstd)=g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t=x1 - x2; x1 = *(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s; *(fptr+i*fstd)=x1+x2; *(dptr+j*dstd)=t; cprodG_d(svd,i, j, g.c, g.s); } static void csvdStep1_d(csvdObj_d *svd) /* save V */ { vsip_vview_d *d = &svd->ds; vsip_vview_d *f = &svd->fs; givensObj_d g; vsip_length n = d->length; vsip_scalar_d mu=0.0, x1=0.0, x2=0.0; vsip_scalar_d t=0.0; vsip_index i,j,k; vsip_scalar_d d2=0.0,f1=0.0,d3=0.0,f2=0.0; vsip_scalar_d *fptr,*dptr,*tdptr,*tfptr; vsip_stride fstd=f->stride*f->block->rstride, dstd=d->stride*d->block->rstride; dptr=d->block->array+d->offset*d->block->rstride; fptr=f->block->array+f->offset*f->block->rstride; if(n >= 3){ d2=*(dptr+dstd*(n-2));f1= *(fptr+fstd*(n-3));d3 = *(dptr+dstd*(n-1));f2= *(fptr+fstd*(n-2)); } else if(n == 2){ d2=*dptr; d3=*(dptr+dstd); f1=0; f2=*fptr; } else { printf("should not be here (see svdStep_d"); exit(-1); } mu = svdMu_d(d2,f1,d3,&f2,svd->eps0); if(f2 == 0.0) *(fptr+fstd*(n-2)) = 0.0; x1=*dptr; x2 = x1 * *fptr; x1 *= x1; x1 -= mu; g=givensCoef_d(x1,x2); x1=*dptr;x2=*fptr; *fptr=g.c * x2 - g.s * x1; *dptr=x1 * g.c + x2 * g.s; tdptr=dptr+dstd; t=*tdptr; *tdptr=t*g.c; t*=g.s; cgtProd_d(0,1,g.c,g.s,svd); for(i=0; i<n-2; i++){ j=i+1; k=i+2; tdptr=dptr+i*dstd; tfptr=fptr+i*fstd; g = givensCoef_d(*tdptr,t); *tdptr=g.r; x1 = *(tdptr+dstd)*g.c; x2=*tfptr*g.s; t= x1 - x2; x1=*(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s ; *(fptr+i*fstd)= x1+x2; *(dptr+j*dstd) = t; x1=*(fptr+j*fstd); t=g.s * x1; *(fptr+j*fstd) = x1*g.c; g=givensCoef_d(*(fptr+i*fstd),t); *(fptr+i*fstd)=g.r; x1=*(dptr+j*dstd); x2=*(fptr+j*fstd); *(dptr+j*dstd)=g.c * x1 + g.s * x2; *(fptr+j*fstd)=g.c * x2 - g.s * x1; x1=*(dptr+k*dstd); t=g.s * x1; *(dptr+k*dstd)=x1*g.c; cgtProd_d(j,k, g.c, g.s,svd); } i=n-2; j=n-1; g = givensCoef_d(*(dptr+i*dstd),t); *(dptr+i*dstd)=g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t=x1 - x2; x1 = *(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s; *(fptr+i*fstd)=x1+x2; *(dptr+j*dstd)=t; } static void svdFinalize_d(svdObj_d *s) { if(s) { vsip_valldestroy_d(s->t); vsip_valldestroy_d(s->w); vsip_malldestroy_d(s->R); vsip_malldestroy_d(s->L); vsip_valldestroy_vi(s->indx_L); vsip_valldestroy_vi(s->indx_R); vsip_valldestroy_d(s->d); vsip_valldestroy_d(s->f); free(s); } s=NULL; } static svdObj_d* svdInit_d(vsip_length m, vsip_length n,int Usave,int Vsave) { svdObj_d *s=malloc(sizeof(svdObj_d)); if(m < n){ printf("Column length must not be less than row length"); return NULL; } if(!s) { printf("\nfailed to allocate svd object\n"); return NULL; } s->init=0; if(!(s->t = vsip_vcreate_d(m,VSIP_MEM_NONE)))s->init++;else s->ts = *s->t; if(!(s->w = vsip_vcreate_d(m,VSIP_MEM_NONE)))s->init++; if(Usave){ if(Usave == 1 ){ if(!(s->L=vsip_mcreate_d(m,m,VSIP_ROW,VSIP_MEM_NONE)))s->init++; if(!(s->indx_L=vsip_vcreate_vi(n,VSIP_MEM_NONE))) s->init++; }else{ /* must be part */ if(!(s->L=vsip_mcreate_d(m,n,VSIP_ROW,VSIP_MEM_NONE)))s->init++; if(!(s->indx_L=vsip_vcreate_vi(n,VSIP_MEM_NONE))) s->init++; } } else { s->L=NULL; s->indx_L=NULL; } if(Vsave){ if(!(s->R=vsip_mcreate_d(n,n,VSIP_ROW,VSIP_MEM_NONE)))s->init++; if(!(s->indx_R=vsip_vcreate_vi(n,VSIP_MEM_NONE))) s->init++; } else { s->R=NULL; s->indx_R=NULL; } if(!(s->d = vsip_vcreate_d(n,VSIP_MEM_NONE)))s->init++; if(!(s->f = vsip_vcreate_d(n-1,VSIP_MEM_NONE)))s->init++; if(s->init){ svdFinalize_d(s); return NULL; } if(Usave) meye_d(s->L); if(Vsave) meye_d(s->R); return s; } static void svdBidiag_d(svdObj_d *svd) { svd->eps0=(mnormFro_d((&svd->B))/(vsip_scalar_d)svd->B.row_length)*EPS; bidiag_d(svd); UmatExtract_d(svd); VHmatExtract_d(svd); biDiagPhaseToZero_d(svd); } static void svdBidiag2_d(svdObj_d *svd) /* save U */ { svd->eps0=(mnormFro_d((&svd->B))/(vsip_scalar_d)svd->B.row_length)*EPS; bidiag_d(svd); UmatExtract_d(svd); biDiagPhaseToZero2_d(svd); } static void svdBidiag1_d(svdObj_d *svd) /* save V */ { svd->eps0=(mnormFro_d((&svd->B))/(vsip_scalar_d)svd->B.row_length)*EPS; bidiag_d(svd); VHmatExtract_d(svd); biDiagPhaseToZero1_d(svd); } static void svdBidiag0_d(svdObj_d *svd) { svd->eps0=(mnormFro_d(&svd->B)/(vsip_scalar_d)svd->B.row_length)*EPS; bidiag_d(svd); biDiagPhaseToZero0_d(svd); } static void svdIteration_d(svdObj_d* svd) { vsip_mview_d *L0 = svd->L; vsip_mview_d *L = &svd->Ls; vsip_vview_d *d0 = svd->d; vsip_vview_d *d = &svd->ds; vsip_vview_d *f0 = svd->f; vsip_vview_d *f = &svd->fs; vsip_mview_d *R0 = svd->R; vsip_mview_d *R= &svd->Rs; vsip_scalar_d eps0 = svd->eps0; vsip_length n; svdCorner cnr; vsip_index k; vsip_length cntr=0; vsip_length maxcntr=5*d0->length; *d=*d0;*f=*f0;*L=*L0; *R=*R0; while (cntr++ < maxcntr){ cnr=svdCorners_d(f0); if (cnr.j == 0) break; ivsv_d(d0,d,cnr.i,cnr.j); ivsv_d(f0,f,cnr.i,cnr.j-1); imsv_d(L0,L,0,0,cnr.i,cnr.j); imsv_d(R0,R,cnr.i,cnr.j,0,0); n=f->length; k=zeroFind_d(d,eps0); if (k > 0 ){ k=k-1; if(VI_VGET_F(d,n) == 0.0){ zeroCol_d(svd); }else{ imsv_d(L,L,0,0,k,0); d->length-=k+1; d->offset += k+1; f->length -= k; f->offset += k; zeroRow_d(svd); } }else{ svdStep_d(svd); } phaseCheck_d(svd); } } static void svdIteration2_d(svdObj_d* svd) /* save U */ { vsip_mview_d *L0 = svd->L; vsip_mview_d *L = &svd->Ls; vsip_vview_d *d0 = svd->d; vsip_vview_d *d = &svd->ds; vsip_vview_d *f0 = svd->f; vsip_vview_d *f = &svd->fs; vsip_scalar_d eps0 = svd->eps0; vsip_length n; svdCorner cnr; vsip_index k; vsip_length cntr=0; vsip_length maxcntr=5*d0->length; *d=*d0;*f=*f0;*L=*L0; while (cntr++ < maxcntr){ cnr=svdCorners_d(f0); if (cnr.j == 0) break; ivsv_d(d0,d,cnr.i,cnr.j); ivsv_d(f0,f,cnr.i,cnr.j-1); imsv_d(L0,L,0,0,cnr.i,cnr.j); n=f->length; k=zeroFind_d(d,eps0); if (k > 0 ){ k=k-1; if(VI_VGET_F(d,n) == 0.0){ zeroCol2_d(svd); }else{ imsv_d(L,L,0,0,k,0); d->length-=k+1; d->offset += k+1; f->length -= k; f->offset += k; zeroRow2_d(svd); } }else{ svdStep2_d(svd); } phaseCheck2_d(svd); } } static void svdIteration1_d(svdObj_d* svd) /* save V */ { vsip_vview_d *d0 = svd->d; vsip_vview_d *d = &svd->ds; vsip_vview_d *f0 = svd->f; vsip_vview_d *f = &svd->fs; vsip_mview_d *R0 = svd->R; vsip_mview_d *R= &svd->Rs; vsip_scalar_d eps0 = svd->eps0; vsip_length n; svdCorner cnr; vsip_index k; vsip_length cntr=0; vsip_length maxcntr=5*d0->length; *d=*d0;*f=*f0; *R=*R0; while (cntr++ < maxcntr){ cnr=svdCorners_d(f0); if (cnr.j == 0) break; ivsv_d(d0,d,cnr.i,cnr.j); ivsv_d(f0,f,cnr.i,cnr.j-1); imsv_d(R0,R,cnr.i,cnr.j,0,0); n=f->length; k=zeroFind_d(d,eps0); if (k > 0 ){ k=k-1; if(VI_VGET_F(d,n) == 0.0){ zeroCol1_d(svd); }else{ d->length-=k+1; d->offset += k+1; f->length -= k; f->offset += k; zeroRow1_d(svd); } }else{ svdStep1_d(svd); } phaseCheck1_d(svd); } } static void svdIteration0_d(svdObj_d* svd) { vsip_vview_d *d0 = svd->d; vsip_vview_d *d = &svd->ds; vsip_vview_d *f0 = svd->f; vsip_vview_d *f = &svd->fs; vsip_scalar_d eps0 = svd->eps0; vsip_length n; svdCorner cnr; vsip_index k; vsip_length cntr=0; vsip_length maxcntr=5*d0->length; *d=*d0;*f=*f0; while (cntr++ < maxcntr){ cnr=svdCorners_d(f0); if (cnr.j == 0) break; ivsv_d(d0,d,cnr.i,cnr.j); ivsv_d(f0,f,cnr.i,cnr.j-1); n=f->length; k=zeroFind_d(d,eps0); if (k > 0 ){ k=k-1; if(VI_VGET_F(d,n) == 0.0){ zeroCol0_d(svd); }else{ d->length-=k+1; d->offset += k+1; f->length -= k; f->offset += k; zeroRow0_d(svd); } }else{ svdStep0_d(svd); } phaseCheck0_d(svd); } } static void svdSort_d(svdObj_d *svd) { vsip_vview_d *d = svd->d; vsip_length n=d->length; vsip_vview_vi* indx_L = svd->indx_L; vsip_vview_vi* indx_R = svd->indx_R; vsip_mview_d *L0 = svd->L; vsip_mview_d *L=&svd->Ls; vsip_mview_d *R0 = svd->R; vsip_vsortip_d(d,VSIP_SORT_BYVALUE,VSIP_SORT_DESCENDING,VSIP_TRUE,indx_L); vcopy_vi(indx_L,indx_R); imsv_d( L0, L, 0,0, 0, n); mpermute_onceCol_d(L,indx_L); mpermute_onceRow_d(R0,indx_R); } static void svdSort2_d(svdObj_d *svd) /* save U */ { vsip_vview_d *d = svd->d; vsip_length n=d->length; vsip_vview_vi* indx_L = svd->indx_L; vsip_mview_d *L0 = svd->L; vsip_mview_d *L=&svd->Ls; vsip_vsortip_d(d,VSIP_SORT_BYVALUE,VSIP_SORT_DESCENDING,VSIP_TRUE,indx_L); imsv_d( L0, L, 0,0, 0, n); mpermute_onceCol_d(L,indx_L); } static void svdSort1_d(svdObj_d *svd) /* save V */ { vsip_vview_d *d = svd->d; vsip_vview_vi* indx_R = svd->indx_R; vsip_mview_d *R0 = svd->R; vsip_vsortip_d(d,VSIP_SORT_BYVALUE,VSIP_SORT_DESCENDING,VSIP_TRUE,indx_R); mpermute_onceRow_d(R0,indx_R); } static void svdSort0_d(svdObj_d *svd) { vsip_vview_d *d = svd->d; vsip_vsortip_d(d,VSIP_SORT_BYVALUE,VSIP_SORT_DESCENDING,VSIP_FALSE,NULL); } static void svd_d(svdObj_d *s,int Usave, int Vsave) { if(Usave && Vsave){ svdBidiag_d(s); svdIteration_d(s); svdSort_d(s); }else if(Usave){ svdBidiag2_d(s); svdIteration2_d(s); svdSort2_d(s); }else if (Vsave){ svdBidiag1_d(s); svdIteration1_d(s); svdSort1_d(s); }else{ svdBidiag0_d(s); svdIteration0_d(s); svdSort0_d(s); } } static void csvdFinalize_d(csvdObj_d *s) { if(s) { vsip_cvalldestroy_d((s)->t); vsip_cvalldestroy_d((s)->w); vsip_cmalldestroy_d((s)->R); vsip_cmalldestroy_d((s)->L); vsip_valldestroy_vi((s)->indx_L); vsip_valldestroy_vi((s)->indx_R); vsip_valldestroy_d((s)->d); vsip_valldestroy_d((s)->f); free(s); } s=NULL; } static csvdObj_d* csvdInit_d(vsip_length m, vsip_length n,int Usave,int Vsave) { csvdObj_d *s=malloc(sizeof(csvdObj_d)); if(m < n){ printf("Column length must not be less than row length"); return NULL; } if(!s) { printf("\nfailed to allocate svd object\n"); return NULL; } s->init=0; if(!(s->t = vsip_cvcreate_d(m,VSIP_MEM_NONE)))s->init++;else s->ts = *s->t; if(!(s->w = vsip_cvcreate_d(m,VSIP_MEM_NONE)))s->init++; if(Usave){ if(Usave == 1 ){ if(!(s->L=vsip_cmcreate_d(m,m,VSIP_ROW,VSIP_MEM_NONE)))s->init++; if(!(s->indx_L=vsip_vcreate_vi(n,VSIP_MEM_NONE))) s->init++; }else{ /* must be part */ if(!(s->L=vsip_cmcreate_d(m,n,VSIP_ROW,VSIP_MEM_NONE)))s->init++; if(!(s->indx_L=vsip_vcreate_vi(n,VSIP_MEM_NONE))) s->init++; } } else { s->L=NULL; s->indx_L=NULL; } if(Vsave){ if(!(s->R=vsip_cmcreate_d(n,n,VSIP_ROW,VSIP_MEM_NONE)))s->init++; if(!(s->indx_R=vsip_vcreate_vi(n,VSIP_MEM_NONE))) s->init++; } else { s->R=NULL; s->indx_R=NULL; } if(!(s->d = vsip_vcreate_d(n,VSIP_MEM_NONE)))s->init++; if(!(s->f = vsip_vcreate_d(n-1,VSIP_MEM_NONE)))s->init++; if(s->init){ csvdFinalize_d(s); return NULL; } if(Usave) cmeye_d(s->L); if(Vsave) cmeye_d(s->R); return s; } static void csvdBidiag_d(csvdObj_d *svd) { svd->eps0=cmnormFro_d(&svd->B)/(vsip_scalar_d)(svd->B.row_length) * EPS; cbidiag_d(svd); cUmatExtract_d(svd); cVHmatExtract_d(svd); cbiDiagPhaseToZero_d(svd); vreal_sv_d(cdiag_sv_d(&svd->B, &svd->bs, 0),(&svd->rbs)); vcopy_d((&svd->rbs),svd->d); vreal_sv_d(cdiag_sv_d(&svd->B, &svd->bs, 1),(&svd->rbs)); vcopy_d((&svd->rbs),svd->f); } static void csvdBidiag2_d(csvdObj_d *svd) { svd->eps0=cmnormFro_d(&svd->B)/(vsip_scalar_d)(svd->B.row_length) * EPS; cbidiag_d(svd); cUmatExtract_d(svd); cbiDiagPhaseToZero2_d(svd); vreal_sv_d(cdiag_sv_d(&svd->B, &svd->bs, 0),(&svd->rbs)); vcopy_d((&svd->rbs),svd->d); vreal_sv_d(cdiag_sv_d(&svd->B, &svd->bs, 1),(&svd->rbs)); vcopy_d((&svd->rbs),svd->f); } static void csvdBidiag1_d(csvdObj_d *svd) { svd->eps0=cmnormFro_d(&svd->B)/(vsip_scalar_d)(svd->B.row_length) * EPS; cbidiag_d(svd); cVHmatExtract_d(svd); cbiDiagPhaseToZero1_d(svd); vreal_sv_d(cdiag_sv_d(&svd->B, &svd->bs, 0),(&svd->rbs)); vcopy_d((&svd->rbs),svd->d); vreal_sv_d(cdiag_sv_d(&svd->B, &svd->bs, 1),(&svd->rbs)); vcopy_d((&svd->rbs),svd->f); } static void csvdBidiag0_d(csvdObj_d *svd) { svd->eps0=cmnormFro_d(&svd->B)/(vsip_scalar_d)(svd->B.row_length) * EPS; cbidiag_d(svd); cbiDiagPhaseToZero0_d(svd); vreal_sv_d(cdiag_sv_d(&svd->B, &svd->bs, 0),(&svd->rbs)); vcopy_d((&svd->rbs),svd->d); vreal_sv_d(cdiag_sv_d(&svd->B, &svd->bs, 1),(&svd->rbs)); vcopy_d((&svd->rbs),svd->f); } static void csvdIteration_d(csvdObj_d *svd) { vsip_cmview_d *L0 = svd->L; vsip_vview_d *d0 = svd->d; vsip_vview_d *f0 = svd->f; vsip_cmview_d *R0 = svd->R; vsip_scalar_d eps0 = svd->eps0; vsip_vview_d *d=&svd->ds; vsip_vview_d *f=&svd->fs; vsip_cmview_d *L=&svd->Ls; vsip_cmview_d *R=&svd->Rs; vsip_length n; svdCorner cnr; vsip_index k; vsip_length cntr=0; vsip_length maxcntr=5*d0->length; *d=*d0;*f=*f0;*L=*L0; *R=*R0; while (cntr++ < maxcntr){ cnr=svdCorners_d(f0); if (cnr.j == 0) break; ivsv_d(d0,d,cnr.i,cnr.j); ivsv_d(f0,f,cnr.i,cnr.j-1); cimsv_d(L0,L,0,0,cnr.i,cnr.j); cimsv_d(R0,R,cnr.i,cnr.j,0,0); n=f->length; k=zeroFind_d(d,eps0); if (k > 0){ k=k-1; if(VI_VGET_F(d,n) == 0.0){ czeroCol_d(svd); }else{ cimsv_d(L,L,0,0,k,0); d->length-=(k+1); d->offset += (k+1); f->length -= k; f->offset += k; czeroRow_d(svd); } }else{ csvdStep_d(svd); } cphaseCheck_d(svd); } } static void csvdIteration2_d(csvdObj_d *svd) /* save U */ { vsip_cmview_d *L0 = svd->L; vsip_vview_d *d0 = svd->d; vsip_vview_d *f0 = svd->f; vsip_scalar_d eps0 = svd->eps0; vsip_vview_d *d=&svd->ds; vsip_vview_d *f=&svd->fs; vsip_cmview_d *L=&svd->Ls; vsip_length n; svdCorner cnr; vsip_index k; vsip_length cntr=0; vsip_length maxcntr=5*d0->length; *d=*d0;*f=*f0;*L=*L0; while (cntr++ < maxcntr){ cnr=svdCorners_d(f0); if (cnr.j == 0) break; ivsv_d(d0,d,cnr.i,cnr.j); ivsv_d(f0,f,cnr.i,cnr.j-1); cimsv_d(L0,L,0,0,cnr.i,cnr.j); n=f->length; k=zeroFind_d(d,eps0); if (k > 0){ k=k-1; if(VI_VGET_F(d,n) == 0.0){ czeroCol2_d(svd); }else{ cimsv_d(L,L,0,0,k,0); d->length-=(k+1); d->offset += (k+1); f->length -= k; f->offset += k; czeroRow2_d(svd); } }else{ csvdStep2_d(svd); } cphaseCheck2_d(svd); } } static void csvdIteration1_d(csvdObj_d *svd) /* save V */ { vsip_vview_d *d0 = svd->d; vsip_vview_d *f0 = svd->f; vsip_cmview_d *R0 = svd->R; vsip_scalar_d eps0 = svd->eps0; vsip_vview_d *d=&svd->ds; vsip_vview_d *f=&svd->fs; vsip_cmview_d *R=&svd->Rs; vsip_length n; svdCorner cnr; vsip_index k; vsip_length cntr=0; vsip_length maxcntr=5*d0->length; *d=*d0;*f=*f0;*R=*R0; while (cntr++ < maxcntr){ cnr=svdCorners_d(f0); if (cnr.j == 0) break; ivsv_d(d0,d,cnr.i,cnr.j); ivsv_d(f0,f,cnr.i,cnr.j-1); cimsv_d(R0,R,cnr.i,cnr.j,0,0); n=f->length; k=zeroFind_d(d,eps0); if (k > 0){ k=k-1; if(VI_VGET_F(d,n) == 0.0){ czeroCol1_d(svd); }else{ d->length-=(k+1); d->offset += (k+1); f->length -= k; f->offset += k; czeroRow1_d(svd); } }else{ csvdStep1_d(svd); } cphaseCheck1_d(svd); } } static void csvdSort_d(csvdObj_d *svd) { vsip_cmview_d* L0 = svd->L; vsip_vview_d* d = svd->d; vsip_cmview_d* R0 = svd->R; vsip_length n=d->length; vsip_vview_vi* indx_L = svd->indx_L; vsip_vview_vi* indx_R = svd->indx_R; vsip_cmview_d *L=&svd->Ls; vsip_vsortip_d(d,VSIP_SORT_BYVALUE,VSIP_SORT_DESCENDING,VSIP_TRUE,indx_L); vcopy_vi(indx_L,indx_R); cimsv_d( L0, L, 0,0, 0, n); cmpermute_onceCol_d(L,indx_L); cmpermute_onceRow_d(R0,indx_R); } static void csvdSort2_d(csvdObj_d *svd) /* save U */ { vsip_cmview_d* L0 = svd->L; vsip_vview_d* d = svd->d; vsip_length n=d->length; vsip_vview_vi* indx_L = svd->indx_L; vsip_cmview_d *L=&svd->Ls; vsip_vsortip_d(d,VSIP_SORT_BYVALUE,VSIP_SORT_DESCENDING,VSIP_TRUE,indx_L); cimsv_d( L0, L, 0,0, 0, n); cmpermute_onceCol_d(L,indx_L); } static void csvdSort1_d(csvdObj_d *svd) /* save V */ { vsip_vview_d* d = svd->d; vsip_cmview_d* R0 = svd->R; vsip_vview_vi* indx_R = svd->indx_R; vsip_vsortip_d(d,VSIP_SORT_BYVALUE,VSIP_SORT_DESCENDING,VSIP_TRUE,indx_R); cmpermute_onceRow_d(R0,indx_R); } static void csvd_d(csvdObj_d *s,int Usave,int Vsave) { if(Usave && Vsave){ csvdBidiag_d(s); csvdIteration_d(s); csvdSort_d(s); }else if(Usave){ csvdBidiag2_d(s); csvdIteration2_d(s); csvdSort2_d(s); }else if (Vsave){ csvdBidiag1_d(s); csvdIteration1_d(s); csvdSort1_d(s); }else{ svdObj_d t; csvdBidiag0_d(s); /* after bidiag this path same as real */ t.eps0=s->eps0; t.d=s->d;t.ds=s->ds;t.f=s->f;t.fs=s->fs; svdIteration0_d(&t); svdSort0_d(&t); } } /* Real */ int vsip_svd_destroy_d(vsip_sv_d* s) { if(s){ svdObj_d* svd=(svdObj_d*)s->svd; svdFinalize_d(svd); free((void*)s); s=NULL; } return 0; } vsip_sv_d * vsip_svd_create_d(vsip_length M, vsip_length N, vsip_svd_uv Usave, vsip_svd_uv Vsave) { vsip_sv_d *s = (vsip_sv_d*) malloc(sizeof(vsip_sv_d)); if(s){ if(M < N){ s->svd = (void*) svdInit_d(N,M,Vsave,Usave); }else{ s->svd = (void*) svdInit_d(M,N,Usave,Vsave); } if(s->svd){ s->attr.Usave=Usave; s->attr.Vsave=Vsave; s->attr.m=M; s->attr.n=N; s->transpose = M < N ? 1:0; } else { vsip_svd_destroy_d(s); } } return s; } int vsip_svd_d(vsip_sv_d *svd, const vsip_mview_d *A, vsip_vview_d *sv) { svdObj_d *s = (svdObj_d*) svd->svd; if(svd->transpose){ s->B = *A; s->B.col_length=A->row_length; s->B.row_length=A->col_length; s->B.col_stride=A->row_stride; s->B.row_stride=A->col_stride; } else { s->B=*A; } if(svd->transpose){ svd_d(s,svd->attr.Vsave,svd->attr.Usave); } else { svd_d(s,svd->attr.Usave,svd->attr.Vsave); } vcopy_d(s->d,sv) return 0; } void vsip_svd_getattr_d(const vsip_sv_d *svd, vsip_sv_attr_d *attrib) { attrib->Usave = svd->attr.Usave; attrib->Vsave = svd->attr.Vsave; attrib->m = svd->attr.m; attrib->n = svd->attr.n; } int vsip_svdmatu_d(const vsip_sv_d *svd, vsip_scalar_vi low, vsip_scalar_vi high, const vsip_mview_d *C) { svdObj_d *s = (svdObj_d*) svd->svd; sv_attr attr = svd->attr; int retval = 0; if(attr.Usave){ if(svd->transpose){ vsip_mview_d *L = s->R; vsip_mview_d *Ls = &s->Rs; Ls->offset=L->offset + L->col_stride * low; Ls->row_stride=L->col_stride; Ls->col_stride=L->row_stride; Ls->row_length = (high-low) + 1; Ls->col_length=L->row_length; mcopy_d(Ls,C); } else { vsip_mview_d *L = s->L; vsip_mview_d *Ls = &s->Ls; Ls->offset = L->offset + L->row_stride * low; Ls->row_length = (high-low) + 1; Ls->col_length = L->col_length; Ls->row_stride = L->row_stride; Ls->col_stride = L->col_stride; mcopy_d(Ls,C); } } else { retval = 1; } return retval; } int vsip_svdmatv_d(const vsip_sv_d *svd, vsip_scalar_vi low, vsip_scalar_vi high, const vsip_mview_d *C) { svdObj_d *s = (svdObj_d*) svd->svd; sv_attr attr = svd->attr; int retval = 0; if(attr.Vsave){ if(svd->transpose){ vsip_mview_d *R = s->L; vsip_mview_d *Rs = &s->Ls; *Rs=*R; Rs->offset += Rs->row_stride * low; Rs->row_length = (high-low) + 1; mcopy_d(Rs,C); } else { vsip_mview_d *R = s->R; vsip_mview_d *Rs = &s->Rs; Rs->offset=R->offset; Rs->row_stride=R->col_stride; Rs->col_stride=R->row_stride; Rs->row_length=R->col_length; Rs->col_length=R->row_length; Rs->offset += Rs->row_stride * low; Rs->row_length = (high-low) + 1; mcopy_d(Rs,C); } } else { retval = 1; } return retval; } int vsip_svdprodu_d(const vsip_sv_d *svd, vsip_mat_op OpU, vsip_mat_side ApU, const vsip_mview_d *In) { svdObj_d* svdObj=(svdObj_d*)svd->svd; vsip_mview_d c = *In; vsip_mview_d C = *In; vsip_index i; vsip_vview_d y; vsip_mview_d U; if(svd->attr.Usave == VSIP_SVD_UVNOS) return 1; if((OpU != VSIP_MAT_NTRANS) && (OpU != VSIP_MAT_TRANS)) return 2; if( (ApU != VSIP_MAT_LSIDE) && (ApU != VSIP_MAT_RSIDE)) return 3; if(svd->transpose){ U = *(svdObj->R); U.row_stride = svdObj->R->col_stride; U.col_stride=svdObj->R->row_stride; U.row_length = svdObj->R->col_length; U.col_length=svdObj->R->row_length; } else { U = *(svdObj->L); } /* UVPART and UVFULL operate the same */ if (ApU == VSIP_MAT_LSIDE){ if(OpU == VSIP_MAT_NTRANS){ vsip_vview_d x = *(svdObj->w); x.offset=0;x.length=U.col_length;x.stride=1; c.col_length=U.col_length; for(i=0; i<c.row_length; i++){ mvprod_d(&U,col_sv_d(&C,&y,i),&x); vcopy_d(&x,col_sv_d(&c,&y,i)) } } else { /* must be TRANS */ vsip_vview_d x = *(svdObj->w); vsip_length rl=U.row_length; vsip_stride rs=U.row_stride; U.row_length = U.col_length; U.col_length = rl; U.row_stride = U.col_stride; U.col_stride = rs; x.offset=0;x.length=U.col_length;x.stride=1; c.col_length=U.col_length; for(i=0; i<c.row_length; i++){ mvprod_d(&U,col_sv_d(&C,&y,i),&x); vcopy_d(&x,col_sv_d(&c,&y,i)) } } } else { /* must be MAT_RSIDE */ if(OpU == VSIP_MAT_NTRANS){ vsip_vview_d x = *(svdObj->w); x.offset=0;x.length=U.row_length;x.stride=1; c.row_length = U.row_length; for(i=0; i<c.col_length; i++){ vmprod_d(row_sv_d(&C,&y,i),&U,&x); vcopy_d(&x,row_sv_d(&c,&y,i)) } } else { vsip_vview_d x = *(svdObj->w); vsip_length rl=U.row_length; vsip_stride rs=U.row_stride; U.row_length = U.col_length; U.col_length = rl; U.row_stride = U.col_stride; U.col_stride = rs; x.offset=0;x.length=U.row_length;x.stride=1; c.row_length=U.row_length; for(i=0; i<c.col_length; i++){ vmprod_d(row_sv_d(&C,&y,i),&U,&x); vcopy_d(&x,row_sv_d(&c,&y,i)) } } } return 0; } int vsip_svdprodv_d(const vsip_sv_d *svd, vsip_mat_op OpV, vsip_mat_side ApV,const vsip_mview_d *In) { svdObj_d* svdObj=(svdObj_d*)svd->svd; vsip_mview_d c = *In; vsip_mview_d C = *In; vsip_index i; vsip_vview_d y; vsip_mview_d V; if(svd->attr.Vsave == VSIP_SVD_UVNOS) return 1; if((OpV != VSIP_MAT_NTRANS) && (OpV != VSIP_MAT_TRANS)) return 2; if( (ApV != VSIP_MAT_LSIDE) && (ApV != VSIP_MAT_RSIDE)) return 3; if(svd->transpose){ V = *(svdObj->L); } else { V = *(svdObj->R); V.row_stride = svdObj->R->col_stride; V.col_stride=svdObj->R->row_stride; V.row_length = svdObj->R->col_length; V.col_length=svdObj->R->row_length; } /* UVPART and UVFULL operate the same */ if (ApV == VSIP_MAT_LSIDE){ if(OpV == VSIP_MAT_NTRANS){ vsip_vview_d x = *(svdObj->w); x.offset=0;x.length=V.row_length;x.stride=1; c.col_length=V.col_length; for(i=0; i<c.row_length; i++){ mvprod_d(&V,col_sv_d(&C,&y,i),&x); vcopy_d(&x,col_sv_d(&c,&y,i)) } } else { /* must be TRANS */ vsip_vview_d x = *(svdObj->w); vsip_length rl=V.row_length; vsip_stride rs=V.row_stride; V.row_length = V.col_length; V.col_length = rl; V.row_stride = V.col_stride; V.col_stride = rs; x.offset=0;x.length=V.col_length;x.stride=1; c.col_length=V.col_length; for(i=0; i<c.row_length; i++){ mvprod_d(&V,col_sv_d(&C,&y,i),&x); vcopy_d(&x,col_sv_d(&c,&y,i)) } } } else { /* must be MAT_RSIDE */ if(OpV == VSIP_MAT_NTRANS){ vsip_vview_d x = *(svdObj->w); x.offset=0;x.length=V.row_length;x.stride=1; c.row_length = V.row_length; for(i=0; i<c.col_length; i++){ vmprod_d(row_sv_d(&C,&y,i),&V,&x); vcopy_d(&x,row_sv_d(&c,&y,i)) } } else { vsip_vview_d x = *(svdObj->w); vsip_length rl=V.row_length; vsip_stride rs=V.row_stride; V.row_length = V.col_length; V.col_length = rl; V.row_stride = V.col_stride; V.col_stride = rs; x.offset=0;x.length=V.row_length;x.stride=1; c.row_length=V.row_length; for(i=0; i<c.col_length; i++){ vmprod_d(row_sv_d(&C,&y,i),&V,&x); vcopy_d(&x,row_sv_d(&c,&y,i)) } } } return 0; } /* Complex */ int vsip_csvd_destroy_d(vsip_csv_d* s) { if(s){ csvdObj_d* svd=(csvdObj_d*)s->svd; csvdFinalize_d(svd); s->svd=NULL; free((void*)s); s=NULL; } return 0; } vsip_csv_d * vsip_csvd_create_d(vsip_length M, vsip_length N, vsip_svd_uv Usave, vsip_svd_uv Vsave) { vsip_csv_d *s = (vsip_csv_d*) malloc(sizeof(vsip_csv_d)); if(s){ if(M < N){ s->svd = (void*) csvdInit_d(N,M,Vsave,Usave); }else{ s->svd = (void*)csvdInit_d(M,N,Usave,Vsave); } if(s->svd){ s->attr.Usave=Usave; s->attr.Vsave=Vsave; s->attr.m=M; s->attr.n=N; s->transpose = M < N ? 1:0; } else { vsip_svd_destroy_d(s); s=NULL; } } return s; } int vsip_csvd_d(vsip_csv_d *svd, const vsip_cmview_d *A, vsip_vview_d *sv) { csvdObj_d *s = (csvdObj_d*) svd->svd; if(svd->transpose){ s->B=*A; s->B.row_length=A->col_length; s->B.col_length=A->row_length; s->B.row_stride=A->col_stride; s->B.col_stride=A->row_stride; cmconj_d(A, A); } else { s->B=*A; } if(svd->transpose){ csvd_d(s,svd->attr.Vsave,svd->attr.Usave); } else { csvd_d(s,svd->attr.Usave,svd->attr.Vsave); } vcopy_d(s->d,sv); return 0; } void vsip_csvd_getattr_d(const vsip_csv_d *svd, vsip_csv_attr_d *attrib) { attrib->Usave = svd->attr.Usave; attrib->Vsave = svd->attr.Vsave; attrib->m = svd->attr.m; attrib->n = svd->attr.n; } int vsip_csvdmatu_d(const vsip_csv_d *svd, vsip_scalar_vi low, vsip_scalar_vi high, const vsip_cmview_d *C) { csvdObj_d *s = (csvdObj_d*) svd->svd; sv_attr attr = svd->attr; int retval = 0; if(attr.Usave){ if(svd->transpose){ vsip_cmview_d *L = s->R; vsip_cmview_d *Ls = &s->Rs; Ls->offset=L->offset + L->col_stride * low; Ls->row_stride=L->col_stride; Ls->col_stride=L->row_stride; Ls->row_length = (high-low) + 1; Ls->col_length=L->row_length; cmconj_d(Ls,C); } else { vsip_cmview_d *L = s->L; vsip_cmview_d *Ls = &s->Ls; Ls->offset = L->offset + L->row_stride * low; Ls->row_length = (high-low) + 1; Ls->row_stride = L->row_stride; Ls->col_length = L->col_length; Ls->col_stride = L->col_stride; cmcopy_d(Ls,C); } } else { retval = 1; } return retval; } int vsip_csvdmatv_d(const vsip_csv_d *svd, vsip_scalar_vi low, vsip_scalar_vi high, const vsip_cmview_d *C) { csvdObj_d *s = (csvdObj_d*) svd->svd; sv_attr attr = svd->attr; int retval = 0; if(attr.Vsave){ if(svd->transpose){ vsip_cmview_d *R = s->L; vsip_cmview_d *Rs = &s->Ls; *Rs=*R; Rs->offset += Rs->row_stride * low; Rs->row_length = (high-low) + 1; cmcopy_d(Rs,C); } else { vsip_cmview_d *R = s->R; vsip_cmview_d *Rs = &s->Rs; Rs->offset=R->offset; Rs->row_stride=R->col_stride; Rs->col_stride=R->row_stride; Rs->row_length=R->col_length; Rs->col_length=R->row_length; Rs->offset += Rs->row_stride * low; Rs->row_length = (high-low) + 1; cmconj_d(Rs,C); } } else { retval = 1; } return retval; } int vsip_csvdprodu_d(const vsip_csv_d *svd, vsip_mat_op OpU, vsip_mat_side ApU, const vsip_cmview_d *In) { csvdObj_d* svdObj=(csvdObj_d*)svd->svd; vsip_cmview_d c = *In; vsip_cmview_d C = *In; vsip_index i; vsip_cvview_d y; vsip_cmview_d U; if(svd->attr.Usave == VSIP_SVD_UVNOS) return 1; if((OpU != VSIP_MAT_NTRANS) && (OpU != VSIP_MAT_HERM)) return 2; if( (ApU != VSIP_MAT_LSIDE) && (ApU != VSIP_MAT_RSIDE)) return 3; if(svd->transpose){ U = *(svdObj->R); U.row_stride = svdObj->R->col_stride; U.col_stride=svdObj->R->row_stride; U.row_length = svdObj->R->col_length; U.col_length=svdObj->R->row_length; } else { U = *(svdObj->L); } /* UVPART and UVFULL operate the same */ if (ApU == VSIP_MAT_LSIDE){ if(OpU == VSIP_MAT_NTRANS){ vsip_cvview_d *x = svdObj->w; x->offset=0;x->length=U.col_length;x->stride=1; c.col_length=U.col_length; for(i=0; i<c.row_length; i++){ cmvprod_d(&U,ccol_sv_d(&C,&y,i),x); cvcopy_d(x,ccol_sv_d(&c,&y,i)) } if(svd->transpose) cmconj_d(&c,&c); } else { /* must be HERM */ vsip_cvview_d *x = svdObj->w; vsip_length rl=U.row_length; vsip_stride rs=U.row_stride; U.row_length = U.col_length; U.col_length = rl; U.row_stride = U.col_stride; U.col_stride = rs; x->offset=0;x->length=U.col_length;x->stride=1; c.col_length=U.col_length; if(svd->transpose){ U = *(svdObj->R); for(i=0; i<c.row_length; i++){ cmvprod_d(&U,ccol_sv_d(&C,&y,i),x) cvcopy_d(x,ccol_sv_d(&c,&y,i)) } } else { for(i=0; i<c.row_length; i++){ cmvjprod_d(&U,ccol_sv_d(&C,&y,i),x) cvcopy_d(x,ccol_sv_d(&c,&y,i)) } } } } else { /* must be MAT_RSIDE */ if(OpU == VSIP_MAT_NTRANS){ vsip_cvview_d *x = svdObj->w; x->offset=0;x->length=U.row_length;x->stride=1; c.row_length = U.row_length; for(i=0; i<c.col_length; i++){ cvmprod_d(crow_sv_d(&C,&y,i),&U,x); cvcopy_d(x,crow_sv_d(&c,&y,i)) } if(svd->transpose) cmconj_d(&c,&c); } else {/* must be herm */ vsip_cvview_d *x = svdObj->w; vsip_length rl=U.row_length; vsip_stride rs=U.row_stride; U.row_length = U.col_length; U.col_length = rl; U.row_stride = U.col_stride; U.col_stride = rs; x->offset=0;x->length=U.row_length;x->stride=1; c.row_length=U.row_length; if(svd->transpose){ U = *(svdObj->R); for(i=0; i<c.row_length; i++){ cvmprod_d(crow_sv_d(&C,&y,i),&U,x) cvcopy_d(x,crow_sv_d(&c,&y,i)) } } else { for(i=0; i<c.col_length; i++){ cvmprodj_d(crow_sv_d(&C,&y,i),&U,x); cvcopy_d(x,crow_sv_d(&c,&y,i)) } } } } return 0; } int vsip_csvdprodv_d(const vsip_csv_d *svd, vsip_mat_op OpV, vsip_mat_side ApV,const vsip_cmview_d *In) { csvdObj_d* svdObj=(csvdObj_d*)svd->svd; vsip_cmview_d c = *In; vsip_cmview_d C = *In; vsip_index i; vsip_cvview_d y; vsip_cmview_d V; if(svd->attr.Vsave == VSIP_SVD_UVNOS) return 1; if((OpV != VSIP_MAT_NTRANS) && (OpV != VSIP_MAT_HERM)) return 2; if( (ApV != VSIP_MAT_LSIDE) && (ApV != VSIP_MAT_RSIDE)) return 3; if(svd->transpose){ V = *(svdObj->L); } else { V = *(svdObj->R); V.row_stride = svdObj->R->col_stride; V.col_stride=svdObj->R->row_stride; V.row_length = svdObj->R->col_length; V.col_length=svdObj->R->row_length; } /* UVPART and UVFULL operate the same */ if (ApV == VSIP_MAT_LSIDE){ if(OpV == VSIP_MAT_NTRANS){ vsip_cvview_d x = *(svdObj->w); x.offset=0;x.length=V.row_length;x.stride=1; c.col_length=V.col_length; for(i=0; i<c.row_length; i++){ if(svd->transpose) cmvprod_d(&V,ccol_sv_d(&C,&y,i),&x) else cmvjprod_d(&V,ccol_sv_d(&C,&y,i),&x) cvcopy_d(&x,ccol_sv_d(&c,&y,i)) } } else { /* must be HERM */ vsip_cvview_d x = *(svdObj->w); if(!svd->transpose) V=*(svdObj->R); else { vsip_length rl=V.row_length; vsip_stride rs=V.row_stride; V.row_length = V.col_length; V.col_length = rl; V.row_stride = V.col_stride; V.col_stride = rs; } x.offset=0;x.length=V.col_length;x.stride=1; c.col_length=V.col_length; for(i=0; i<c.row_length; i++){ if(!svd->transpose) cmvprod_d(&V,ccol_sv_d(&C,&y,i),&x) else cmvjprod_d(&V,ccol_sv_d(&C,&y,i),&x) cvcopy_d(&x,ccol_sv_d(&c,&y,i)) } } } else { /* must be MAT_RSIDE */ if(OpV == VSIP_MAT_NTRANS){ vsip_cvview_d x = *(svdObj->w); x.offset=0;x.length=V.row_length;x.stride=1; c.row_length = V.row_length; for(i=0; i<c.col_length; i++){ if(svd->transpose) cvmprod_d(crow_sv_d(&C,&y,i),&V,&x) else cvmprodj_d(crow_sv_d(&C,&y,i),&V,&x) cvcopy_d(&x,crow_sv_d(&c,&y,i)) } } else { /* must be HERM */ vsip_cvview_d x = *(svdObj->w); if(!svd->transpose) V=*(svdObj->R); else { vsip_length rl=V.row_length; vsip_stride rs=V.row_stride; V.row_length = V.col_length; V.col_length = rl; V.row_stride = V.col_stride; V.col_stride = rs; } x.offset=0;x.length=V.row_length;x.stride=1; c.row_length=V.row_length; for(i=0; i<c.col_length; i++){ if(!svd->transpose) cvmprod_d(crow_sv_d(&C,&y,i),&V,&x) else cvmprodj_d(crow_sv_d(&C,&y,i),&V,&x) cvcopy_d(&x,crow_sv_d(&c,&y,i)) } } } return 0; } <file_sep>/* Created R Judd */ /* Copyright (c) 2006 <NAME> */ /* MIT style license, see Copyright notice in top level directory */ /* $Id: llsqsol_f.h,v 1.1 2006/05/16 16:45:18 judd Exp $ */ #include"VU_mprintm_f.include" static int llsqsol_f(void) { vsip_mview_f *A = vsip_mcreate_f(10,6,VSIP_ROW,VSIP_MEM_NONE); vsip_vview_f *ad = vsip_mdiagview_f(A,0); vsip_vview_f *ac = vsip_mcolview_f(A,0); vsip_mview_f *AT = vsip_mtransview_f(A); vsip_mview_f *XB = vsip_mcreate_f(10,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *XBs = vsip_msubview_f(XB,0,0,6,3); vsip_vview_f *xbc = vsip_mcolview_f(XB,0); vsip_mview_f *B = vsip_mcreate_f(10,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *Bs = vsip_msubview_f(B,0,0,6,3); vsip_mview_f *X = vsip_mcreate_f(6,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *ATA = vsip_mcreate_f(6,6,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *ATXB = vsip_mcreate_f(6,3,VSIP_ROW,VSIP_MEM_NONE); int i; vsip_chol_f *chol = vsip_chold_create_f(VSIP_TR_LOW,6); vsip_block_f *ablock = vsip_blockcreate_f(500,VSIP_MEM_NONE); vsip_mview_f *A1 = vsip_mbind_f(ablock,200,-3,10,-31,6); vsip_mview_f *BX1 = vsip_mbind_f(ablock,203,8,10,2,3); vsip_mview_f *BX1s = vsip_msubview_f(BX1,0,0,6,3); vsip_mfill_f(0.0,A); vsip_mfill_f(0.0,XB); printf("********\nTEST covsol_f\n"); printf("\n Test vsip_covsol_f\n"); /* need to make up some data for A */ for(i=0; i<6; i++){ vsip_vputoffset_f(ac,i); vsip_vramp_f(-1.3,1.1,ac); } vsip_vramp_f(3,1.2,ad); /* need to make up some data for XB */ for(i=0; i<3; i++){ vsip_vputoffset_f(xbc,i); vsip_vramp_f(.1,(vsip_scalar_f)i/3.0,xbc); } /* square off A and XB for use with cholesky */ vsip_mprod_f(AT,A,ATA); vsip_mprod_f(AT,XB,ATXB); vsip_mcopy_f_f(ATXB, Bs); /* Copy the original data for use with non-simple matrix */ vsip_mcopy_f_f(XB,BX1); vsip_mcopy_f_f(A,A1); /* check input data */ printf("Input Data \n"); printf("A = ");VU_mprintm_f("4.2",A); printf("\nAT * A = ");VU_mprintm_f("4.2",ATA); printf("\nXB = ");VU_mprintm_f("4.2",XB); printf("\nAT * XB =");VU_mprintm_f("4.2",ATXB); /* slove using Cholesky and ATA matrix and Bs matrix */ printf("\nSolve using cholesky and ATA matrix \n (AT * A) X = B \nfor X"); vsip_chold_f(chol,ATA); vsip_cholsol_f(chol,Bs); printf("\nX = ");VU_mprintm_f("7.5",Bs); /* check */ printf("\ncheck"); /* the following Restores ATA but chol object is no longer correct */ vsip_mprod_f(AT,A,ATA); vsip_mprod_f(ATA,Bs,X); printf("\nATA * X ="); VU_mprintm_f("4.2",X); vsip_msub_f(ATXB,X,X); { float check = (float) vsip_msumval_f(X); if(fabs(check) < .0001) printf("check = %f\ncorrect\n",check); else printf("check = %f\nerror\n",check); } /* slove using llsqsol and A, XB matrix */ printf("\nSolve\n (AT * A) X = B \nfor X"); vsip_llsqsol_f(A,XB); printf("\nXBs = ");VU_mprintm_f("7.5",XBs); vsip_msub_f(Bs,XBs,X); { float check = (float) vsip_msumval_f(X); if(fabs(check) < .0001) printf("check = %f\ncorrect\n",check); else printf("check = %f\nerror\n",check); } /* slove using llsqsol and A1,BX1 inputs */ printf("\nSolve nonstandard stride _f \n (AT * A) X = B \nfor X"); vsip_llsqsol_f(A1,BX1); vsip_mcopy_f_f(BX1s,X); printf("\nX = ");VU_mprintm_f("7.5",X); vsip_msub_f(Bs,BX1s,X); { float check = (float) vsip_msumval_f(X); if(fabs(check) < .0001) printf("check = %f\ncorrect\n",check); else printf("check = %f\nerror\n",check); } vsip_mdestroy_f(A1); vsip_mdestroy_f(BX1); vsip_mdestroy_f(BX1s); vsip_blockdestroy_f(ablock); vsip_vdestroy_f(ad); vsip_vdestroy_f(ac); vsip_vdestroy_f(xbc); vsip_mdestroy_f(AT); vsip_malldestroy_f(A); vsip_mdestroy_f(XBs); vsip_malldestroy_f(XB); vsip_malldestroy_f(X); vsip_mdestroy_f(Bs); vsip_malldestroy_f(B); vsip_malldestroy_f(ATA); vsip_malldestroy_f(ATXB); vsip_chold_destroy_f(chol); return 0; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmexpoavg_f.h,v 2.0 2003/02/22 15:23:21 judd Exp $ */ #include"VU_cmprintm_f.include" static void cmexpoavg_f(void){ printf("\n******\nTEST cmexpoavg_f\n"); { vsip_scalar_f alpha = (vsip_scalar_f)(1.0/3.0); vsip_scalar_f data1[]= {1,.1, 2,.2, 3,.3, 4,-.1, 5,-.3, 6,-.4, 7,.8, 8,.9, 9,-1}; vsip_scalar_f data2[]= {2,.1, 3,.2, 4,.3, 6,-.1, 8,-.3, 6,-.6, 7,.7, 8,.5, 1,-1.3}; vsip_scalar_f data3[]= {0,.2, 3,.5, 3,.1, 2,-.1, 5,-.3, 6,-.4, 7,.8, 8,.9, 9,-1.5}; vsip_cmview_f *ans = vsip_cmcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *m1 = vsip_cmbind_f( vsip_cblockbind_f(data1,NDPTR_f,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_cmview_f *m2 = vsip_cmbind_f( vsip_cblockbind_f(data2,NDPTR_f,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_cmview_f *m3 = vsip_cmbind_f( vsip_cblockbind_f(data3,NDPTR_f,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_cmview_f *c = vsip_cmcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *chk = vsip_cmcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *chk_r = vsip_mrealview_f(chk); vsip_cblockadmit_f(vsip_cmgetblock_f(m1),VSIP_TRUE); vsip_cblockadmit_f(vsip_cmgetblock_f(m2),VSIP_TRUE); vsip_cblockadmit_f(vsip_cmgetblock_f(m3),VSIP_TRUE); printf("call vsip_cmexpoavg_f(alpha,b,c) three times\n"); printf("alpha = 1\n"); printf("first call b =\n");VU_cmprintm_f("8.6",m1); printf("alpha = 1/2\n"); printf("second call b =\n");VU_cmprintm_f("8.6",m2); printf("alpha = 1/3\n"); printf("third call b =\n");VU_cmprintm_f("8.6",m3); printf("c initialized to zero\n"); { vsip_mview_f *cr = vsip_mrealview_f(c); vsip_mview_f *ci = vsip_mimagview_f(c); vsip_mfill_f(0,cr); vsip_mfill_f(0,ci); vsip_mdestroy_f(cr); vsip_mdestroy_f(ci); } vsip_cmexpoavg_f(1.0,m1,c); vsip_cmexpoavg_f(.5,m2,c); vsip_cmexpoavg_f(1.0/3.0,m3,c); printf("after third call c =\n");VU_cmprintm_f("8.6",c); vsip_cmadd_f(m1,m2,ans); vsip_cmadd_f(m3,ans,ans); vsip_rscmmul_f(alpha,ans,ans); printf("\nright answer =\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(ans,c,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,0,2 * .0001,0,1,chk_r); if(fabs(vsip_msumval_f(chk_r)) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(m1); vsip_cmalldestroy_f(m2); vsip_cmalldestroy_f(m3); vsip_cmalldestroy_f(ans); vsip_cmalldestroy_f(c); vsip_mdestroy_f(chk_r); vsip_cmalldestroy_f(chk); } return; } <file_sep>CC=gcc INCLUDE=-I./ CFLAGS= -O3 -Wall -std=c89 -pedantic -arch x86_64 SOURCE:=$(wildcard *.c) OBJECTS:=$(patsubst %.c,%.o,$(SOURCE)) FUNC:=$(patsubst %.c,%(),$(SOURCE)) ARCHIVE=libvsip.a AR=ar -rcvs $(ARCHIVE):$(OBJECTS) $(AR) $(ARCHIVE) $(OBJECTS) %o: %c $(CC) $(CFLAGS) $(INCLUDE) -c $^ file1: echo $(SOURCE) > file1 clean: rm -f *.o cleanall: rm -f *.o $(ARCHIVE) <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: min_f.h,v 2.0 2003/02/22 15:23:18 judd Exp $ */ static void min_f(void){ printf("********\nTEST min_f\n"); { vsip_scalar_f x = 5; vsip_scalar_f y = -1; vsip_scalar_f a = -1; vsip_scalar_f b = vsip_min_f(x,y); printf(" %5.4f = vsip_min_f(%5.4f,%5.4f)\n",b,x,y); (fabs(a-b) > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); } { vsip_scalar_f x = -5; vsip_scalar_f y = -1; vsip_scalar_f a = -5; vsip_scalar_f b = vsip_min_f(x,y); printf(" %5.4f = vsip_min_f(%5.4f,%5.4f)\n",b,x,y); (fabs(a-b) > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); } { vsip_scalar_f x = -5; vsip_scalar_f y = 1; vsip_scalar_f a = -5; vsip_scalar_f b = vsip_min_f(x,y); printf(" %5.4f = vsip_min_f(%5.4f,%5.4f)\n",b,x,y); (fabs(a-b) > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); } { vsip_scalar_f x = 5; vsip_scalar_f y = 1; vsip_scalar_f a = 1; vsip_scalar_f b = vsip_min_f(x,y); printf(" %5.4f = vsip_min_f(%5.4f,%5.4f)\n",b,x,y); (fabs(a-b) > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); } return; } /* done */ <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmswap_f.h,v 2.0 2003/02/22 15:23:21 judd Exp $ */ #include"VU_cmprintm_f.include" static void cmswap_f(void){ printf("\n*******\nTEST cmswap_f\n\n"); { vsip_scalar_f data1_r[] = { -1, -2, 3, 4, -5, -6}; vsip_scalar_f data1_i[] = { 1, 2, -3, -4, 5, 6}; vsip_scalar_f data2 [] = { 10,20, 11,21, 12,22, 13,23, 14,24, 15,25}; vsip_cblock_f *block1 = vsip_cblockbind_f(data1_r,data1_i,6,VSIP_MEM_NONE); vsip_cblock_f *block2 = vsip_cblockbind_f(data2,NDPTR_f,6,VSIP_MEM_NONE); vsip_cmview_f *a = vsip_cmbind_f(block1,0,2,3,1,2); vsip_cmview_f *b = vsip_cmbind_f(block2,0,2,3,1,2); vsip_cmview_f *a1 = vsip_cmcreate_f(3,2,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(3,2,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *chk = vsip_cmcreate_f(3,2,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *chk_r = vsip_mrealview_f(chk); vsip_cblockadmit_f(block1,VSIP_TRUE); vsip_cblockadmit_f(block2,VSIP_TRUE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); printf("matrix a\n");VU_cmprintm_f("8.6",a); printf("matrix b\n");VU_cmprintm_f("8.6",b); printf("vsip_cmswap_f(a,b)\n"); vsip_cmswap_f(a,b); printf("matrix a\n");VU_cmprintm_f("8.6",a); printf("matrix b\n");VU_cmprintm_f("8.6",b); vsip_cmsub_f(a,b1,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error in matrix <a>\n"); else printf("<a> correct\n"); vsip_cmsub_f(b,a1,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error in matrix <b>\n"); else printf("<b> correct\n"); vsip_cmalldestroy_f(a); vsip_cmalldestroy_f(b); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_mdestroy_f(chk_r); vsip_cmalldestroy_f(chk); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mexpoavg_f.h,v 2.0 2003/02/22 15:23:24 judd Exp $ */ #include"VU_mprintm_f.include" static void mexpoavg_f(void){ printf("\n******\nTEST mexpoavg_f\n"); { vsip_scalar_f alpha = (vsip_scalar_f)(1.0/3.0); vsip_scalar_f data1[]= {1,.1, 2,.2, 3,.3, 4,-.1, 5,-.3, 6,-.4, 7,.8, 8,.9, 9,-1}; vsip_scalar_f data2[]= {2,.1, 3,.2, 4,.3, 6,-.1, 8,-.3, 6,-.6, 7,.7, 8,.5, 1,-1.3}; vsip_scalar_f data3[]= {0,.2, 3,.5, 3,.1, 2,-.1, 5,-.3, 6,-.4, 7,.8, 8,.9, 9,-1.5}; vsip_mview_f *ans = vsip_mcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *m1 = vsip_mbind_f( vsip_blockbind_f(data1,18,VSIP_MEM_NONE),0,3,3,1,3); vsip_mview_f *m2 = vsip_mbind_f( vsip_blockbind_f(data2,18,VSIP_MEM_NONE),1,4,3,1,3); vsip_mview_f *m3 = vsip_mbind_f( vsip_blockbind_f(data3,18,VSIP_MEM_NONE),3,1,3,3,3); vsip_mview_f *c = vsip_mcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *chk = vsip_mcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_f(vsip_mgetblock_f(m1),VSIP_TRUE); vsip_blockadmit_f(vsip_mgetblock_f(m2),VSIP_TRUE); vsip_blockadmit_f(vsip_mgetblock_f(m3),VSIP_TRUE); printf("call vsip_mexpoavg_f(alpha,b,c) three times\n"); printf("alpha = 1\n"); printf("first call b =\n");VU_mprintm_f("8.6",m1); printf("alpha = 1/2\n"); printf("second call b =\n");VU_mprintm_f("8.6",m2); printf("alpha = 1/3\n"); printf("third call b =\n");VU_mprintm_f("8.6",m3); printf("c initialized to zero\n"); vsip_mfill_f(0,c); vsip_mexpoavg_f(1.0,m1,c); vsip_mexpoavg_f(.5,m2,c); vsip_mexpoavg_f(1.0/3.0,m3,c); printf("after third call c =\n");VU_mprintm_f("8.6",c); vsip_madd_f(m1,m2,ans); vsip_madd_f(m3,ans,ans); vsip_smmul_f(alpha,ans,ans); printf("\nright answer =\n"); VU_mprintm_f("6.4",ans); vsip_msub_f(ans,c,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,0,2 * .0001,0,1,chk); if(fabs(vsip_msumval_f(chk)) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_f(m1); vsip_malldestroy_f(m2); vsip_malldestroy_f(m3); vsip_malldestroy_f(ans); vsip_malldestroy_f(c); vsip_malldestroy_f(chk); } return; } <file_sep>/* Created RJudd November 22, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vkron_d.c,v 2.0 2003/02/22 15:19:14 judd Exp $ */ #include"vsip.h" #include"vsip_vviewattributes_d.h" #include"vsip_mviewattributes_d.h" void vsip_vkron_d( vsip_scalar_d alpha, const vsip_vview_d *x, const vsip_vview_d *y, const vsip_mview_d *C) { vsip_scalar_d tmp; vsip_length n = x->length, m = y->length; vsip_scalar_d *x_p = x->block->array + x->offset * x->block->rstride; vsip_scalar_d *y_p = y->block->array + y->offset * y->block->rstride; vsip_scalar_d *yp0 = y_p; vsip_scalar_d *Cp0 = C->block->array + C->offset * C->block->rstride; vsip_scalar_d *C_p = Cp0; vsip_stride Crst = C->row_stride * C->block->rstride, Ccst = C->col_stride * C->block->rstride, xst = x->stride * x->block->rstride, yst = y->stride * y->block->rstride; while(n-- > 0){ tmp = *x_p * alpha; x_p += xst; while(m-- > 0){ *C_p = tmp * *y_p; C_p += Ccst; y_p+= yst; } Cp0 += Crst; C_p = Cp0; y_p = yp0; m = y->length; } return; } <file_sep>/* Created RJudd October 6, 2000 */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_cmtransview_f.h,v 2.1 2003/03/08 14:54:14 judd Exp $ */ #ifndef _VI_CMTRANSVIEW_F_H #define _VI_CMTRANSVIEW_F_H #include"vsip.h" #include"vsip_cmviewattributes_f.h" static vsip_cmview_f* VI_cmtransview_f( const vsip_cmview_f* v, vsip_cmview_f * a) { *a = *v; a->row_stride = v->col_stride; a->col_stride = v->row_stride; a->row_length = v->col_length; a->col_length = v->row_length; return a; } #endif /* _VI_CMTRANSVIEW_F_H */ <file_sep>/* Created RJudd November 22, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mkron_d.c,v 2.1 2006/06/08 22:19:26 judd Exp $ */ #include"vsip.h" #include"vsip_vviewattributes_d.h" #include"vsip_mviewattributes_d.h" static void VI_smmul_d( vsip_scalar_d a, const vsip_mview_d *b, const vsip_mview_d *r) { { vsip_length n_mj, /* major length */ n_mn; /* minor length */ vsip_stride bst_mj, bst_mn, rst_mj, rst_mn; vsip_scalar_d *bp = (b->block->array) + b->offset * b->block->rstride, *rp = (r->block->array) + r->offset * r->block->rstride; vsip_scalar_d *bp0 = bp, *rp0 = rp; /* pick direction dependent on output */ if(r->row_stride < r->col_stride){ n_mj = r->row_length; n_mn = r->col_length; rst_mj = r->row_stride; rst_mn = r->col_stride; bst_mj = b->row_stride; bst_mn = b->col_stride; rst_mj *= r->block->rstride; rst_mn *= r->block->rstride; bst_mj *= b->block->rstride; bst_mn *= b->block->rstride; } else { n_mn = r->row_length; n_mj = r->col_length; rst_mn = r->row_stride; rst_mj = r->col_stride; bst_mn = b->row_stride; bst_mj = b->col_stride; rst_mn *= r->block->rstride; rst_mj *= r->block->rstride; bst_mn *= b->block->rstride; bst_mj *= b->block->rstride; } while(n_mn-- > 0){ vsip_length n = n_mj; while(n-- >0){ *rp = a * *bp ; bp += bst_mj; rp += rst_mj; } bp0 += bst_mn; rp0 += rst_mn; bp = bp0; rp = rp0; } } return; } static vsip_scalar_d VI_mget_d( const vsip_mview_d *v, vsip_index row, vsip_index col){ return (*(v->block->array + v->block->rstride * (v->offset + row * v->col_stride + col * v->row_stride))); } void vsip_mkron_d( vsip_scalar_d alpha, const vsip_mview_d *x, const vsip_mview_d *y, const vsip_mview_d *c) { vsip_mview_d C = *c; vsip_length y_row_length = y->row_length, x_row_length = x->row_length, y_col_length = y->col_length, x_col_length = x->col_length; vsip_offset c_offset = c->offset; /* c row is x_row * y_col_length, c col is x_col * y_row_length */ vsip_stride c_str_c = y_col_length * c->col_stride; vsip_stride c_str_r = y_row_length * c->row_stride; vsip_length i,j; C.row_length = y_row_length; C.col_length = y_col_length; for(i=0; i< x_col_length; i++){ for(j=0; j< x_row_length; j++){ C.offset = c_offset + i * c_str_c + j * c_str_r; VI_smmul_d(VI_mget_d(x,i,j) * alpha,y,&C); } } return; } <file_sep>/* Created RJudd */ /* */ #include"VU_vprintm_d.include" static void interpolate_linear_d(void) { printf("*********\nTEST linear fitfor double\n"); { vsip_length N0 = 11; vsip_length N = 50; vsip_vview_d *yf = vsip_vcreate_d(N,VSIP_MEM_NONE); vsip_vview_d *xf = vsip_vcreate_d(N,VSIP_MEM_NONE); vsip_vview_d *xp = vsip_vcreate_d(N0,VSIP_MEM_NONE); vsip_vview_d *yp = vsip_vcreate_d(N0,VSIP_MEM_NONE); vsip_vview_d *yf_ans=vsip_vcreate_d(N,VSIP_MEM_NONE); vsip_vramp_d(0.0,1.0,xp); vsip_vramp_d(0.0,0.204,xf); vsip_svmul_d(2.0/5.0 * M_PI,xp,yp); vsip_svmul_d(2.0/5.0 * M_PI,xf,yf_ans); vsip_vsin_d(yp,yp); vsip_vsin_d(yf_ans,yf_ans); printf("xp = ");VU_vprintm_d("5.4",xp); printf("yp = ");VU_vprintm_d("5.4",yp); printf("xf = ");VU_vprintm_d("5.4",xf); vsip_vinterp_linear_d(xp,yp,xf,yf); printf("linfit = ");VU_vprintm_d("5.4",yf); printf("ans = ");VU_vprintm_d("5.4",yf_ans); vsip_valldestroy_d(xf); vsip_valldestroy_d(xp); vsip_valldestroy_d(yp); vsip_valldestroy_d(yf); vsip_valldestroy_d(yf_ans); } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mexp10_f.h,v 2.0 2003/02/22 15:23:24 judd Exp $ */ #include"VU_mprintm_f.include" static void mexp10_f(void){ printf("\n*******\nTEST mexp10_f\n\n"); { vsip_scalar_f data[] = {0.1, 0.2, 0.4, 0.8, 1.6, 3.2}; vsip_scalar_f ans[] = {1.2589, 1.5849, 2.5119, 6.3096,39.8107, 1584.8932}; vsip_block_f *block = vsip_blockbind_f(data,6,VSIP_MEM_NONE); vsip_block_f *ans_block = vsip_blockbind_f(ans,6,VSIP_MEM_NONE); vsip_mview_f *a = vsip_mbind_f(block,0,2,3,1,2); vsip_mview_f *ansm = vsip_mbind_f(ans_block,0,2,3,1,2); vsip_mview_f *b = vsip_mcreate_f(3,2,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *chk = vsip_mcreate_f(3,2,VSIP_COL,VSIP_MEM_NONE); vsip_blockadmit_f(block,VSIP_TRUE); vsip_blockadmit_f(ans_block,VSIP_TRUE); printf("test out of place, compact, user \"a\", vsipl \"b\"\n"); vsip_mexp10_f(a,b); printf("mexp10_f(a,b)\n matrix a\n");VU_mprintm_f("8.6",a); printf("matrix b\n");VU_mprintm_f("8.6",b); printf("expected answer to 4 decimal digits\n");VU_mprintm_f("9.4",ansm); vsip_msub_f(b,ansm,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.001,.001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check mexp10_f in place\n"); vsip_mexp10_f(a,a); vsip_msub_f(a,ansm,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,.001,.001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_f(a); vsip_malldestroy_f(b); vsip_malldestroy_f(chk); vsip_malldestroy_f(ansm); } return; } <file_sep>// // JVVector.swift // SJvsipEx // // Created by <NAME> on 10/12/16. // Copyright © 2016 JVSIP. All rights reserved. // import Foundation import vsip public class JVVector_d { private let vsip: OpaquePointer? private let maxLength: Int public init() { vsip = nil maxLength = 0 } public init?(length: Int){ vsip_init(nil) maxLength = length if let v = vsip_vcreate_d(vsip_length(length), VSIP_MEM_NONE) { self.vsip = v } else { return nil } } deinit{ vsip_valldestroy_d(self.vsip) vsip_finalize(nil) } public var length: Int { get { return Int(vsip_vgetlength_d(self.vsip)) } set(length) { precondition(length * self.stride + self.offset <= self.maxLength) vsip_vputlength_d(self.vsip, vsip_length(length)) } } public var offset: Int { get { return Int(vsip_vgetoffset_d(self.vsip)) } set(offset) { precondition(offset + self.length * self.stride <= self.maxLength+1) vsip_vputoffset_d(self.vsip, vsip_offset(offset)) } } public var stride: Int { get { return Int(vsip_vgetstride_d(self.vsip)) } set(stride) { precondition(stride * self.length + self.offset <= self.maxLength) precondition(stride * self.length + self.offset >= 0) vsip_vputstride_d(self.vsip, vsip_stride(stride)) } } public subscript(index: Int) -> Double { get{ return Double(vsip_vget_d(self.vsip, vsip_index(index))) } set(value){ vsip_vput_d(self.vsip, vsip_index(index), vsip_scalar_d(value)) } } public func ramp(start: Double, step: Double) { vsip_vramp_d(vsip_scalar_d(start), vsip_scalar_d(step), self.vsip) } } <file_sep>#!/bin/sh ls | sed '/\.h/!d' | sed 's/^/#include"/' | sed 's/$/"/' >includes ls | sed '/\.h/!d' | sed 's/\.h/();/' | sed 's/^/ /' >functions sed -e '/func\.h/ r includes' <testing.tmplt | sed -e '/func()/ r functions' >test_all.c rm includes rm functions cc -o test_all test_all.c -O3 -Wall -std=c89 -pedantic -I../include ../lib/libvsip.a <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D881 */ #ifndef VSIP_VI__h #define VSIP_VI__h 1 #define vsip_valid_structure_object (0x5555) #define VSIP_VALID_STRUCTURE_OBJECT (0x5555) #define vsip_freed_structure_object (0xAAAA) #define VSIP_FREED_STRUCTURE_OBJECT (0xAAAA) #define VSIP_RELEASED_BLOCK (0) #define VSIP_ADMITTED_BLOCK (1) #define VSIP_VSIPL_BLOCK (0) #define VSIP_USER_BLOCK (1) #define VSIP_DERIVED_BLOCK (2) #endif /* VSIP_VI__h */ <file_sep>#!/bin/sh ATEST=$1 AWORKINGDIR="./" AVSIPLIB="../lib/libvsip.a" AVSIPHEADERDIR="../include" CC=cc set `echo $ATEST | sed 's/\// /g'` AFILE=`eval echo \\\$$#` AFUNC=`eval echo $AFILE | sed '/\.h/!d' | sed 's/\.h/();/'` echo "/* atest.c */" >atest.c echo "/* $AFILE */" >>atest.c echo "#include<stdio.h>\n#include<string.h>\n#include<vsip.h>\n" >>atest.c echo "#define NDPTR_f ((vsip_scalar_f*)NULL)\n#define NDPTR_d ((vsip_scalar_d*)NULL)" >>atest.c echo "#define NDPTR_i ((vsip_scalar_i*)NULL)\n#define NDPTR_si ((vsip_scalar_si*)NULL)" >>atest.c echo "#include\"$ATEST\"\n" >>atest.c echo "int main(){\n\tvsip_init((void*)0);" >>atest.c echo "\n/* function to test */\n\t$AFUNC\n" >>atest.c echo "\tvsip_finalize((void*)0); \n\treturn 0;\n} " >>atest.c $CC atest.c -o atest -I$AVSIPHEADERDIR $AVSIPLIB ./atest <file_sep>// // meansqvalEx.swift // vsip // // Created by <NAME> on 4/19/17. // Copyright © 2017 JVSIP. All rights reserved. // import Foundation import vsip func meansqvalEx_cd(length: vsip_length) { let _ = vsip_init(nil) let v = vsip_cvcreate_d(length, VSIP_MEM_NONE) let vr = vsip_vrealview_d(v) let vi = vsip_vimagview_d(v) vsip_vramp_d(0.1,0.2,vr) vsip_vramp_d(0.5, -0.2, vi) print(vsip_cvmeansqval_d(v)) vsip_vdestroy_d(vr); vsip_vdestroy_d(vi); vsip_cvalldestroy_d(v) let _ = vsip_finalize(nil) } func meansqvalEx_cd(rows: vsip_length, cols: vsip_length) { let _ = vsip_init(nil) let length = rows * cols let m = vsip_cmcreate_d(rows, cols, VSIP_ROW, VSIP_MEM_NONE) let mr = vsip_mrealview_d(m) let mi = vsip_mimagview_d(m) let vr = vsip_vbind_d(vsip_vgetblock_d(mr),0,1,length) let vi = vsip_vbind_d(vsip_vgetblock_d(mi),0,1,length) vsip_vramp_d(0.1,0.2,vr) vsip_vramp_d(0.5, -0.2, vi) print(vsip_cmmeansqval_d(m)) vsip_vdestroy_d(vr); vsip_vdestroy_d(vi); vsip_mdestroy_d(mr); vsip_mdestroy_d(mi); vsip_cmalldestroy_d(m) let _ = vsip_finalize(nil) } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cvkron_f.h,v 2.1 2009/09/05 18:01:45 judd Exp $ */ #include"VU_cmprintm_f.include" #include"VU_cvprintm_f.include" static void cvkron_f(void){ printf("********\nTEST cvkron_f\n"); { vsip_cscalar_f alpha = vsip_cmplx_f(-3,2); vsip_scalar_f data_a_r[] = { 1, 1}; vsip_scalar_f data_a_i[] = { 1, -1}; vsip_scalar_f data_b_r[] = {3, 5, 2}; vsip_scalar_f data_b_i[] = {1, 1, 2}; vsip_scalar_f ans_r[] = { -14.0, -8.0, -24.0, -10.0, -8.0, -12.0}; vsip_scalar_f ans_i[] = { -8.0, 14.0, -10.0, 24.0, -12.0, 8.0}; vsip_cblock_f *block_a = vsip_cblockbind_f(data_a_r,data_a_i,2,VSIP_MEM_NONE); vsip_cblock_f *block_b = vsip_cblockbind_f(data_b_r,data_b_i,3,VSIP_MEM_NONE); vsip_cblock_f *block_c = vsip_cblockcreate_f(100,VSIP_MEM_NONE); vsip_cblock_f *ans_block = vsip_cblockbind_f(ans_r,ans_i,6,VSIP_MEM_NONE); vsip_cvview_f *a = vsip_cvbind_f(block_a,0,1,2); vsip_cvview_f *b = vsip_cvbind_f(block_b,0,1,3); vsip_cmview_f *c = vsip_cmbind_f(block_c,99,-1,3,-4,2); vsip_cmview_f *ansm = vsip_cmbind_f(ans_block,0,2,3,1,2); vsip_cmview_f *chk = vsip_cmcreate_f(3,2,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *chk_r = vsip_mrealview_f(chk); vsip_cblockadmit_f(block_a,VSIP_TRUE); vsip_cblockadmit_f(block_b,VSIP_TRUE); vsip_cblockadmit_f(ans_block,VSIP_TRUE); printf("vsip_cvkron_f(alpha,a,b,c)\n"); vsip_cvkron_f(alpha,a,b,c); printf("alpha = %f %+fi\n",(double)alpha.r,(double)alpha.i); printf("vector a\n");VU_cvprintm_f("8.6",a); printf("vector b\n");VU_cvprintm_f("8.6",b); printf("matrix c\n");VU_cmprintm_f("8.6",c); printf("right answer\n");VU_cmprintm_f("8.4",ansm); vsip_cmsub_f(c,ansm,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cvalldestroy_f(a); vsip_cvalldestroy_f(b); vsip_cmalldestroy_f(c); vsip_mdestroy_f(chk_r); vsip_cmalldestroy_f(chk); vsip_cmalldestroy_f(ansm); } return; } <file_sep>## Created RJudd ## <NAME> Diego ## $Id: Makefile,v 2.0 2003/02/22 15:27:27 judd Exp $ ## Top Level of library distribution ## RDIR=$(HOME)/local RDIR=../.. ## C compiler CC=cc INCLUDEDIR=-I$(RDIR)/include LIBDIR=-L$(RDIR)/lib LIBS= -lvsip -lm OPTIONS=-O2 example: example12.c $(CC) -o example12 example12.c $(OPTIONS) $(INCLUDEDIR) $(LIBDIR) $(LIBS) clean: rm -f example12 example12.exe <file_sep>//: Playground - noun: a place where people can play import Foundation import vsip import SJVsip // a vector of length 10 and type double let zero = Scalar(0.0), one = Scalar(1.0) let fmt = "4.3" let aMatrix = Matrix(columnLength: 5, rowLength: 5, type: .d, major: VSIP_ROW) aMatrix.randn(8, portable: true) aMatrix.mPrint(fmt) let lu = LUD(type: aMatrix.type, size: aMatrix.columnLength) let xb = Matrix(columnLength: 5, rowLength: 2, type: .d, major: VSIP_ROW) let b = xb.empty xb.randn(9, portable: true) prod(aMatrix, times: xb, resultsIn: b) lu.decompose(aMatrix) xb.mPrint(fmt); b.mPrint(fmt) lu.solve(matOp: VSIP_MAT_NTRANS, b) b.mPrint(fmt) <file_sep>/* Created RJudd January 26, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mgather_f.c,v 2.0 2003/02/22 15:18:56 judd Exp $ */ #include"vsip.h" #include"vsip_mviewattributes_f.h" #include"vsip_vviewattributes_f.h" #include"vsip_vviewattributes_mi.h" #include"vsip_vviewattributes_vi.h" void vsip_mgather_f( const vsip_mview_f *a, const vsip_vview_mi *x, const vsip_vview_f *r) { vsip_length n = x->length; vsip_stride ast_c = a->col_stride * a->block->rstride, ast_r = a->row_stride * a->block->rstride, rst = r->stride * r->block->rstride, xst = x->stride * 2; /* stride of matrix index row or col value */ vsip_scalar_f *ap = (a->block->array) + a->offset * a->block->rstride, *rp = (r->block->array) + r->offset * r->block->rstride; vsip_scalar_vi *xp_r = (x->block->array) + x->offset; /* row value */ vsip_scalar_vi *xp_c = xp_r + 1; /* col value */ /*end define*/ while(n-- > 0){ *rp = *(ap + *xp_r * ast_c + *xp_c * ast_r); rp += rst; xp_r += xst; xp_c += xst; } } <file_sep>/* Created <NAME> 2, 2012 */ /* Retired */ /* https://github.com/rrjudd/jvsip */ /*********************************************************************** // This code includes no warranty, express or implied, including the / // warranties of merchantability and fitness for a particular purpose./ // No person or entity assumes any legal liability or responsibility / // for the accuracy, completeness, or usefulness of an information / // apparatus, product, or process disclosed, or represents that its / // use would not infringe privately owned rights. / **********************************************************************/ #include"vsip.h" #include"vsip_vviewattributes_f.h" #include"vsip_vviewattributes_bl.h" void vsip_svleq_f( vsip_scalar_f a, const vsip_vview_f* b, const vsip_vview_bl* r) { { vsip_length n = r->length; vsip_stride bst = b->stride * b->block->rstride, rst = r->stride; vsip_scalar_f *bp = (b->block->array) + b->offset * b->block->rstride; vsip_scalar_bl *rp = (r->block->array) + r->offset; /*end define*/ while(n-- > 0){ *rp = (a == *bp); bp += bst; rp += rst; } } } <file_sep># About This is a distribution of a VSIPL library. VSIPL is a signal processing library specification developed by a working group of diverse individuals from industry and government. University participation was generally sponsored by government contract. The acknowledgment page of the specification contains information on participants and there institutions. The specification **VSIPL 1.3 API** is available in the **doc** directory. This was the last specification approved before the working group moved to the Object Management Group (OMG); and the last version I was personally involved with. I am not involved with the OMG or the version of the specification there. ## C version This distribution supports the C VSIPL specification and includes the C spec and C Code (ANSI C89) with many (not all) of the functions defined by the spec. There are many examples and test code. The code is written from the ground up with standard C; and is the de-facto reference implementation for the C VSIPL specification. No other third party library is needed to make the code so the implementation is very portable. The c_VSIP_src directory holds C Source code needed to build the jvsip VSIPL C Library. To **Build** type **make**. If that fails try (in a terminal) > cc -c *.c -I./ > ar rcvs libvsip.a *.o To use include vsip.h (in this directory; put it in a handy place) and link with libvsip.a . There are other ways to make this library and lots of flags you can try. This is the most brain dead way if you just want to try it out and don't know a lot about C or libraries. Use only if you can't get the Makefile to work properly for you. You should just be able to type **make** in a terminal window opened in the root (jvsip) directory. This code depends only on an ansi C89 compliant compiler to build. Look for more information in the **doc** directory. ## C++ version Currently a C++ API exists; developed by the HPEC-SI working group. The C++ API includes both a serial and parallel spec. This distribution does not support the C++ API. For C++ VSIPL information I would recommend searching for VSIPL and the OMG. # Some History The original VSIPL was done by a working group (started in about 1995) which was specific to C VSIPL. The VSIPL working group morphed into the HPEC-SI working group (High Performance Embedded Computing - Software Initiative) which developed the C++ API's. Note HPEC-SI was not specific to VSIPL. This distribution is based on the TVCPP distribution. I wrote TVCPP while a government employee and have been maintaining it into retirement. I placed it on github and renamed the distribution to JVSIP to prevent it's demise from lack of support. The **Copyright** document contains additional information. The original goal of VSIPL is that anybody can implement a VSIPL Library. The idea was that multiple (hardware) vendors would implement VSIPL instead of their proprietary library and software would be more portable when new hardware is purchased. The reality has been more toward software vendors creating VSIPL libraries for multiple platforms. # Current Affairs This distribution is open and free to anybody that wants to use or modify the source code for their own uses. Only source code is distributed and only the user is responsible for any result of using the distribution. If you need things like performance and support please go to a commercial signal processing library. I may (or may not) be willing to supply advice depending upon the work involved and my own agenda. I am retired now and this is a hobby for me. I might have better things to do with my time. ## Not C VSIPL In retirement I have explored other programming paradigms besides C. A lot of this work made it's way into JVSIP. I spent a lot of time on python and there is a very complete _Proof of Concept_ in the **python** directory. There are notebooks in the **doc** directory which demonstrate the python code. There is a **c++** directory which is NOT very complete. I don't know C++ and have not had much success trying to use it. It was a big time waister so I decided to quit working with C++. (In particular I don't like generics in Swift or C++) I work on an Apple platform and have started using Swift as my main language. Some of this work shows up in the **AppleXcode** directory. There are several projects available in this directory and your mileage may vary. # Directories A short overview of directory structure. Some folks won't be interested in everything. Note there are various documents available on how to make and use things. **jvsip** > top level directory, you may have cloned into something else > **AppleXcode** >> Stuff particular to an Apple Environment with the Xcode IDE > **c_VSIP_src** >> C source code for VSIPL > **c_VSIP_testing** >> Source code for testing VSIPL codes > **doc** >> Most (but not all) documents. Includes how to make and use information >> These documents are PDF. > **examples** and **c_VSIP_example** >> Examples. Note c_VSIP_testing also may be examined for examples of how to do VSIPL code > **python** >> Python modules are in this directory <file_sep>/* Created R Judd */ /* Copyright (c) 2006 <NAME> */ /* MIT style license, see Copyright notice in top level directory */ /* $Id: ccovsol_d.h,v 1.2 2006/05/16 16:45:18 judd Exp $ */ #include"VU_cmprintm_d.include" static int ccovsol_d(void) { vsip_cmview_d *A = vsip_cmcreate_d(10,6,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *BX = vsip_cmcreate_d(10,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *X = vsip_cmcreate_d(6,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *ANS = vsip_cmcreate_d(6,3,VSIP_ROW,VSIP_MEM_NONE); /* create space for ccovsol data */ vsip_cblock_d *ablock = vsip_cblockcreate_d(500,VSIP_MEM_NONE); vsip_cmview_d *A1 = vsip_cmbind_d(ablock,200,-3,10,-31,6); vsip_cscalar_d a0 = vsip_cmplx_d(0.0,0.0); int i; vsip_cmfill_d(a0,A); vsip_cmfill_d(a0,BX); printf("********\nTEST ccovsol_d\n"); printf("Test covariance solver vsip_ccovsol_d\n"); /* Solving for X in A X = B */ /* A is (M,N) M >= N; X is (N,K), B is (N,K) */ /* need to make up some data */ /* data for matrix A */ for(i=0; i<vsip_cmgetrowlength_d(A); i++){ /* fill by column */ vsip_cvview_d *ac = vsip_cmcolview_d(A,i); vsip_vview_d *ac_r = vsip_vrealview_d(ac); vsip_vview_d *ac_i = vsip_vimagview_d(ac); vsip_vramp_d(-1.3,1.1,ac_r); vsip_vramp_d(+1.3,-1.1,ac_i); vsip_vdestroy_d(ac_r); vsip_vdestroy_d(ac_i); vsip_cvdestroy_d(ac); } { /* make sure diagonal keeps things stable */ vsip_cvview_d *ad = vsip_cmdiagview_d(A,0); vsip_vview_d *ad_r = vsip_vrealview_d(ad); vsip_vview_d *ad_i = vsip_vimagview_d(ad); vsip_vramp_d(3,1.2,ad_r); vsip_vramp_d(3,-1.2,ad_i); vsip_vdestroy_d(ad_r); vsip_vdestroy_d(ad_i); vsip_cvdestroy_d(ad); } /* Data for matrix B */ for(i=0; i<vsip_cmgetcollength_d(BX); i++){ /* fill by row */ vsip_cvview_d *bxr = vsip_cmrowview_d(BX,i); vsip_vview_d *bxr_r = vsip_vrealview_d(bxr); vsip_vview_d *bxr_i = vsip_vimagview_d(bxr); vsip_vramp_d(0.1,(vsip_scalar_d)i/3.0,bxr_r); vsip_vramp_d(0.1,(vsip_scalar_d)i/4.0,bxr_i); vsip_vdestroy_d(bxr_r);vsip_vdestroy_d(bxr_i); vsip_cvdestroy_d(bxr); } printf("Input data \n"); printf("A = ");VU_cmprintm_d("4.2",A); printf("\nB = ");VU_cmprintm_d("4.2",BX); { vsip_cchol_d *chol = vsip_cchold_create_d(VSIP_TR_LOW,6); vsip_cmview_d *B = vsip_cmcreate_d(6,3,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *AHA = vsip_cmcreate_d(6,6,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *AH = vsip_cmcreate_d(6,10,VSIP_ROW,VSIP_MEM_NONE); /* solve using Cholesky and AHA matrix */ printf("\nSolve using Cholesky"); printf("\nA is input matrix, AT (AH) is transpose (Hermitian) of A\n"); printf("Solve for X least squares using (AH prod A ) prod X = AH prod B\n"); /* calculate matrix AHA = AH * A */ vsip_cmherm_d(A,AH); vsip_cmprod_d(AH,A,AHA); /* calculate AH * B */ vsip_cmprod_d(AH,BX,X); printf("\nAH prod A = ");VU_cmprintm_d("4.2",AHA); printf("\nAH prod B = ");VU_cmprintm_d("4.2",X); vsip_cchold_d(chol,AHA); vsip_ccholsol_d(chol,X);/* B replaced by X */ printf("\nX = ");VU_cmprintm_d("7.5",X); vsip_cchold_destroy_d(chol); /* check */ printf("\ncheck\n (AH prod A) prod X := AH prod B"); /* restore AHA */ vsip_cmprod_d(AH,A,AHA); /* calculate AHA prod X */ vsip_cmprod_d(AHA,X,B); vsip_cmcopy_d_d(X,ANS); /* if correct Need ANSwer */ /* for check place AH * BX into X */ vsip_cmprod_d(AH,BX, X); printf("\nAHA * X ="); VU_cmprintm_d("4.2",B); vsip_cmsub_d(X,B,X); { float check = (float) vsip_cmmeansqval_d(X); if(fabs(check) < .0001) printf("check = %f\ncorrect\n",check); else printf("check = %f\nerror\n",check); } /* restore X for use by covsol */ vsip_cmprod_d(AH,BX, X); vsip_cmalldestroy_d(B); vsip_cmalldestroy_d(AHA); vsip_cmalldestroy_d(AH); } /* solve using ccovsol */ /* copy data so we can solve covariance problem later on */ vsip_cmcopy_d_d(A,A1); printf("\nSolve using ccovsol_d "); vsip_ccovsol_d(A1,X); printf("Expect X to be\n");VU_cmprintm_d("7.5",ANS); printf("\nX = ");VU_cmprintm_d("7.5",X); vsip_cmsub_d(ANS,X,X); { float check = (float) vsip_cmmeansqval_d(X); if(fabs(check) < .0001) printf("check = %f\ncorrect\n",check); else printf("check = %f\nerror\n",check); } vsip_cmdestroy_d(A1); vsip_cblockdestroy_d(ablock); vsip_cmalldestroy_d(A); vsip_cmalldestroy_d(BX); vsip_cmalldestroy_d(X); return 0; } <file_sep>/* * svd4_f.h * VSIP_svd_fev * * Created by <NAME> on 9/13/08. * Copyright 2008 Home. All rights reserved. * */ #include"VU_mprintm_f.include" #include"VU_vprintm_f.include" static void svd4_f(void){ printf("********\nTEST svd4 for float\n"); { vsip_index i; vsip_length M=10, N=3; vsip_scalar_f data[30] = {0, 0, 0, 0, \ 0, 0, 0, 0, \ 0, 0, 0, 1, \ 0, 0, 0, 100,\ 0, 0, 1, 0, \ 1,0,0,1,0,0,0,0,0,0}; vsip_vview_f *s = vsip_vcreate_f(((M > N) ? N : M),VSIP_MEM_NONE); vsip_sv_f *svd = vsip_svd_create_f(M,N,VSIP_SVD_UVFULL,VSIP_SVD_UVFULL); vsip_block_f *block = vsip_blockbind_f(data,(M * N),VSIP_MEM_NONE); vsip_mview_f *A0 = vsip_mbind_f(block,0,1,M,M,N); vsip_block_f *vblk = vsip_blockcreate_f(600,VSIP_MEM_NONE); vsip_mview_f *A = vsip_mbind_f(vblk,3,3, M,3*M , N); vsip_mview_f *U = vsip_mcreate_f(M,M,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *V = vsip_mcreate_f(N,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *B = vsip_mcreate_f(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_f(block,VSIP_TRUE); vsip_mcopy_f_f(A0,A); printf("in = ");VU_mprintm_f("6.3",A); if(vsip_svd_f(svd,A,s)){ printf("svd error\n"); return; } /* create the singular value matrix */ vsip_mfill_f(0.0,B); for(i=0; i<vsip_vgetlength_f(s); i++) vsip_mput_f(B,i,i,vsip_vget_f(s,i)); vsip_svdmatu_f(svd, 0, M-1, U); vsip_svdmatv_f(svd, 0, N-1, V); printf("U = ");VU_mprintm_f("12.10",U); printf("B = ");VU_mprintm_f("12.10",B); printf("V = ");VU_mprintm_f("12.10",V); VU_vprintm_f("12.10",s); { /* check that A0 = U * B * V' */ vsip_scalar_mi mi; vsip_scalar_f chk = 1.0; vsip_scalar_f lim = 5 * FLT_EPSILON * fabs(vsip_mmaxmgval_f(A0,&mi)); vsip_mview_f *dif=vsip_mcreate_f(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *out = vsip_mcreate_f(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *Vt = vsip_mtransview_f(V); vsip_mprod_f(U,B,dif); vsip_mprod_f(dif,Vt,out); vsip_msub_f(out,A0,dif); vsip_mmag_f(dif, dif); chk = vsip_msumval_f(dif)/(2 * M * N); printf("%20.18e - %20.18e = %e\n",lim,chk, (lim - chk)); if(chk > lim){ printf("error\n"); } else { printf("correct\n"); } vsip_malldestroy_f(dif); vsip_malldestroy_f(out); vsip_mdestroy_f(Vt); } vsip_svd_destroy_f(svd); vsip_malldestroy_f(A0); vsip_malldestroy_f(A); vsip_valldestroy_f(s); vsip_malldestroy_f(U); vsip_malldestroy_f(B); vsip_malldestroy_f(V); } return; } <file_sep>/* Created RJudd For Core January 10, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vcreate_hanning_f.c,v 2.1 2003/04/22 02:19:59 judd Exp $ */ /* Removed Development Mode RJudd Sept 00 */ #include"vsip.h" #include"vsip_vviewattributes_f.h" #include"vsip_scalars.h" #include"VI_vcreate_f.h" #define twoPI 6.2831853071796 vsip_vview_f* (vsip_vcreate_hanning_f)( vsip_length N, vsip_memory_hint h) { vsip_vview_f *a; a = VI_vcreate_f(N,h); if(a == NULL) return (vsip_vview_f*)NULL; { /*define variables*/ vsip_length n = 0; vsip_scalar_f *ap = (a->block->array) + a->offset, temp = (vsip_scalar_f)twoPI/(N+1); /*end define*/ /* Note this is always unit stride */ while(n++ < N ){ *ap++ = (vsip_scalar_f)0.5 * ((vsip_scalar_f)1. - (vsip_scalar_f)VSIP_COS_F(temp * (vsip_scalar_f) n)); } } return a; } <file_sep>/* Created RJudd September 16, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cblockcreate_f.c,v 2.1 2006/06/08 22:19:26 judd Exp $ */ #include"vsip.h" #include"vsip_cblockattributes_f.h" #include"VI_blockcreate_f.h" #include"VI_blockdestroy_f.h" vsip_cblock_f* (vsip_cblockcreate_f)( vsip_length N, vsip_memory_hint h) { vsip_cblock_f* b = (vsip_cblock_f*)malloc(sizeof(vsip_cblock_f)); if(b != NULL){ b->kind = VSIP_VSIPL_BLOCK; b->admit = VSIP_ADMITTED_BLOCK; b->markings = VSIP_VALID_STRUCTURE_OBJECT; b->size = N; /* size in complex elements */ b->bindings = 0; b->hint = h; #if defined(VSIP_DEFAULT_SPLIT) || defined(VSIP_ALWAYS_SPLIT) b->cstride = 1; /* native block are split */ b->R = VI_blockcreate_f(N,h); b->I = VI_blockcreate_f(N,h); if((b->R == NULL) || (b->I == NULL)){ VI_blockdestroy_f(b->R); VI_blockdestroy_f(b->I); free((void *)b); b = (vsip_cblock_f*)NULL; } else { /* modifiy real */ b->R->kind = VSIP_DERIVED_BLOCK; b->I->kind = VSIP_DERIVED_BLOCK; b->R->parent = b; b->I->parent = b; } #else b->cstride = 2; /* native block are interleaved */ b->R = VI_blockcreate_f(2 * N,h); b->I = (vsip_block_f*)malloc(sizeof(vsip_block_f)); if((b->R == NULL) || (b->I == NULL)){ VI_blockdestroy_f(b->R); free((void *)b->I); free((void *)b); b = (vsip_cblock_f*)NULL; } else { /* modifiy real */ b->R->kind = VSIP_DERIVED_BLOCK; b->R->rstride = b->cstride; b->R->size = N; /* size in real elements */ b->R->parent = b; /* initiate imaginary */ /* same as real except array data pointer one greater */ *b->I = *b->R; b->I->array++; } #endif #if defined(VSIP_ALWAYS_INTERLEAVED) b->data = ((void*)0); b->Rp = (vsip_scalar_f*)NULL; b->Ip = (vsip_scalar_f*)NULL; #elif defined(VSIP_ALWAYS_SPLIT) b->r_data = ((void*)0); b->i_data = ((void*)0); b->Rp = (vsip_scalar_f*)NULL; b->Ip = (vsip_scalar_f*)NULL; #endif if(b){ b->a_scalar.r = 0.0; b->a_scalar.i = 0.0; b->a_zero.r = 0.0; b->a_zero.i = 0.0; b->a_one.r = 1.0; b->a_one.i = 0.0; b->a_imag_one.r = 0.0; b->a_imag_one.i = 1.0; } } return b; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cvkron_d.h,v 2.1 2009/09/05 18:01:45 judd Exp $ */ #include"VU_cmprintm_d.include" #include"VU_cvprintm_d.include" static void cvkron_d(void){ printf("********\nTEST cvkron_d\n"); { vsip_cscalar_d alpha = vsip_cmplx_d(-3,2); vsip_scalar_d data_a_r[] = { 1, 1}; vsip_scalar_d data_a_i[] = { 1, -1}; vsip_scalar_d data_b_r[] = {3, 5, 2}; vsip_scalar_d data_b_i[] = {1, 1, 2}; vsip_scalar_d ans_r[] = { -14.0, -8.0, -24.0, -10.0, -8.0, -12.0}; vsip_scalar_d ans_i[] = { -8.0, 14.0, -10.0, 24.0, -12.0, 8.0}; vsip_cblock_d *block_a = vsip_cblockbind_d(data_a_r,data_a_i,2,VSIP_MEM_NONE); vsip_cblock_d *block_b = vsip_cblockbind_d(data_b_r,data_b_i,3,VSIP_MEM_NONE); vsip_cblock_d *block_c = vsip_cblockcreate_d(100,VSIP_MEM_NONE); vsip_cblock_d *ans_block = vsip_cblockbind_d(ans_r,ans_i,6,VSIP_MEM_NONE); vsip_cvview_d *a = vsip_cvbind_d(block_a,0,1,2); vsip_cvview_d *b = vsip_cvbind_d(block_b,0,1,3); vsip_cmview_d *c = vsip_cmbind_d(block_c,99,-1,3,-4,2); vsip_cmview_d *ansm = vsip_cmbind_d(ans_block,0,2,3,1,2); vsip_cmview_d *chk = vsip_cmcreate_d(3,2,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *chk_r = vsip_mrealview_d(chk); vsip_cblockadmit_d(block_a,VSIP_TRUE); vsip_cblockadmit_d(block_b,VSIP_TRUE); vsip_cblockadmit_d(ans_block,VSIP_TRUE); printf("vsip_cvkron_d(alpha,a,b,c)\n"); vsip_cvkron_d(alpha,a,b,c); printf("alpha = %f %+fi\n",(double)alpha.r,(double)alpha.i); printf("vector a\n");VU_cvprintm_d("8.6",a); printf("vector b\n");VU_cvprintm_d("8.6",b); printf("matrix c\n");VU_cmprintm_d("8.6",c); printf("right answer\n");VU_cmprintm_d("8.4",ansm); vsip_cmsub_d(c,ansm,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_d(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cvalldestroy_d(a); vsip_cvalldestroy_d(b); vsip_cmalldestroy_d(c); vsip_mdestroy_d(chk_r); vsip_cmalldestroy_d(chk); vsip_cmalldestroy_d(ansm); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: msdiv_d.h,v 2.0 2003/02/22 15:23:26 judd Exp $ */ #include"VU_mprintm_d.include" static void msdiv_d(void){ printf("\n******\nTEST msdiv_d\n"); { vsip_scalar_d data1= 5.5; vsip_scalar_d data2[]= {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9}; vsip_scalar_d ans[] = {.2, .8, 1.4, .4, 1.0, 1.6, .6, 1.2, 1.8}; vsip_mview_d *m2 = vsip_mbind_d( vsip_blockbind_d(data2,9,VSIP_MEM_NONE),0,1,3,3,3); vsip_mview_d *ma = vsip_mbind_d( vsip_blockbind_d(ans,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_mview_d *m3 = vsip_mcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *chk = vsip_mcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_d(vsip_mgetblock_d(m2),VSIP_TRUE); vsip_blockadmit_d(vsip_mgetblock_d(ma),VSIP_TRUE); printf("call vsip_msdiv_d(a,beta,c)\n"); printf("a =\n");VU_mprintm_d("8.6",m2); printf("beta = %f\n",data1); vsip_msdiv_d(m2,data1,m3); printf("c =\n");VU_mprintm_d("8.6",m3); printf("\nright answer =\n"); VU_mprintm_d("6.4",ma); vsip_msub_d(ma,m3,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,0,.0001,0,1,chk); if(fabs(vsip_msumval_d(chk)) > .5) printf("error\n"); else printf("correct\n"); vsip_mcopy_d_d(m2,m3); printf(" a,c inplace\n"); vsip_msdiv_d(m3,data1,m3); vsip_msub_d(ma,m3,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,0,.0001,0,1,chk); if(fabs(vsip_msumval_d(chk)) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_d(m2); vsip_malldestroy_d(m3); vsip_malldestroy_d(ma); vsip_malldestroy_d(chk); } return; } <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mcopyfrom_user_d.h,v 1.1 2007/04/18 03:59:06 judd Exp $ */ #include"VU_mprintm_d.include" static void mcopyfrom_user_d(void){ vsip_index i,j; printf("********\nTEST mcopyfrom_user_d\n"); { /* check row copy */ vsip_block_d *block = vsip_blockcreate_d(200,VSIP_MEM_NONE); vsip_scalar_d input[20]={0,1,2,3,10,11,12,13,20,21,22,23,30,31,32,33,40,41,42,43}; vsip_mview_d *view = vsip_mbind_d(block,100,2,5,12,4); vsip_vview_d *all = vsip_vbind_d(block,0,1,200); vsip_scalar_d check = 0; vsip_vfill_d(-1,all); vsip_mcopyfrom_user_d(input,VSIP_ROW,view); printf("check row copy\n"); VU_mprintm_d("3.2",view); for(i=0; i<5; i++) { for(j=0; j < 4; j++) { check += fabs(input[i * 4 + j] - vsip_mget_d(view,i,j)); } } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_vdestroy_d(all); vsip_mdestroy_d(view); vsip_blockdestroy_d(block); } { /* check col copy */ vsip_block_d *block = vsip_blockcreate_d(200,VSIP_MEM_NONE); vsip_scalar_d input[20]={0,10,20,30,40,1,11,21,31,41,2,12,22,32,42,3,13,23,33,43}; vsip_mview_d *view = vsip_mbind_d(block,100,2,5,12,4); vsip_vview_d *all = vsip_vbind_d(block,0,1,200); vsip_scalar_d check = 0; vsip_vfill_d(-1,all); vsip_mcopyfrom_user_d(input,VSIP_COL,view); printf("check col copy\n"); VU_mprintm_d("3.2",view); for(j=0; j<4; j++) { for(i=0; i < 5; i++) { check += fabs(input[j * 5 + i] - vsip_mget_d(view,i,j)); } } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_vdestroy_d(all); vsip_mdestroy_d(view); vsip_blockdestroy_d(block); } return; } <file_sep># Elementary Math functions from vsip import * def __iscompatible(a,b): chk = True msg='None' if ('pyJvsip' not in repr(a)) or ('pyJvsip' not in repr(b)): chk = False msg='Input must be a pyJvsip View' elif a.type != b.type: chk = False msg = 'Inputs must be the same type' elif 'mview' in a.type: if (a.rowlength != b.rowlength) or (a.collength != b.collength): chk = False msg = 'Inputs must be the same size' else: if a.length != b.length: chk = False msg = 'Inputs must be the same size' return (chk,msg) def __isSizeCompatible(a,b): if 'mview' in a.type and 'mview' in b.type: if (a.rowlength == b.rowlength) and (a.collength == b.collength): return True elif 'vview' in a.type and 'vview' in b.type: if a.length == b.length: return True else: return False # vsip_dsswap_p def swap(a,b): """ See VSIP specification for Information """ f = {'cmview_d':vsip_cmswap_d, 'cmview_f':vsip_cmswap_f, 'cvview_d':vsip_cvswap_d, \ 'cvview_f':vsip_cvswap_f, 'mview_d':vsip_mswap_d, 'mview_f':vsip_mswap_f,\ 'vview_d':vsip_vswap_d, 'vview_f':vsip_vswap_f, 'vview_i':vsip_vswap_i,\ 'vview_si':vsip_vswap_si, 'vview_uc':vsip_vswap_uc} chk, msg = __iscompatible(a,b) assert chk, msg t=a.type assert t in f, 'Type <:' +t+ ':> not supported for swap' f[a.type](a.vsip,b.vsip) # vsip_dsgather_p def gather(a,b,c): """ See VSIP specification for Information """ f={'cmview_dvview_micvview_d':vsip_cmgather_d, 'cmview_fvview_micvview_f':vsip_cmgather_f, 'cvview_dvview_vicvview_d':vsip_cvgather_d, 'cvview_fvview_vicvview_f':vsip_cvgather_f, 'mview_dvview_mivview_d':vsip_mgather_d, 'mview_fvview_mivview_f':vsip_mgather_f, 'vview_dvview_vivview_d':vsip_vgather_d, 'vview_fvview_vivview_f':vsip_vgather_f, 'vview_ivview_vivview_i':vsip_vgather_i, 'vview_sivview_vivview_si':vsip_vgather_si, 'vview_ucvview_vivview_uc':vsip_vgather_uc, 'vview_mivview_vivview_mi':vsip_vgather_mi, 'vview_vivview_vivview_vi':vsip_vgather_vi} assert 'pyJvsip' in repr(a),'Argument one must be a pyJvsip view object in function gather' assert 'pyJvsip' in repr(b),'Argument two must be a pyJvsip view object in function gather' assert 'pyJvsip' in repr(c),'Argument three must be a pyJvsip view object in function gather' t=a.type+b.type+c.type assert t in f, 'Type <:' +t+ ':> not supported for gather' assert __isSizeCompatible(b,c),'Index vector must be the same length as output vector' f[t](a.vsip,b.vsip,c.vsip) return c # vsip_dsscatter_p def scatter(a,b,c): """ See VSIP specification for Information """ f={'cvview_dcmview_dvview_mi':vsip_cmscatter_d, 'cvview_fcmview_fvview_mi':vsip_cmscatter_f, 'cvview_dcvview_dvview_vi':vsip_cvscatter_d, 'cvview_fcvview_fvview_vi':vsip_cvscatter_f, 'vview_dmview_dvview_mi':vsip_mscatter_d, 'vview_fmview_fvview_mi':vsip_mscatter_f, 'vview_dvview_dvview_vi':vsip_vscatter_d, 'vview_fvview_fvview_vi':vsip_vscatter_f, 'vview_i,vview_i,vview_vi':vsip_vscatter_i, 'vview_sivview_sivview_vi':vsip_vscatter_si, 'vview_ucvview_ucvview_vi':vsip_vscatter_uc} assert 'pyJvsip' in repr(a),'Argument one must be a pyJvsip view object in function scatter' assert 'pyJvsip' in repr(b),'Argument two must be a pyJvsip view object in function scatter' assert 'pyJvsip' in repr(c),'Argument three must be a pyJvsip view object in function scatter' t=a.type+b.type+c.type assert t in f, 'Type <:' +t+ ':> not supported for scatter' assert __isSizeCompatible(a,c),'Index vector must be the same length as input vector' f[t](a.vsip,b.vsip,c.vsip) return c # vsip_srect_p def rect(a,b,*vars): """ See VSIP specification for Information Convert polar to rectangular represenation Usage: rect(a,b,c) where a and b are views of type ?view_f or ?view_d c is a compliant view of type c?view_f or c?view_d OR: c = rect(a,b) compliant output c is created by function call. """ f={'vview_dvview_dcvview_d':vsip_vrect_d, 'vview_fvview_fcvview_f':vsip_vrect_f, 'mview_dmview_dcmview_d':vsip_mrect_d, 'mview_fmview_fcmview_f':vsip_mrect_f} assert 'pyJvsip' in repr(a),'Argument one must be a pyJvsip view object in function rect' assert 'pyJvsip' in repr(b),'Argument two must be a pyJvsip view object in function rect' assert len(vars) < 2, 'To many arguments to rect function' if len(vars) == 1: c = vars[0] else: c = a.otherEmpty assert 'pyJvsip' in repr(c),'Argument three must be a pyJvsip view object in function rect' t=a.type+b.type+c.type assert t in f, 'Type <:' +t+ ':> not supported for rect' assert __isSizeCompatible(a,b) and __isSizeCompatible(a,c),'Size error in rect' f[t](a.vsip,b.vsip,c.vsip) return c # vsip_sreal_p def real(a,b): """ See VSIP specification for Information real part a is of type complex; b is of corresponding type real """ f={'cvview_dvview_d':vsip_vreal_d, 'cvview_fvview_f':vsip_vreal_f, 'cmview_dmview_d':vsip_mreal_d, 'cmview_fmview_f':vsip_mreal_f} assert 'pyJvsip' in repr(a),'Argument one must be a pyJvsip view object in function real' assert 'pyJvsip' in repr(b),'Argument two must be a pyJvsip view object in function real' t=a.type+b.type assert t in f, 'Type <:' +t+ ':> not supported for real' assert __isSizeCompatible(a,b),'Size error in real' f[t](a.vsip,b.vsip) return b # vsip_simag_p def imag(a,b): """ See VSIP specification for Information Imaginary part a is of type complex; b is of corresponding type imaginary. """ f={'cvview_dvview_d':vsip_vimag_d, 'cvview_fvview_f':vsip_vimag_f, 'cmview_dmview_d':vsip_mimag_d, 'cmview_fmview_f':vsip_mimag_f} assert 'pyJvsip' in repr(a),'Argument one must be a pyJvsip view object in function imag' assert 'pyJvsip' in repr(b),'Argument two must be a pyJvsip view object in function imag' t=a.type+b.type assert t in f, 'Type <:' +t+ ':> not supported for imag' assert __isSizeCompatible(a,b),'Size error in imag' f[t](a.vsip,b.vsip) return b # vsip_scmplx_p def cmplx(a,b,*vars): """ See VSIP specification for Information Convert Convert real, imaginary (a,b) into complex Usage: cmplx(a,b,c) where a and b are views of type vview_f or vview_d c is a compliant view of type cvview_f or cvview_d OR: c = cmplx(a,b) compliant output c is created by function call. """ f={'vview_dvview_dcvview_d':vsip_vcmplx_d, 'vview_fvview_fcvview_f':vsip_vcmplx_f, 'mview_dmview_dcmview_d':vsip_mcmplx_d, 'mview_fmview_fcmview_f':vsip_mcmplx_f} assert 'pyJvsip' in repr(a),'Argument one must be a pyJvsip view object in function cmplx' assert 'pyJvsip' in repr(b),'Argument two must be a pyJvsip view object in function cmplx' assert len(vars) < 2, 'To many arguments to rect function' if len(vars) == 1: c = vars[0] else: c = a.otherEmpty assert 'pyJvsip' in repr(c),'Argument three must be a pyJvsip view object in function cmplx' t=a.type+b.type+c.type assert t in f, 'Type <:' +t+ ':> not supported for cmplx' assert __isSizeCompatible(a,b) and __isSizeCompatible(a,c),'Size error in cmplx' f[t](a.vsip,b.vsip,c.vsip) return c # vsip_spolar_p def polar(a,*vars): """ See VSIP specification for Information Convert polar (complex vector) to rectangular (real vectors of radius and angle) Usage: polar(a,r,phi) or: (r,phi) = polar(a) where: a is a complex vector/matrix pyJvsip view r is a radius of type real (vector/matrix pyJvsip view) phi is an angle (vector/matrix pyJvsip view) """ f={'cvview_dvview_dvview_d':vsip_vpolar_d, 'cvview_fvview_fvview_f':vsip_vpolar_f, 'cmview_dmview_dmview_d':vsip_mpolar_d, 'cmview_fmview_fmview_f':vsip_mpolar_f} assert 'pyJvsip' in repr(a),'Argument one must be a pyJvsip view object in function polar' assert len(vars) < 3, 'To many arguments to function polar' assert len(vars) == 2 or len(vars) == 0, 'In Polar argument two and three must both be present or both be absent' if len(vars) == 0: b = a.otherEmpty c = b.empty else: b=vars[0] c=vars[1] assert 'pyJvsip' in repr(b),'Argument two must be a pyJvsip view object in function polar' assert 'pyJvsip' in repr(c),'Argument three must be a pyJvsip view object in function polar' t=a.type+b.type+c.type assert t in f, 'Type <:' +t+ ':> not supported for polar' assert __isSizeCompatible(a,b) and __isSizeCompatible(a,c),'Size error in polar' f[t](a.vsip,b.vsip,c.vsip) return(b,c) # the nary functions are not currently supported in jvsip # vsip_smary_p # vsip_snary_p # vsip_sserialmary_p # vsip_sunary_p # vsip_sbool_p # pyJvsip does not support tensors at this time # vsip_dtscatter_p # vsip_dtgather_p <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D881 */ #ifndef _vsip_firattributes_f_h #define _vsip_firattributes_f_h 1 #include"VI.h" struct vsip_firattributes_f{ vsip_vview_f *h; vsip_vview_f *s; vsip_length N; vsip_length M; vsip_length p; vsip_length D; int ntimes; vsip_symmetry symm; vsip_alg_hint hint; vsip_obj_state state; }; #endif /* _vsip_firattributes_f_h */ <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_length_si.h,v 2.1 2007/04/18 17:05:56 judd Exp $ */ static void get_put_length_si(void){ printf("********\nTEST get_put_length_si\n"); { vsip_offset ivo = 3; vsip_stride ivs = 0; vsip_length ivl = 3; vsip_length jvl = 5; vsip_stride irs = 0, ics = 0; vsip_length irl = 2, icl = 3; vsip_length jrl = 5, jcl = 2; vsip_stride ixs = 0, iys = 0, izs = 0; vsip_length ixl = 2, iyl = 3, izl = 4; vsip_length jxl = 3, jyl = 4, jzl = 2; vsip_block_si *b = vsip_blockcreate_si(80,VSIP_MEM_NONE); vsip_vview_si *v = vsip_vbind_si(b,ivo,ivs,ivl); vsip_mview_si *m = vsip_mbind_si(b,ivo,ics,icl,irs,irl); vsip_tview_si *t = vsip_tbind_si(b,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_length s; printf("test vgetlength_si\n"); fflush(stdout); { s = vsip_vgetlength_si(v); (s == ivl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputlength_si\n"); fflush(stdout); { vsip_vputlength_si(v,jvl); s = vsip_vgetlength_si(v); (s == jvl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /*************************************************************************/ printf("test mgetrowlength_si\n"); fflush(stdout); { s = vsip_mgetrowlength_si(m); (s == irl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputrowlength_si\n"); fflush(stdout); { vsip_mputrowlength_si(m,jrl); s = vsip_mgetrowlength_si(m); (s == jrl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test mgetcollength_si\n"); fflush(stdout); { s = vsip_mgetcollength_si(m); (s == icl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputcollength_si\n"); fflush(stdout); { vsip_mputcollength_si(m,jcl); s = vsip_mgetcollength_si(m); (s == jcl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /*************************************************************************/ printf("test tgetxlength_si\n"); fflush(stdout); { s = vsip_tgetxlength_si(t); (s == ixl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputxlength_si\n"); fflush(stdout); { vsip_tputxlength_si(t,jxl); s = vsip_tgetxlength_si(t); (s == jxl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test tgetylength_si\n"); fflush(stdout); { s = vsip_tgetylength_si(t); (s == iyl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputylength_si\n"); fflush(stdout); { vsip_tputylength_si(t,jyl); s = vsip_tgetylength_si(t); (s == jyl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test tgetzlength_si\n"); fflush(stdout); { s = vsip_tgetzlength_si(t); (s == izl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputzlength_si\n"); fflush(stdout); { vsip_tputzlength_si(t,jzl); s = vsip_tgetzlength_si(t); (s == jzl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } vsip_vdestroy_si(v); vsip_mdestroy_si(m); vsip_talldestroy_si(t); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_stride_i.h,v 2.1 2007/04/18 17:05:56 judd Exp $ */ static void get_put_stride_i(void){ printf("********\nTEST get_put_stride_i\n"); { vsip_offset ivo = 3; vsip_stride ivs = 2; vsip_length ivl = 3; vsip_stride jvs = 3; vsip_stride irs = 1, ics = 3; vsip_length irl = 2, icl = 3; vsip_stride jrs = 5, jcs = 2; vsip_stride ixs = 2, iys = 4, izs = 14; vsip_length ixl = 2, iyl = 3, izl = 4; vsip_stride jxs = 4, jys = 14, jzs = 2; vsip_block_i *b = vsip_blockcreate_i(80,VSIP_MEM_NONE); vsip_vview_i *v = vsip_vbind_i(b,ivo,ivs,ivl); vsip_mview_i *m = vsip_mbind_i(b,ivo,ics,icl,irs,irl); vsip_tview_i *t = vsip_tbind_i(b,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_stride s; printf("test vgetstride_i\n"); fflush(stdout); { s = vsip_vgetstride_i(v); (s == ivs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputstride_i\n"); fflush(stdout); { vsip_vputstride_i(v,jvs); s = vsip_vgetstride_i(v); (s == jvs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /*************************************************************************/ printf("test mgetrowstride_i\n"); fflush(stdout); { s = vsip_mgetrowstride_i(m); (s == irs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputrowstride_i\n"); fflush(stdout); { vsip_mputrowstride_i(m,jrs); s = vsip_mgetrowstride_i(m); (s == jrs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test mgetcolstride_i\n"); fflush(stdout); { s = vsip_mgetcolstride_i(m); (s == ics) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputcolstride_i\n"); fflush(stdout); { vsip_mputcolstride_i(m,jcs); s = vsip_mgetcolstride_i(m); (s == jcs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /*************************************************************************/ printf("test tgetxstride_i\n"); fflush(stdout); { s = vsip_tgetxstride_i(t); (s == ixs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputxstride_i\n"); fflush(stdout); { vsip_tputxstride_i(t,jxs); s = vsip_tgetxstride_i(t); (s == jxs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test tgetystride_i\n"); fflush(stdout); { s = vsip_tgetystride_i(t); (s == iys) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputystride_i\n"); fflush(stdout); { vsip_tputystride_i(t,jys); s = vsip_tgetystride_i(t); (s == jys) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test tgetzstride_i\n"); fflush(stdout); { s = vsip_tgetzstride_i(t); (s == izs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputzstride_i\n"); fflush(stdout); { vsip_tputzstride_i(t,jzs); s = vsip_tgetzstride_i(t); (s == jzs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } vsip_vdestroy_i(v); vsip_mdestroy_i(m); vsip_talldestroy_i(t); } return; } <file_sep>/* Created RJudd September 16, 2000 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cblockadmit_d.c,v 2.1 2006/06/08 22:19:26 judd Exp $ */ #include"vsip.h" #include"vsip_cblockattributes_d.h" int (vsip_cblockadmit_d)( vsip_cblock_d* b, vsip_scalar_bl update) { int blockadmit = (int)update; /* keep update from warning since don't use */ #if defined(VSIP_DEFAULT_SPLIT) #include"VI_cblockadmit_d_ds.h" #elif defined(VSIP_ALWAYS_SPLIT) #include"VI_cblockadmit_d_as.h" #elif defined(VSIP_ALWAYS_INTERLEAVED) #include"VI_cblockadmit_d_ai.h" #else #include"VI_cblockadmit_d_di.h" #endif return blockadmit; } <file_sep>/* // jvsip_svd_f.c // jvsipF // // Created by <NAME> on 4/21/13. // Copyright (c) 2013 Independent Consultant. All rights reserved. */ /********************************************************************* // This code includes no warranty, express or implied, including / // the warranties of merchantability and fitness for a particular / // purpose. / // No person or entity assumes any legal liability or responsibility / // for the accuracy, completeness, or usefulness of any information, / // apparatus, product, or process disclosed, or represents that / // its use would not infringe privately owned rights. / *********************************************************************/ /********************************************************************* // The MIT License (see copyright for jvsip in top level directory) // http://opensource.org/licenses/MIT **********************************************************************/ #include"vsip.h" #include"vsip_svdattributes_f.h" #include"VI.h" #include"vsip_blockattributes_f.h" #include"vsip_cblockattributes_f.h" #include"vsip_blockattributes_vi.h" #include"vsip_vviewattributes_f.h" #include"vsip_mviewattributes_f.h" #include"vsip_cvviewattributes_f.h" #include"vsip_cmviewattributes_f.h" #include"vsip_vviewattributes_vi.h" #define EPS FLT_EPSILON #define VI_VGET_F(v,i) (*(v->block->array + (v->offset + (vsip_stride)(i) * v->stride) * v->block->rstride)) #define scaleV(v) { \ vsip_index k;vsip_scalar_f *p = v->block->array + v->offset * v->block->rstride;\ vsip_stride std = v->stride * v->block->rstride;vsip_length n = v->length * std;\ vsip_scalar_f scl = p[0];p[0]=1.0;for(k=std; k<n; k+=std) p[k] /= scl; \ } #define CMAG_F(re,im) ((re == 0.0) ? im:(im< re) ? re * (vsip_scalar_f)sqrt(1.0 + (im/re) * (im/re)): \ im * (vsip_scalar_f)sqrt(1.0 + (re/im) * (re/im))) /* coded for this routine. Only done in place */ #define csvmul_f(alpha, b) {\ vsip_length _n = b->length; vsip_stride cbst = b->block->cstride;\ vsip_scalar_f *bpr = b->block->R->array + cbst * b->offset,*bpi = b->block->I->array + cbst * b->offset;\ register vsip_scalar_f temp; vsip_stride bst = cbst * b->stride;\ while(_n-- > 0){temp = alpha.r * *bpr - *bpi * alpha.i;*bpi = alpha.r * *bpi + alpha.i * *bpr;*bpr = temp;\ bpr += bst; bpi += bst;}} #define cvcopy_f(a, r) {\ vsip_length _n = (r)->length;vsip_stride cast = (a)->block->cstride,crst = (r)->block->cstride;\ vsip_scalar_f *apr = (a)->block->R->array + cast * (a)->offset,*rpr = (r)->block->R->array + crst * (r)->offset;\ vsip_scalar_f *api = (a)->block->I->array + cast * (a)->offset,*rpi = (r)->block->I->array + crst * (r)->offset;\ vsip_stride ast = (cast * (a)->stride),rst = (crst * (r)->stride);\ while(_n-- > 0){*rpr = *apr;*rpi = *api;apr += ast; api += ast;rpr += rst; rpi += rst;}} #define vcopy_f(a,r) {vsip_length _n = (r)->length;\ vsip_stride ast = (a)->stride * (a)->block->rstride,rst = (r)->stride * (r)->block->rstride;\ vsip_scalar_f *ap = (a)->block->array + (a)->offset * (a)->block->rstride,*rp = (r)->block->array+(r)->offset * (r)->block->rstride;\ while(_n-- > 0){*rp = *ap;ap += ast; rp += rst;}} #define vcopy_vi(a,r) {vsip_length _n = (r)->length;\ vsip_stride ast = (a)->stride,rst = (r)->stride;\ vsip_scalar_vi *ap = (a)->block->array + (a)->offset,*rp = (r)->block->array+(r)->offset;\ while(_n-- > 0){*rp = *ap;ap += ast; rp += rst;}} #define mcopy_f(a,r) {vsip_length n_mj,n_mn;vsip_stride ast_mj, ast_mn,rst_mj, rst_mn;\ vsip_scalar_f *rp = ((r)->block->array) + (r)->offset * (r)->block->rstride,\ *ap = ((a)->block->array) + (a)->offset * (a)->block->rstride;vsip_scalar_f *rp0 = rp,*ap0 = ap;\ if((r)->row_stride < (r)->col_stride){n_mj = (r)->row_length; n_mn = (r)->col_length;\ rst_mj = (r)->row_stride; rst_mn = (r)->col_stride;ast_mj = (a)->row_stride; ast_mn = (a)->col_stride;\ rst_mj *= (r)->block->rstride; rst_mn *= (r)->block->rstride;ast_mj *= (a)->block->rstride; ast_mn *= (a)->block->rstride;\ } else {n_mn = (r)->row_length; n_mj = (r)->col_length;\ rst_mn = (r)->row_stride; rst_mj = (r)->col_stride;ast_mn = (a)->row_stride; ast_mj = (a)->col_stride;\ rst_mn *= (r)->block->rstride; rst_mj *= (r)->block->rstride;ast_mn *= (a)->block->rstride; ast_mj *= (a)->block->rstride;\ } while(n_mn-- > 0){vsip_length n = n_mj;while(n-- >0){*rp = *ap;ap += ast_mj; rp += rst_mj;\ }ap0 += ast_mn; rp0 += rst_mn;ap = ap0; rp = rp0;}} #define cmcopy_f(a,r) {vsip_length n_mj, n_mn; vsip_stride ast_mj, ast_mn,rst_mj, rst_mn; \ vsip_scalar_f *ap_r = (a)->block->R->array + (a)->offset * (a)->block->cstride,*rp_r = (r)->block->R->array + (r)->offset * (r)->block->cstride;\ vsip_scalar_f *ap_i = (a)->block->I->array + (a)->offset * (a)->block->cstride,*rp_i = (r)->block->I->array + (r)->offset * (r)->block->cstride;\ vsip_scalar_f *ap0_r = ap_r,*rp0_r = rp_r,*ap0_i = ap_i,*rp0_i = rp_i;\ if((r)->row_stride < (r)->col_stride){n_mj = (r)->row_length; n_mn = (r)->col_length;\ rst_mj = (r)->row_stride; rst_mn = (r)->col_stride;ast_mj = (a)->row_stride; ast_mn = (a)->col_stride;\ rst_mj *= (r)->block->cstride; rst_mn *= (r)->block->cstride;ast_mj *= (a)->block->cstride; ast_mn *= (a)->block->cstride;\ } else {n_mn = (r)->row_length; n_mj = (r)->col_length;\ rst_mn = (r)->row_stride; rst_mj = (r)->col_stride;ast_mn = (a)->row_stride; ast_mj = (a)->col_stride;\ rst_mn *= (r)->block->cstride; rst_mj *= (r)->block->cstride;ast_mn *= (a)->block->cstride; ast_mj *= (a)->block->cstride;}\ while(n_mn-- > 0){vsip_length n = n_mj;while(n-- >0){*rp_r = *ap_r;*rp_i = *ap_i;ap_r += ast_mj; rp_r += rst_mj;\ ap_i += ast_mj; rp_i += rst_mj;}ap0_r += ast_mn; rp0_r += rst_mn;ap0_i += ast_mn; rp0_i += rst_mn;\ ap_r = ap0_r; rp_r = rp0_r; ap_i = ap0_i; rp_i = rp0_i;}} #define cmherm_f(_A,_R) { \ vsip_length lx = _A->row_length,ly = _A->col_length;vsip_stride cAst = _A->block->cstride,cRst = _R->block->cstride;\ vsip_scalar_f *a_p_r = _A->block->R->array + cAst * _A->offset,\ *a_p_i = _A->block->I->array + cAst * _A->offset,*r_p_r = _R->block->R->array + cRst * _R->offset, *r_p_i;vsip_length i, j;\ vsip_stride stAx = cAst * _A->row_stride, stAy = cAst *_A->col_stride, stRx = cRst * _R->row_stride,stRy = cRst *_R->col_stride;\ for(i=0; i<ly; i++){\ r_p_r = _R->block->R->array + cRst * _R->offset + i * stRx;r_p_i = _R->block->I->array + cRst * _R->offset + i * stRx;\ a_p_r = _A->block->R->array + cAst * _A->offset + i * stAy;a_p_i = _A->block->I->array + cAst * _A->offset + i * stAy;\ for(j=0; j<lx; j++){*r_p_r = *a_p_r;*r_p_i = - *a_p_i;r_p_r += stRy; a_p_r += stAx;r_p_i += stRy; a_p_i += stAx;}}} #define cmconj_f( a, r) { vsip_length n_mj, n_mn; vsip_stride ast_mj, ast_mn, rst_mj, rst_mn; \ vsip_scalar_f *ap_r = (a)->block->R->array + (a)->offset * (a)->block->cstride, *rp_r = (r)->block->R->array + (r)->offset * (r)->block->cstride, \ *ap_i = (a)->block->I->array + (a)->offset * (a)->block->cstride, *rp_i = (r)->block->I->array + (r)->offset * (r)->block->cstride, \ *ap0_r = ap_r, *rp0_r = rp_r, *ap0_i = ap_i, *rp0_i = rp_i; \ if((r)->row_stride < (r)->col_stride){ n_mj = (r)->row_length; n_mn = (r)->col_length; \ rst_mj = (r)->row_stride; rst_mn = (r)->col_stride; ast_mj = (a)->row_stride; ast_mn = (a)->col_stride; \ rst_mj *= (r)->block->cstride; rst_mn *= (r)->block->cstride; ast_mj *= (a)->block->cstride; ast_mn *= (a)->block->cstride; \ } else { n_mn = (r)->row_length; n_mj = (r)->col_length; \ rst_mn = (r)->row_stride; rst_mj = (r)->col_stride; ast_mn = (a)->row_stride; ast_mj = (a)->col_stride; \ rst_mn *= (r)->block->cstride; rst_mj *= (r)->block->cstride; ast_mn *= (a)->block->cstride; ast_mj *= (a)->block->cstride; \ } while(n_mn-- > 0){ vsip_length _n = n_mj; while(_n-- >0){ \ *rp_r = *ap_r; *rp_i = - *ap_i; ap_r += ast_mj; rp_r += rst_mj; ap_i += ast_mj; rp_i += rst_mj; \ } ap0_r += ast_mn; rp0_r += rst_mn; ap_r = ap0_r; rp_r = rp0_r; ap0_i += ast_mn; rp0_i += rst_mn; ap_i = ap0_i;rp_i = rp0_i;}} #define mpermute_onceCol_f(in, p){ vsip_scalar_f *ptr,t;vsip_length ndta, n_ind; vsip_stride indta_strd, in_ind_strd; \ register vsip_index to0; register vsip_index from0; vsip_index _i,_j,*b,from,to;\ ndta = in->col_length; n_ind = in->row_length; indta_strd = in->col_stride * in->block->rstride;\ in_ind_strd = in->row_stride * in->block->rstride; ptr = in->block->array + in->offset * in->block->rstride;\ b = p->block->array + p->offset; for(_i=0; _i<n_ind; _i++){ vsip_index r_or_c = b[_i * p->stride];\ from0 = b[_i * p->stride] * in_ind_strd; to0 = _i * in_ind_strd;\ if(from0 != to0) { for(_j=0; _j<ndta; _j++){to = to0 + _j * indta_strd, from = from0 + _j * indta_strd;\ t = ptr[to]; ptr[to] = ptr[from]; ptr[from] = t; } _j=_i;\ while(_i != b[_j * p->stride]){ _j++; if(_j > n_ind) exit(-1); } b[_j * p->stride] = r_or_c;}}} #define mpermute_onceRow_f(in, p) { vsip_index _i,_j,from,to; vsip_length ndta, n_ind; \ vsip_stride indta_strd=in->row_stride * in->block->rstride,in_ind_strd=in->col_stride * in->block->rstride;\ vsip_scalar_f *ptr = in->block->array + in->offset * in->block->rstride,t;\ vsip_scalar_vi *b = p->block->array + p->offset; ndta = in->row_length; n_ind = in->col_length;\ for(_i=0; _i<n_ind; _i++){ vsip_index r_or_c = b[_i * p->stride]; \ register vsip_index from0 = b[_i * p->stride] * in_ind_strd; register vsip_index to0 = _i * in_ind_strd;\ if(from0 != to0) { for(_j=0; _j<ndta; _j++){ to = to0 + _j * indta_strd; from = from0 + _j * indta_strd;\ t = ptr[to]; ptr[to] = ptr[from]; ptr[from] = t; } _j=_i; while(_i != b[_j * p->stride])\ { _j++; if(_j > n_ind) exit(-1);}b[_j * p->stride] = r_or_c; } } } #define cmpermute_onceCol_f(in, p){\ vsip_length ndta=in->col_length, n_ind=in->row_length; vsip_stride indta_strd, in_ind_strd; vsip_index _i,_j;\ vsip_scalar_f *ptr_re = in->block->R->array + in->offset * in->block->cstride, \ *ptr_im = in->block->I->array + in->offset * in->block->cstride;\ vsip_scalar_vi *b = p->block->array + p->offset;\ indta_strd = in->col_stride * in->block->cstride; in_ind_strd = in->row_stride * in->block->cstride;\ for(_i=0; _i<n_ind; _i++){vsip_index r_or_c = b[_i * p->stride]; \ register vsip_index from0 = b[_i * p->stride] * in_ind_strd; register vsip_index to0 = _i * in_ind_strd;\ if(from0 != to0) { for(_j=0; _j<ndta; _j++){ vsip_index to = to0 + _j * indta_strd; \ vsip_index from = from0 + _j * indta_strd;vsip_scalar_f t = ptr_re[to]; ptr_re[to] = ptr_re[from];\ ptr_re[from] = t; t = ptr_im[to];ptr_im[to] = ptr_im[from]; ptr_im[from] = t;\ }_j=_i; while(_i != b[_j * p->stride]){ _j++; if(_j > n_ind) exit(-1); } b[_j * p->stride] = r_or_c; } } } #define cmpermute_onceRow_f( in, p){\ vsip_length ndta, n_ind; vsip_stride indta_strd, in_ind_strd; vsip_index _i,_j;\ vsip_scalar_f *ptr_re = in->block->R->array + in->offset * in->block->cstride, \ *ptr_im = in->block->I->array + in->offset * in->block->cstride;\ vsip_scalar_vi *b = p->block->array + p->offset; ndta = in->row_length; n_ind = in->col_length;\ indta_strd = in->row_stride * in->block->cstride; in_ind_strd = in->col_stride * in->block->cstride;\ for(_i=0; _i<n_ind; _i++){ vsip_index r_or_c = b[_i * p->stride]; \ register vsip_index from0 = b[_i * p->stride] * in_ind_strd; register vsip_index to0 = _i * in_ind_strd;\ if(from0 != to0) { for(_j=0; _j<ndta; _j++){ vsip_index to = to0 + _j * indta_strd; \ vsip_index from = from0 + _j * indta_strd;vsip_scalar_f t = ptr_re[to]; ptr_re[to] = ptr_re[from]; \ ptr_re[from] = t; t = ptr_im[to]; ptr_im[to] = ptr_im[from]; ptr_im[from] = t;\ }_j=_i; while(_i != b[_j * p->stride]){ _j++; if(_j > n_ind) exit(-1); } b[_j * p->stride] = r_or_c;}}} #define vmprod_f(a,B,r) {vsip_length nx=0,mx=0;\ vsip_scalar_f *ap=(a)->block->array+(a)->offset * (a)->block->rstride,*ap0=ap,\ *rp=(r)->block->array+(r)->offset * (r)->block->rstride, *Byp=(B)->block->array+(B)->offset * (B)->block->rstride,*Bxp = Byp;\ vsip_stride BCst = (B)->col_stride * (B)->block->rstride,BRst=(B)->row_stride * (B)->block->rstride,\ rst = (r)->stride * (r)->block->rstride; while(nx++ < (B)->row_length){*rp=0;mx=0;\ while(mx++ < (B)->col_length){ *rp += *ap * *Byp; ap += (a)->stride; Byp += BCst; }ap = ap0; Byp = (Bxp += BRst); rp += rst;}} #define mvprod_f(_A, _b, _r) {vsip_length nx=0, mx=0;\ vsip_scalar_f *bp=(_b)->block->array+(_b)->offset * (_b)->block->rstride,\ *rp=(_r)->block->array+(_r)->offset * (_r)->block->rstride, *Ayp=(_A)->block->array+(_A)->offset * (_A)->block->rstride, *Axp=Ayp;\ vsip_stride rst=(_r)->stride * (_r)->block->rstride, ARst=(_A)->row_stride * (_A)->block->rstride,\ ACst=(_A)->col_stride * (_A)->block->rstride, bst=(_b)->stride * (_b)->block->rstride;\ while(nx++ < (_A)->col_length){ *rp=0; mx=0; while(mx++ < (_A)->row_length){ *rp += *bp * *Axp; bp += bst; Axp += ARst; }\ bp=(_b)->block->array+(_b)->offset * (_b)->block->rstride; Axp=(Ayp += ACst); rp += rst; } } #define cvmprod_f(_a,_B,_r) { vsip_length nx = 0, mx = 0; \ vsip_stride cast = (_a)->block->cstride, crst = (_r)->block->cstride, cBst = (_B)->block->cstride;\ vsip_scalar_f *ap_r = (vsip_scalar_f*)((_a)->block->R->array + cast * (_a)->offset),\ *ap_i = (vsip_scalar_f*)((_a)->block->I->array + cast * (_a)->offset),\ *rp_r = (vsip_scalar_f*)((_r)->block->R->array + crst * (_r)->offset),\ *rp_i = (vsip_scalar_f*)((_r)->block->I->array + crst * (_r)->offset),\ *Byp_r = (vsip_scalar_f*)((_B)->block->R->array + cBst * (_B)->offset),\ *Byp_i = (vsip_scalar_f*)((_B)->block->I->array + cBst * (_B)->offset),\ *Bxpr = Byp_r, *Bxpi = Byp_i; vsip_stride sta = cast * (_a)->stride, str = crst * (_r)->stride, stB = cBst * (_B)->col_stride;\ while(nx++ < (_B)->row_length){ *rp_r = 0; *rp_i = 0; mx = 0;\ while(mx++ < (_B)->col_length){\ *rp_r += *ap_r * *Byp_r - *ap_i * *Byp_i; \ *rp_i += *ap_i * *Byp_r + *ap_r * *Byp_i;\ ap_r += sta; Byp_r += stB; ap_i += sta; Byp_i += stB; } \ ap_r = (vsip_scalar_f*)((_a)->block->R->array + cast * (_a)->offset); ap_i = (vsip_scalar_f*)((_a)->block->I->array + cast * (_a)->offset);\ Byp_r = (Bxpr += (cBst * (_B)->row_stride)); Byp_i = (Bxpi += (cBst * (_B)->row_stride)); rp_r += str; rp_i += str;}} #define cvmprodj_f(_a,_B,_r) { vsip_length nx = 0, mx = 0; \ vsip_stride cast = (_a)->block->cstride, crst = (_r)->block->cstride, cBst = (_B)->block->cstride;\ vsip_scalar_f *ap_r = (vsip_scalar_f*)((_a)->block->R->array + cast * (_a)->offset),\ *ap_i = (vsip_scalar_f*)((_a)->block->I->array + cast * (_a)->offset),\ *rp_r = (vsip_scalar_f*)((_r)->block->R->array + crst * (_r)->offset),\ *rp_i = (vsip_scalar_f*)((_r)->block->I->array + crst * (_r)->offset),\ *Byp_r = (vsip_scalar_f*)((_B)->block->R->array + cBst * (_B)->offset),\ *Byp_i = (vsip_scalar_f*)((_B)->block->I->array + cBst * (_B)->offset),\ *Bxpr = Byp_r, *Bxpi = Byp_i; vsip_stride sta = cast * (_a)->stride, str = crst * (_r)->stride, stB = cBst * (_B)->col_stride;\ while(nx++ < (_B)->row_length){ *rp_r = 0; *rp_i = 0; mx = 0;\ while(mx++ < (_B)->col_length){ \ *rp_r += *ap_r * *Byp_r + *ap_i * *Byp_i; \ *rp_i += *ap_i * *Byp_r - *ap_r * *Byp_i;\ ap_r += sta; Byp_r += stB; ap_i += sta; Byp_i += stB; } \ ap_r = (vsip_scalar_f*)((_a)->block->R->array + cast * (_a)->offset); ap_i = (vsip_scalar_f*)((_a)->block->I->array + cast * (_a)->offset);\ Byp_r = (Bxpr += (cBst * (_B)->row_stride)); Byp_i = (Bxpi += (cBst * (_B)->row_stride)); rp_r += str; rp_i += str;}} #define cmvprod_f(_A,_b,_r){ \ if(((_A)->block->cstride == 2) && ((_b)->block->cstride == 2) && ((_r)->block->cstride == 2)){\ vsip_length nx = 0, mx = 0; vsip_stride cbst = (_b)->block->cstride, crst = (_b)->block->cstride, cAst = (_A)->block->cstride;\ vsip_scalar_f *bp_r = (vsip_scalar_f*)((_b)->block->R->array + cbst * (_b)->offset),\ *rp_r = (vsip_scalar_f*)((_r)->block->R->array + crst * (_r)->offset),\ *Axp_r = (vsip_scalar_f*)((_A)->block->R->array + cAst * (_A)->offset),\ *Aypr = Axp_r; vsip_stride stb = cbst * (_b)->stride, str = crst * (_r)->stride, stA = cAst * (_A)->row_stride;\ vsip_scalar_f dot_r, dot_i; while(nx++ < (_A)->col_length){ mx = 0; dot_r = 0; dot_i = 0;\ while(mx++ < (_A)->row_length){ vsip_scalar_f Ar = *Axp_r, Ai = *(Axp_r + 1); vsip_scalar_f br = *bp_r, bi = *(bp_r + 1);\ dot_r += br * Ar - bi * Ai; \ dot_i += bi * Ar + br * Ai; \ bp_r += stb; Axp_r += stA; } *rp_r = dot_r; *(rp_r + 1) = dot_i;\ bp_r = (vsip_scalar_f*)((_b)->block->R->array + cbst * (_b)->offset); Axp_r = (Aypr += (cAst * (_A)->col_stride));rp_r += str;}\ } else { vsip_length nx = 0, mx = 0;\ vsip_stride cbst = (_b)->block->cstride, crst = (_r)->block->cstride, cAst = (_A)->block->cstride;\ vsip_scalar_f *bp_r = (vsip_scalar_f*)((_b)->block->R->array + cbst * (_b)->offset),\ *bp_i = (vsip_scalar_f*)((_b)->block->I->array + cbst * (_b)->offset),\ *rp_r = (vsip_scalar_f*)((_r)->block->R->array + crst * (_r)->offset),\ *rp_i = (vsip_scalar_f*)((_r)->block->I->array + crst * (_r)->offset),\ *Axp_r = (vsip_scalar_f*)((_A)->block->R->array + cAst * (_A)->offset),\ *Axp_i = (vsip_scalar_f*)((_A)->block->I->array + cAst * (_A)->offset),\ *Aypr = Axp_r, *Aypi = Axp_i; vsip_stride stb = cbst * (_b)->stride, str = crst * (_r)->stride, stA = cAst * (_A)->row_stride;\ vsip_scalar_f dot_r, dot_i; while(nx++ < (_A)->col_length){ dot_r = 0; dot_i = 0; mx = 0;\ while(mx++ < (_A)->row_length){ \ dot_r += *bp_r * *Axp_r - *bp_i * *Axp_i; \ dot_i += *bp_i * *Axp_r + *bp_r * *Axp_i;\ bp_r += stb; Axp_r += stA; bp_i += stb; Axp_i += stA; }\ *rp_r = dot_r; *rp_i = dot_i; bp_r = (vsip_scalar_f*)((_b)->block->R->array + cbst * (_b)->offset);\ bp_i = (vsip_scalar_f*)((_b)->block->I->array + cbst * (_b)->offset); Axp_r = (Aypr += (cAst * (_A)->col_stride));\ Axp_i = (Aypi += (cAst * (_A)->col_stride)); rp_r += str; rp_i += str; }}} #define cmvjprod_f(_A,_b,_r){ \ if(((_A)->block->cstride == 2) && ((_b)->block->cstride == 2) && ((_r)->block->cstride == 2)){\ vsip_length nx = 0, mx = 0; vsip_stride cbst = (_b)->block->cstride, crst = (_b)->block->cstride, cAst = (_A)->block->cstride;\ vsip_scalar_f *bp_r = (vsip_scalar_f*)((_b)->block->R->array + cbst * (_b)->offset),\ *rp_r = (vsip_scalar_f*)((_r)->block->R->array + crst * (_r)->offset),\ *Axp_r = (vsip_scalar_f*)((_A)->block->R->array + cAst * (_A)->offset),\ *Aypr = Axp_r; vsip_stride stb = cbst * (_b)->stride, str = crst * (_r)->stride, stA = cAst * (_A)->row_stride;\ vsip_scalar_f dot_r, dot_i; while(nx++ < (_A)->col_length){ mx = 0; dot_r = 0; dot_i = 0;\ while(mx++ < (_A)->row_length){ vsip_scalar_f Ar = *Axp_r, Ai = *(Axp_r + 1); vsip_scalar_f br = *bp_r, bi = *(bp_r + 1);\ dot_r += br * Ar + bi * Ai; \ dot_i += bi * Ar - br * Ai ; \ bp_r += stb; Axp_r += stA; } *rp_r = dot_r; *(rp_r + 1) = dot_i;\ bp_r = (vsip_scalar_f*)((_b)->block->R->array + cbst * (_b)->offset); Axp_r = (Aypr += (cAst * (_A)->col_stride));rp_r += str;}\ } else { vsip_length nx = 0, mx = 0;\ vsip_stride cbst = (_b)->block->cstride, crst = (_r)->block->cstride, cAst = (_A)->block->cstride;\ vsip_scalar_f *bp_r = (vsip_scalar_f*)((_b)->block->R->array + cbst * (_b)->offset),\ *bp_i = (vsip_scalar_f*)((_b)->block->I->array + cbst * (_b)->offset),\ *rp_r = (vsip_scalar_f*)((_r)->block->R->array + crst * (_r)->offset),\ *rp_i = (vsip_scalar_f*)((_r)->block->I->array + crst * (_r)->offset),\ *Axp_r = (vsip_scalar_f*)((_A)->block->R->array + cAst * (_A)->offset),\ *Axp_i = (vsip_scalar_f*)((_A)->block->I->array + cAst * (_A)->offset),\ *Aypr = Axp_r, *Aypi = Axp_i; vsip_stride stb = cbst * (_b)->stride, str = crst * (_r)->stride, stA = cAst * (_A)->row_stride;\ vsip_scalar_f dot_r, dot_i; while(nx++ < (_A)->col_length){ dot_r = 0; dot_i = 0; mx = 0;\ while(mx++ < (_A)->row_length){ \ dot_r += *bp_r * *Axp_r + *bp_i * *Axp_i; \ dot_i += *bp_i * *Axp_r - *bp_r * *Axp_i; \ bp_r += stb; Axp_r += stA; bp_i += stb; Axp_i += stA; }\ *rp_r = dot_r; *rp_i = dot_i; bp_r = (vsip_scalar_f*)((_b)->block->R->array + cbst * (_b)->offset);\ bp_i = (vsip_scalar_f*)((_b)->block->I->array + cbst * (_b)->offset); Axp_r = (Aypr += (cAst * (_A)->col_stride));\ Axp_i = (Aypi += (cAst * (_A)->col_stride)); rp_r += str; rp_i += str; }}} #define svmul_f(alpha, _b, _r) {vsip_length n = (_r)->length;\ vsip_stride bst=(_b)->stride * (_b)->block->rstride, rst = (_r)->stride * (_r)->block->rstride;\ vsip_scalar_f *bp=(_b)->block->array+(_b)->offset * (_b)->block->rstride, *rp=(_r)->block->array+(_r)->offset * (_r)->block->rstride;\ while(n-- > 0){ *rp = alpha * *bp; bp += bst; rp += rst;}} #define mtrans_f(A, R) { vsip_length lx = (A)->row_length, ly = (A)->col_length; vsip_index i, j; vsip_scalar_f tmp;\ vsip_scalar_f *a_p = (A)->block->array + (A)->offset * (A)->block->rstride, *r_p = R->block->array + R->offset * R->block->rstride;\ vsip_stride stAx = (A)->row_stride * (A)->block->rstride, stAy = (A)->col_stride * (A)->block->rstride,\ stRx = R->row_stride * R->block->rstride, stRy = R->col_stride * R->block->rstride;\ if((lx == ly) && (a_p == r_p)){ for(i=1; i<lx; i++){ for(j=0; j<i; j++){ tmp = *(a_p + j * stAy + i * stAx);\ *(a_p + j * stAy + i * stAx) = *(a_p + j * stAx + i * stAy); *(a_p + j * stAx + i * stAy) = tmp; } }\ } else { for(i=0; i<ly; i++){ r_p = R->block->array + R->offset * R->block->rstride + i * stRx;\ a_p = (A)->block->array + (A)->offset * (A)->block->rstride + i * stAy; for(j=0; j<lx; j++){ *r_p = *a_p;\ r_p += stRy; a_p += stAx; } } } } typedef struct {vsip_index i; vsip_index j;} svdCorner; typedef struct {vsip_scalar_f c; vsip_scalar_f s; vsip_scalar_f r;}givensObj_f ; static svdObj_f *svdInit_f(vsip_length, vsip_length,int,int); static void svdFinalize_f(svdObj_f*); static void svd_f(svdObj_f*,int,int); static csvdObj_f *csvdInit_f(vsip_length, vsip_length,int,int); static void csvdFinalize_f(csvdObj_f*); static void csvd_f(csvdObj_f*,int,int); static vsip_scalar_f hypot_f(vsip_scalar_f a0,vsip_scalar_f b0){ vsip_scalar_f a = (a0 < 0.0) ? -a0:a0; vsip_scalar_f b = (b0 < 0.0) ? -b0:b0; if (a == 0.0) return b; else if (b == 0.0) return a; else if (b < a) return a * (vsip_scalar_f)sqrt(1.0 + (b/a) * (b/a)); else return b * (vsip_scalar_f)sqrt(1.0 + (a/b) * (a/b)); } static vsip_vview_f *vsv_f(vsip_vview_f *v, vsip_vview_f *vs, vsip_index i) { *vs=*v; vs->offset += i * vs->stride; vs->length -= i; return vs; } static vsip_mview_f* msv_f(vsip_mview_f *B,vsip_mview_f *BS, vsip_index i,vsip_index j) { *BS = *B; BS->row_length -= j; BS->col_length -= i; BS->offset += j * BS->row_stride + i * BS->col_stride; return BS; } static vsip_mview_f* imsv_f( vsip_mview_f *B, vsip_mview_f *BS, vsip_index i1,vsip_index j1, vsip_index i2, vsip_index j2) { *BS=*B; if(j1 == 0) j1 =(B)->col_length; if(j2 == 0) j2 =(B)->row_length; BS->col_length = (j1 - i1); BS->row_length = (j2 - i2); BS->offset += i2 * B->row_stride + i1 * B->col_stride; return BS; } static vsip_vview_f *ivsv_f( vsip_vview_f *v, vsip_vview_f *vs, vsip_index i,vsip_index j) { *vs=*v; if(j==0) j=v->length; vs->offset += i * v->stride; vs->length = j-i; return vs; } static vsip_vview_f *col_sv_f(vsip_mview_f*Am,vsip_vview_f* vv,vsip_index col) { vv->block = Am->block; vv->offset = Am->offset + col * Am->row_stride; vv->stride = Am->col_stride; vv->length = Am->col_length; return vv; } static vsip_vview_f *row_sv_f(vsip_mview_f*Am,vsip_vview_f* vv,vsip_index row) { vv->block = Am->block; vv->offset = Am->offset + row * Am->col_stride; vv->stride = Am->row_stride; vv->length = Am->row_length; return vv; } static vsip_vview_f *diag_sv_f(vsip_mview_f* Am,vsip_vview_f* a, vsip_stride i) { a->block = Am->block; a->stride=Am->row_stride + Am->col_stride; if(i==0){ a->length = Am->row_length; a->offset = Am->offset; } else if (i == 1){ a->offset = Am->offset + Am->row_stride; a->length = Am->row_length - 1; } else { printf("Failed in diag_sv_f\n"); exit(0); } return a; } static vsip_cmview_f* cimsv_f( vsip_cmview_f *B, vsip_cmview_f *BS, vsip_index i1,vsip_index j1, vsip_index i2, vsip_index j2) { *BS=*B; if(j1 == 0) j1 =B->col_length; if(j2 == 0) j2 =B->row_length; BS->col_length = (j1 - i1); BS->row_length = (j2 - i2); BS->offset += i2 * B->row_stride + i1 * B->col_stride; return BS; } static vsip_cvview_f *ccol_sv_f(vsip_cmview_f*Am,vsip_cvview_f* vv,vsip_index col) { vv->block = Am->block; vv->offset = Am->offset + col * Am->row_stride; vv->stride = Am->col_stride; vv->length = Am->col_length; return vv; } static vsip_cvview_f *crow_sv_f(vsip_cmview_f*Am,vsip_cvview_f* vv,vsip_index row) { vv->block=Am->block; vv->offset = Am->offset + row * Am->col_stride; vv->stride = Am->row_stride; vv->length = Am->row_length; return vv; } static vsip_cvview_f *cdiag_sv_f(vsip_cmview_f* Am,vsip_cvview_f* a, vsip_stride i) { a->block = Am->block; a->stride=Am->row_stride + Am->col_stride; if(i==0){ a->length = Am->row_length; a->offset = Am->offset; } else if (i == 1){ a->offset = Am->offset + Am->row_stride; a->length = Am->row_length - 1; } else { printf("Failed in diag_sv_f\n"); exit(0); } return a; } static vsip_scalar_f vnorm2_f(vsip_vview_f *a) { vsip_length n = a->length; vsip_stride ast = a->stride * a->block->rstride; vsip_scalar_f *ap = (a->block->array) + a->offset * a->block->rstride,t = 0; while(n-- > 0){ t += (*ap * *ap); ap += ast; } return (vsip_scalar_f)sqrt(t); } static vsip_scalar_f mnormFro_f(vsip_mview_f *v) { vsip_length m=v->col_length,n=v->row_length; vsip_index i,j; vsip_stride rstrd=v->row_stride*v->block->rstride; vsip_stride cstrd=v->col_stride*v->block->rstride; vsip_scalar_f *vre=v->block->array+v->offset*v->block->rstride; vsip_scalar_f re=0.0; for(i=0; i<m; i++){ vsip_offset o=i*cstrd; vsip_scalar_f *rp=vre+o; for(j=0; j<n; j++){ re += *rp * *rp; rp += rstrd; } } return sqrt(re); } static void meye_f(vsip_mview_f *v) { vsip_length m=v->col_length,n=v->row_length; vsip_index i,j; vsip_stride rstrd=v->row_stride*v->block->rstride; vsip_stride cstrd=v->col_stride*v->block->rstride; vsip_scalar_f *vre=v->block->array+v->offset*v->block->rstride; for(i=0; i<m; i++){ vsip_offset o=i*cstrd; vsip_scalar_f *rp=vre+o; for(j=0; j<n; j++){ *rp = (i==j) ? 1.0:0.0; rp += rstrd; } } } /* sign function as defined in http://www.netlib.org/lapack/lawnspdf/lawn148.pdf */ static vsip_scalar_f sign_f(vsip_scalar_f a_in) { return (a_in < 0.0) ? -1.0:1.0; } static vsip_cscalar_f csign_f(vsip_cscalar_f a_in) { vsip_scalar_f re = a_in.r < 0.0 ? -a_in.r:a_in.r; vsip_scalar_f im = a_in.i < 0.0 ? -a_in.i:a_in.i; vsip_scalar_f t= (re==0.0) ? im: ((im==0.0) ? re:((re<im) ? im*sqrt(1.0 + re/im*re/im):re*sqrt(1.0+im/re*im/re))); vsip_cscalar_f retval; retval.r=0.0; retval.i = 0.0; if(t == 0.0){ retval.r = 1.0; return retval; } else if (im==0.0) { retval.r = (a_in.r < 0.0) ? -1.0:1.0; return retval; } else { retval.r = a_in.r/t; retval.i = a_in.i/t; return retval; } } static void phaseCheck_f(svdObj_f *svd) { vsip_scalar_f *fptr, *dptr; vsip_mview_f *L = svd->L; vsip_vview_f *d = svd->d; vsip_vview_f *f = svd->f; vsip_scalar_f eps0 = svd->eps0; vsip_length nd=d->length; vsip_length nf=f->length; vsip_index i; vsip_scalar_f ps; vsip_scalar_f m; vsip_vview_f *l = &svd->ls_one; vsip_stride fstrd=f->stride * d->block->rstride; vsip_stride dstrd=d->stride * d->block->rstride; dptr=d->block->array +d->offset * d->block->rstride; fptr=f->block->array + f->offset * f->block->rstride; for(i=0; i<nd; i++){ ps=*dptr; m = (ps<0) ? -ps:ps; ps=sign_f(ps); if(m > eps0){ col_sv_f(L,l,i); { vsip_scalar_f *p = l->block->array + l->offset * l->block->rstride; vsip_stride std = l->stride * l->block->rstride; vsip_length n = l->length * std; vsip_index k; for(k=0; k<n; k+=std) p[k] *= ps; } *dptr=m; if (i < nf) *fptr *= ps; } else { *dptr = 0.0; } dptr+=dstrd;fptr+=fstrd; } dptr=d->block->array +d->offset * d->block->rstride; fptr=f->block->array + f->offset * f->block->rstride; for(i=0; i<nf; i++){ vsip_scalar_f f_i= fabs(*fptr); m = (*dptr + *(dptr+dstrd)) * eps0; if (f_i < m) *fptr = 0.0; dptr+=dstrd;fptr+=fstrd; } } static void phaseCheck2_f(svdObj_f *svd) /* save U */ { vsip_scalar_f *fptr, *dptr; vsip_mview_f *L = svd->L; vsip_vview_f *d = svd->d; vsip_vview_f *f = svd->f; vsip_scalar_f eps0 = svd->eps0; vsip_length nd=d->length; vsip_length nf=f->length; vsip_index i; vsip_scalar_f ps; vsip_scalar_f m; vsip_vview_f *l = &svd->ls_one; vsip_stride fstrd=f->stride * d->block->rstride; vsip_stride dstrd=d->stride * d->block->rstride; dptr=d->block->array +d->offset * d->block->rstride; fptr=f->block->array + f->offset * f->block->rstride; for(i=0; i<nd; i++){ ps=*dptr; m = (ps<0) ? -ps:ps; ps=sign_f(ps); if(m > eps0){ col_sv_f(L,l,i); { vsip_scalar_f *p = l->block->array + l->offset * l->block->rstride; vsip_stride std = l->stride * l->block->rstride; vsip_length n = l->length * std; vsip_index k; for(k=0; k<n; k+=std) p[k] *= ps; } *dptr=m; if (i < nf) *fptr *= ps; } else { *dptr = 0.0; } dptr+=dstrd;fptr+=fstrd; } dptr=d->block->array +d->offset * d->block->rstride; fptr=f->block->array + f->offset * f->block->rstride; for(i=0; i<nf; i++){ vsip_scalar_f f_i= fabs(*fptr); m = (*dptr + *(dptr+dstrd)) * eps0; if (f_i < m) *fptr = 0.0; dptr+=dstrd;fptr+=fstrd; } } static void phaseCheck1_f(svdObj_f *svd) /* save V */ { vsip_scalar_f *fptr, *dptr; vsip_vview_f *d = svd->d; vsip_vview_f *f = svd->f; vsip_scalar_f eps0 = svd->eps0; vsip_length nd=d->length; vsip_length nf=f->length; vsip_index i; vsip_scalar_f ps; vsip_scalar_f m; vsip_stride fstrd=f->stride * d->block->rstride; vsip_stride dstrd=d->stride * d->block->rstride; dptr=d->block->array +d->offset * d->block->rstride; fptr=f->block->array + f->offset * f->block->rstride; for(i=0; i<nd; i++){ ps=*dptr; m = (ps<0) ? -ps:ps; ps=sign_f(ps); if(m > eps0){ *dptr=m; if (i < nf) *fptr *= ps; } else { *dptr = 0.0; } dptr+=dstrd;fptr+=fstrd; } dptr=d->block->array +d->offset * d->block->rstride; fptr=f->block->array + f->offset * f->block->rstride; for(i=0; i<nf; i++){ vsip_scalar_f f_i= fabs(*fptr); m = (*dptr + *(dptr+dstrd)) * eps0; if (f_i < m) *fptr = 0.0; dptr+=dstrd;fptr+=fstrd; } } static void phaseCheck0_f(svdObj_f *svd) { vsip_scalar_f *fptr, *dptr; vsip_vview_f *d = svd->d; vsip_vview_f *f = svd->f; vsip_scalar_f eps0 = svd->eps0; vsip_length nd=d->length; vsip_length nf=f->length; vsip_index i; vsip_scalar_f ps; vsip_scalar_f m; vsip_stride fstrd=f->stride * d->block->rstride; vsip_stride dstrd=d->stride * d->block->rstride; dptr=d->block->array +d->offset * d->block->rstride; fptr=f->block->array + f->offset * f->block->rstride; for(i=0; i<nd; i++){ ps=*dptr; m = (ps<0) ? -ps:ps; ps=sign_f(ps); if(m > eps0){ *dptr=m; if (i < nf) *fptr *= ps; } else { *dptr = 0.0; } dptr+=dstrd;fptr+=fstrd; } dptr=d->block->array +d->offset * d->block->rstride; fptr=f->block->array + f->offset * f->block->rstride; for(i=0; i<nf; i++){ vsip_scalar_f f_i= fabs(*fptr); m = (*dptr + *(dptr+dstrd)) * eps0; if (f_i < m) *fptr = 0.0; dptr+=dstrd;fptr+=fstrd; } } static void biDiagPhaseToZero_f( svdObj_f *svd) { vsip_vview_f *x=&svd->bs,*v=svd->d; diag_sv_f(&svd->B,x,0); vcopy_f(x,v); diag_sv_f(&svd->B,x,1); v=svd->f; vcopy_f(x,v); phaseCheck_f(svd); } static void biDiagPhaseToZero2_f( svdObj_f *svd) { vsip_vview_f *x=&svd->bs,*v=svd->d; diag_sv_f(&svd->B,x,0); vcopy_f(x,v); diag_sv_f(&svd->B,x,1); v=svd->f; vcopy_f(x,v); phaseCheck2_f(svd); } static void biDiagPhaseToZero1_f( svdObj_f *svd) { vsip_vview_f *x=&svd->bs,*v=svd->d; diag_sv_f(&svd->B,x,0); vcopy_f(x,v); diag_sv_f(&svd->B,x,1); v=svd->f; vcopy_f(x,v); phaseCheck1_f(svd); } static void biDiagPhaseToZero0_f( svdObj_f *svd) { vsip_vview_f *x=&svd->bs,*v=svd->d; diag_sv_f(&svd->B,x,0); vcopy_f(x,v); diag_sv_f(&svd->B,x,1); v=svd->f; vcopy_f(x,v); phaseCheck0_f(svd); } #define opu_f(A,x,y) {\ vsip_length m = (A)->col_length,n = (A)->row_length;vsip_index i,ii,j,jj;\ vsip_scalar_f *ap=(A)->block->array + (A)->offset * (A)->block->rstride, \ *xp=x->block->array + x->offset * x->block->rstride,*yp=y->block->array + y->offset * y->block->rstride;\ vsip_stride xstd = x->block->rstride * x->stride,ystd = y->block->rstride * y->stride,\ r_std = (A)->block->rstride * (A)->row_stride,c_std = (A)->block->rstride * (A)->col_stride;\ m *= c_std; n *= r_std;\ for(i=0, ii=0; i<m; i+=c_std, ii+=xstd){vsip_scalar_f c = xp[ii], *app=ap+i;\ for(j=0, jj=0; j<n; j+=r_std, jj+=ystd){ app[j] = app[j] + c * yp[jj];}}} static void houseProd_f(vsip_vview_f *v, vsip_mview_f *A,vsip_vview_f *w) { vsip_scalar_f *vptr = v->block->array + v->offset*v->block->rstride; vsip_stride vstd = v->stride*v->block->rstride; vsip_scalar_f beta = 0.0; vsip_length n=v->length; while(n-- > 0){ beta += *vptr * *vptr;vptr+=vstd;} beta=2.0/beta; w->length = A->row_length; vmprod_f(v,A,w) svmul_f(-beta,w,w) opu_f(A,v,w) } static void prodHouse_f(vsip_mview_f *A, vsip_vview_f *v, vsip_vview_f *w) { vsip_scalar_f *vptr = v->block->array + v->offset*v->block->rstride; vsip_stride vstd = v->stride*v->block->rstride; vsip_scalar_f beta = 0.0; vsip_length n=v->length; while(n-- > 0){ beta += *vptr * *vptr;vptr+=vstd;} beta=2.0/beta; w->length = A->col_length; mvprod_f(A,v,w) svmul_f(-beta,w,w) opu_f(A,w,v) } static vsip_vview_f *houseVector_f(vsip_vview_f* x) { vsip_scalar_f *x0=x->block->array + x->offset * x->block->rstride; vsip_scalar_f nrm=vnorm2_f(x); vsip_scalar_f t = *x0; vsip_scalar_f s = t + sign_f(t) * nrm; *x0=s; nrm = vnorm2_f(x); if (nrm == 0.0) *x0=1.0; else { vsip_stride std = x->stride * x->block->rstride; vsip_length n = x->length * std; vsip_index k; for(k=0; k<n; k+=std) x0[k] /= nrm; } return x; } static void VHmatExtract_f(svdObj_f *svd) { vsip_mview_f* B = &svd->B; vsip_index i,j; vsip_length n = B->row_length; vsip_mview_f *Bs=&svd->Bs; vsip_mview_f *V=svd->R; vsip_mview_f *Vs=&svd->Rs; vsip_vview_f *v=&svd->bs; vsip_scalar_f t; vsip_scalar_f *vptr; if(n < 3) return; for(i=n-3; i>0; i--){ j=i+1; row_sv_f(msv_f(B,Bs,i,j),v,0); vptr=v->block->array+v->offset*v->block->rstride; t=*vptr; *vptr = 1.0; prodHouse_f(msv_f(V,Vs,j,j),v,svd->w); *vptr = t; } row_sv_f(msv_f(B,Bs,0,1),v,0); vptr=v->block->array+v->offset*v->block->rstride; t=*vptr; *vptr = 1.0; prodHouse_f(msv_f(V,Vs,1,1),v,svd->w); *vptr = t; } static void UmatExtract_f(svdObj_f *svd) { vsip_mview_f* B=&svd->B; vsip_mview_f *U=svd->L; vsip_index i; vsip_length m = B->col_length; vsip_length n = B->row_length; vsip_mview_f *Bs=&svd->Bs; vsip_mview_f *Us=&svd->Ls; vsip_vview_f *v=&svd->bs; vsip_scalar_f t; vsip_scalar_f *vptr; if (m > n){ i=n-1; col_sv_f(msv_f(B,Bs,i,i),v,0); vptr=v->block->array+v->offset*v->block->rstride; t=*vptr; *vptr = 1.0; houseProd_f(v,msv_f(U,Us,i,i),svd->w); *vptr = t; } for(i=n-2; i>0; i--){ col_sv_f(msv_f(B,Bs,i,i),v,0); vptr=v->block->array+v->offset*v->block->rstride; t=*vptr; *vptr = 1.0; houseProd_f(v,msv_f(U,Us,i,i),svd->w); *vptr = t; } col_sv_f(msv_f(B,Bs,0,0),v,0); vptr=v->block->array+v->offset*v->block->rstride; t=*vptr; *vptr = 1.0; houseProd_f(v,msv_f(U,Us,0,0),svd->w); *vptr= t; } static void bidiag_f(svdObj_f *svd) { vsip_mview_f *B = &svd->B; vsip_mview_f *Bs = &svd->Bs; vsip_length m = B->col_length; vsip_length n = B->row_length; vsip_vview_f *x=col_sv_f(B,&svd->bs,0); vsip_vview_f *v=svd->t; vsip_vview_f *vs = &svd->ts; vsip_index i,j; for(i=0; i<n-1; i++){ v->length=m-i; col_sv_f(msv_f(B,Bs,i,i),x,0); vcopy_f(x,v);/*0*/ houseVector_f(v); scaleV(v) houseProd_f(v,Bs,svd->w); vsv_f(v,vs,1);vsv_f(x,x,1); vcopy_f(vs,x);/*1*/ if(i < n-2){ j = i+1; v->length = n-j; row_sv_f(msv_f(B,Bs,i,j),x,0); vcopy_f(x,v);/*2*/ houseVector_f(v); scaleV(v) prodHouse_f(Bs,v,svd->w); vsv_f(v,vs,1);vsv_f(x,x,1); vcopy_f(vs,x);/*3*/ } } if(m > n){ i=n-1; v->length=m-i; col_sv_f(msv_f(B,Bs,i,i),x,0); vcopy_f(x,v); /*4*/ houseVector_f(v); scaleV(v) houseProd_f(v,Bs,svd->w); vsv_f(v,vs,1);vsv_f(x,x,1); vcopy_f(vs,x);/*5*/ } } static void gtProd_f(vsip_index i, vsip_index j, vsip_scalar_f c,vsip_scalar_f s, svdObj_f* svd) { vsip_mview_f* R = &svd->Rs; vsip_vview_f *a1= row_sv_f(R,&svd->rs_one, i); vsip_vview_f *a2= row_sv_f(R,&svd->rs_two, j); vsip_index k; vsip_scalar_f *t1 = a1->block->array + (a1->offset) * a1->block->rstride; vsip_scalar_f *t2 = a2->block->array + (a2->offset) * a2->block->rstride; vsip_stride std = a1->stride * a1->block->rstride; vsip_length n = a1->length * std; for(k=0; k<n; k+=std){ register vsip_scalar_f b1 = t1[k]; register vsip_scalar_f b2 = t2[k]; t1[k] = c * b1 + s * b2; t2[k] = c * b2 - s * b1; } } static void prodG_f(svdObj_f* svd,vsip_index i, vsip_index j,vsip_scalar_f c, vsip_scalar_f s) { vsip_mview_f* L = &svd->Ls; vsip_vview_f *a1= col_sv_f(L,&svd->ls_one,i); vsip_vview_f *a2= col_sv_f(L,&svd->ls_two,j); vsip_index k; vsip_scalar_f *t1 = a1->block->array + (a1->offset) * a1->block->rstride; vsip_scalar_f *t2 = a2->block->array + (a2->offset) * a2->block->rstride; vsip_stride std = a1->stride * a1->block->rstride; vsip_length n = a1->length * std; for(k=0; k<n; k+=std){ register vsip_scalar_f b1 = t1[k]; register vsip_scalar_f b2 = t2[k]; t1[k] = c * b1 + s * b2; t2[k] = c * b2 - s * b1; } } static givensObj_f givensCoef_f(vsip_scalar_f x1, vsip_scalar_f x2) { givensObj_f retval; vsip_scalar_f t = hypot_f(x1,x2); if (x2 == 0.0 ){ retval.c=1.0;retval.s=0.0;retval.r=x1; } else if (x1 == 0.0 || t == 0.0) { retval.c=0.0;retval.s=sign_f(x2);retval.r=t; }else{ vsip_scalar_f sn = sign_f(x1); retval.c=((x1 < 0.0) ? -x1:x1)/t;retval.s=sn*x2/t; retval.r=sn*t; } return retval; } static void zeroCol_f(svdObj_f *svd) { vsip_vview_f *d=&svd->ds; vsip_vview_f *f=&svd->fs; vsip_length n = f->length; givensObj_f g; vsip_scalar_f xd,xf,t; vsip_index i,j,k; if (n == 1){ xd=*(d->block->array + d->offset * d->block->rstride); xf=*(f->block->array + f->offset * f->block->rstride); g=givensCoef_f(xd,xf); *(d->block->array + d->offset * d->block->rstride)=g.r; *(f->block->array + f->offset * f->block->rstride)=0.0; gtProd_f(0,1,g.c,g.s,svd); }else if (n == 2){ xd=VI_VGET_F(d,1); xf=VI_VGET_F(f,1); g=givensCoef_f(xd,xf); *(d->block->array + (d->offset+1) * d->block->rstride)=g.r; *(f->block->array + (f->offset+1) * f->block->rstride)=0.0; xf=VI_VGET_F(f,0); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset) * f->block->rstride)=xf; gtProd_f(1,2,g.c,g.s,svd); xd=VI_VGET_F(d,0); g=givensCoef_f(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; gtProd_f(0,2,g.c,g.s,svd); }else{ i=n-1; j=i-1; k=i; xd=*(d->block->array + (d->offset+i) * d->block->rstride); xf=*(f->block->array + (f->offset+i) * f->block->rstride); g=givensCoef_f(xd,xf); xf=*(f->block->array + (f->offset+j) * f->block->rstride); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; *(f->block->array + (f->offset+i) * f->block->rstride)=0.0; t=-xf*g.s; xf*=g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; gtProd_f(i,k+1,g.c,g.s,svd); while (i > 1){ i = j; j = i-1; xd=*(d->block->array + (d->offset+i) * d->block->rstride); g=givensCoef_f(xd,t); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; xf=*(f->block->array + (f->offset+j) * f->block->rstride); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; gtProd_f(i,k+1,g.c,g.s,svd); } xd=*(d->block->array + d->offset * d->block->rstride); g=givensCoef_f(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; gtProd_f(0,k+1,g.c,g.s,svd); } } static void zeroRow_f(svdObj_f *svd) { vsip_vview_f *d = &svd->ds; vsip_vview_f *f = &svd->fs; vsip_scalar_f *dptr=d->block->array+d->offset*d->block->rstride; vsip_scalar_f *fptr=f->block->array + f->offset*d->block->rstride; vsip_stride dstd=d->stride*d->block->rstride; vsip_stride fstd=f->stride*f->block->rstride; vsip_length n = d->length; givensObj_f g; vsip_scalar_f xd,xf,t; vsip_index i; xd=*dptr; xf=*fptr; g=givensCoef_f(xd,xf); if (n == 1){ *dptr=g.r; *fptr=0.0; prodG_f(svd,n,0,g.c,g.s); }else{ *dptr=g.r; *fptr=0.0; xf=*(fptr+fstd); t= -xf * g.s; xf *= g.c; *(fptr+fstd)=xf; prodG_f(svd,1,0,g.c,g.s); for(i=1; i<n-1; i++){ xd=*(dptr+dstd*i); g=givensCoef_f(xd,t); prodG_f(svd,i+1,0,g.c,g.s); *(dptr+dstd*i)=g.r; xf=*(fptr+fstd*(i+1)); t=-xf * g.s; xf *= g.c; *(fptr+fstd*(i+1))=xf; } xd=*(dptr+dstd*(n-1)); g=givensCoef_f(xd,t); *(dptr+dstd*(n-1))=g.r; prodG_f(svd,n,0,g.c,g.s); } } static void zeroCol2_f(svdObj_f *svd) /* save U */ { vsip_vview_f *d=&svd->ds; vsip_vview_f *f=&svd->fs; vsip_length n = f->length; givensObj_f g; vsip_scalar_f xd,xf,t; vsip_index i,j,k; if (n == 1){ xd=*(d->block->array + d->offset * d->block->rstride); xf=*(f->block->array + f->offset * f->block->rstride); g=givensCoef_f(xd,xf); *(d->block->array + d->offset * d->block->rstride)=g.r; *(f->block->array + f->offset * f->block->rstride)=0.0; }else if (n == 2){ xd=VI_VGET_F(d,1); xf=VI_VGET_F(f,1); g=givensCoef_f(xd,xf); *(d->block->array + (d->offset+1) * d->block->rstride)=g.r; *(f->block->array + (f->offset+1) * f->block->rstride)=0.0; xf=VI_VGET_F(f,0); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset) * f->block->rstride)=xf; xd=VI_VGET_F(d,0); g=givensCoef_f(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; }else{ i=n-1; j=i-1; k=i; xd=*(d->block->array + (d->offset+i) * d->block->rstride); xf=*(f->block->array + (f->offset+i) * f->block->rstride); g=givensCoef_f(xd,xf); xf=*(f->block->array + (f->offset+j) * f->block->rstride); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; *(f->block->array + (f->offset+i) * f->block->rstride)=0.0; t=-xf*g.s; xf*=g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; while (i > 1){ i = j; j = i-1; xd=*(d->block->array + (d->offset+i) * d->block->rstride); g=givensCoef_f(xd,t); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; xf=*(f->block->array + (f->offset+j) * f->block->rstride); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; gtProd_f(i,k+1,g.c,g.s,svd); } xd=*(d->block->array + d->offset * d->block->rstride); g=givensCoef_f(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; } } static void zeroRow2_f(svdObj_f *svd) /* save U */ { vsip_vview_f *d = &svd->ds; vsip_vview_f *f = &svd->fs; vsip_scalar_f *dptr=d->block->array+d->offset*d->block->rstride; vsip_scalar_f *fptr=f->block->array + f->offset*d->block->rstride; vsip_stride dstd=d->stride*d->block->rstride; vsip_stride fstd=f->stride*f->block->rstride; vsip_length n = d->length; givensObj_f g; vsip_scalar_f xd,xf,t; vsip_index i; xd=*dptr; xf=*fptr; g=givensCoef_f(xd,xf); if (n == 1){ *dptr=g.r; *fptr=0.0; prodG_f(svd,n,0,g.c,g.s); }else{ *dptr=g.r; *fptr=0.0; xf=*(fptr+fstd); t= -xf * g.s; xf *= g.c; *(fptr+fstd)=xf; prodG_f(svd,1,0,g.c,g.s); for(i=1; i<n-1; i++){ xd=*(dptr+dstd*i); g=givensCoef_f(xd,t); prodG_f(svd,i+1,0,g.c,g.s); *(dptr+dstd*i)=g.r; xf=*(fptr+fstd*(i+1)); t=-xf * g.s; xf *= g.c; *(fptr+fstd*(i+1))=xf; } xd=*(dptr+dstd*(n-1)); g=givensCoef_f(xd,t); *(dptr+dstd*(n-1))=g.r; prodG_f(svd,n,0,g.c,g.s); } } static void zeroCol1_f(svdObj_f *svd) /* save V */ { vsip_vview_f *d=&svd->ds; vsip_vview_f *f=&svd->fs; vsip_length n = f->length; givensObj_f g; vsip_scalar_f xd,xf,t; vsip_index i,j,k; if (n == 1){ xd=*(d->block->array + d->offset * d->block->rstride); xf=*(f->block->array + f->offset * f->block->rstride); g=givensCoef_f(xd,xf); *(d->block->array + d->offset * d->block->rstride)=g.r; *(f->block->array + f->offset * f->block->rstride)=0.0; gtProd_f(0,1,g.c,g.s,svd); }else if (n == 2){ xd=VI_VGET_F(d,1); xf=VI_VGET_F(f,1); g=givensCoef_f(xd,xf); *(d->block->array + (d->offset+1) * d->block->rstride)=g.r; *(f->block->array + (f->offset+1) * f->block->rstride)=0.0; xf=VI_VGET_F(f,0); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset) * f->block->rstride)=xf; gtProd_f(1,2,g.c,g.s,svd); xd=VI_VGET_F(d,0); g=givensCoef_f(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; gtProd_f(0,2,g.c,g.s,svd); }else{ i=n-1; j=i-1; k=i; xd=*(d->block->array + (d->offset+i) * d->block->rstride); xf=*(f->block->array + (f->offset+i) * f->block->rstride); g=givensCoef_f(xd,xf); xf=*(f->block->array + (f->offset+j) * f->block->rstride); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; *(f->block->array + (f->offset+i) * f->block->rstride)=0.0; t=-xf*g.s; xf*=g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; gtProd_f(i,k+1,g.c,g.s,svd); while (i > 1){ i = j; j = i-1; xd=*(d->block->array + (d->offset+i) * d->block->rstride); g=givensCoef_f(xd,t); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; xf=*(f->block->array + (f->offset+j) * f->block->rstride); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; gtProd_f(i,k+1,g.c,g.s,svd); } xd=*(d->block->array + d->offset * d->block->rstride); g=givensCoef_f(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; gtProd_f(0,k+1,g.c,g.s,svd); } } static void zeroRow1_f(svdObj_f *svd) /* save V */ { vsip_vview_f *d = &svd->ds; vsip_vview_f *f = &svd->fs; vsip_scalar_f *dptr=d->block->array+d->offset*d->block->rstride; vsip_scalar_f *fptr=f->block->array + f->offset*d->block->rstride; vsip_stride dstd=d->stride*d->block->rstride; vsip_stride fstd=f->stride*f->block->rstride; vsip_length n = d->length; givensObj_f g; vsip_scalar_f xd,xf,t; vsip_index i; xd=*dptr; xf=*fptr; g=givensCoef_f(xd,xf); if (n == 1){ *dptr=g.r; *fptr=0.0; }else{ *dptr=g.r; *fptr=0.0; xf=*(fptr+fstd); t= -xf * g.s; xf *= g.c; *(fptr+fstd)=xf; for(i=1; i<n-1; i++){ xd=*(dptr+dstd*i); g=givensCoef_f(xd,t); *(dptr+dstd*i)=g.r; xf=*(fptr+fstd*(i+1)); t=-xf * g.s; xf *= g.c; *(fptr+fstd*(i+1))=xf; } xd=*(dptr+dstd*(n-1)); g=givensCoef_f(xd,t); *(dptr+dstd*(n-1))=g.r; } } static void zeroCol0_f(svdObj_f *svd) { vsip_vview_f *d=&svd->ds; vsip_vview_f *f=&svd->fs; vsip_length n = f->length; givensObj_f g; vsip_scalar_f xd,xf,t; vsip_index i,j; if (n == 1){ xd=*(d->block->array + d->offset * d->block->rstride); xf=*(f->block->array + f->offset * f->block->rstride); g=givensCoef_f(xd,xf); *(d->block->array + d->offset * d->block->rstride)=g.r; *(f->block->array + f->offset * f->block->rstride)=0.0; }else if (n == 2){ xd=VI_VGET_F(d,1); xf=VI_VGET_F(f,1); g=givensCoef_f(xd,xf); *(d->block->array + (d->offset+1) * d->block->rstride)=g.r; *(f->block->array + (f->offset+1) * f->block->rstride)=0.0; xf=VI_VGET_F(f,0); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset) * f->block->rstride)=xf; xd=VI_VGET_F(d,0); g=givensCoef_f(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; }else{ i=n-1; j=i-1; xd=*(d->block->array + (d->offset+i) * d->block->rstride); xf=*(f->block->array + (f->offset+i) * f->block->rstride); g=givensCoef_f(xd,xf); xf=*(f->block->array + (f->offset+j) * f->block->rstride); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; *(f->block->array + (f->offset+i) * f->block->rstride)=0.0; t=-xf*g.s; xf*=g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; while (i > 1){ i = j; j = i-1; xd=*(d->block->array + (d->offset+i) * d->block->rstride); g=givensCoef_f(xd,t); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; xf=*(f->block->array + (f->offset+j) * f->block->rstride); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; } xd=*(d->block->array + d->offset * d->block->rstride); g=givensCoef_f(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; } } static void zeroRow0_f(svdObj_f *svd) { vsip_vview_f *d = &svd->ds; vsip_vview_f *f = &svd->fs; vsip_scalar_f *dptr=d->block->array+d->offset*d->block->rstride; vsip_scalar_f *fptr=f->block->array + f->offset*d->block->rstride; vsip_stride dstd=d->stride*d->block->rstride; vsip_stride fstd=f->stride*f->block->rstride; vsip_length n = d->length; givensObj_f g; vsip_scalar_f xd,xf,t; vsip_index i; xd=*dptr; xf=*fptr; g=givensCoef_f(xd,xf); if (n == 1){ *dptr=g.r; *fptr=0.0; }else{ *dptr=g.r; *fptr=0.0; xf=*(fptr+fstd); t= -xf * g.s; xf *= g.c; *(fptr+fstd)=xf; for(i=1; i<n-1; i++){ xd=*(dptr+dstd*i); g=givensCoef_f(xd,t); *(dptr+dstd*i)=g.r; xf=*(fptr+fstd*(i+1)); t=-xf * g.s; xf *= g.c; *(fptr+fstd*(i+1))=xf; } xd=*(dptr+dstd*(n-1)); g=givensCoef_f(xd,t); *(dptr+dstd*(n-1))=g.r; } } static vsip_scalar_f svdMu_f(vsip_scalar_f d2,vsip_scalar_f f1,vsip_scalar_f d3,vsip_scalar_f* f2, vsip_scalar_f eps0) { vsip_scalar_f mu; vsip_scalar_f cu=d2 * d2 + f1 * f1; vsip_scalar_f cl=d3 * d3 + *f2 * *f2; vsip_scalar_f cd = d2 * *f2; vsip_scalar_f T = (cu + cl); vsip_scalar_f D = (cu * cl - cd * cd)/(T*T); vsip_scalar_f root = T * (vsip_scalar_f) sqrt(1.0 - ((4 * D)>1.0 ? 1.0:4*D)); vsip_scalar_f lambda1 = (T + root)/(2.); vsip_scalar_f lambda2 = (T - root)/(2.); vsip_scalar_f c1=lambda1-cl,c2=lambda2-cl; c1=(c1<0) ? -c1:c1; c2=(c2<0) ? -c2:c2; if(root == 0.0) if(fabs(*f2) < (d2 + d3) * eps0) *f2=0.0; if(c1 < c2) mu = lambda1; else mu = lambda2; return mu; } static vsip_index zeroFind_f(vsip_vview_f* d, vsip_scalar_f eps0) { vsip_scalar_f *dptr=d->block->array + d->offset*d->block->rstride; vsip_stride dstrd=d->stride*d->block->rstride; vsip_index j = d->length; vsip_scalar_f xd=*(dptr+(j-1)*dstrd); while(xd > eps0){ if (j > 1){ j -= 1; xd=*(dptr+(j-1)*dstrd); }else if(j==1) return 0; } *(dptr+(j-1)*dstrd)=0.0; return j; } static svdCorner svdCorners_f(vsip_vview_f* f) { svdCorner crnr; vsip_scalar_f *fptr=f->block->array + f->offset*f->block->rstride; vsip_stride fstrd=f->stride*f->block->rstride; vsip_index j=f->length-1; vsip_index i; while((j > 0) && *(fptr+j*fstrd) == 0.0) j-=1; if(j == 0 && *fptr == 0.0){ crnr.i=0; crnr.j=0; } else { i = j; while((i > 0) && *(fptr+i*fstrd) != 0.0) i -= 1; if(i==0 && *fptr == 0.0){ crnr.i = 1; crnr.j = j+2; } else if(i == 0 && *fptr != 0.0){ crnr.i = 0; crnr.j= j+2; }else{ crnr.i = i+1; crnr.j = j+2; } } /* index and length of f != 0 */ return crnr; } static void svdStep_f(svdObj_f *svd) { vsip_vview_f *d = &svd->ds; vsip_vview_f *f = &svd->fs; givensObj_f g; vsip_length n = d->length; vsip_scalar_f mu=0.0, x1=0.0, x2=0.0; vsip_scalar_f t=0.0; vsip_index i,j,k; vsip_scalar_f d2=0.0,f1=0.0,d3=0.0,f2=0.0; vsip_scalar_f *fptr,*dptr; vsip_stride fstd=f->stride*f->block->rstride, dstd=d->stride*d->block->rstride; dptr=d->block->array+d->offset*d->block->rstride; fptr=f->block->array+f->offset*f->block->rstride; if(n >= 3){ d2=*(dptr+dstd*(n-2));f1= *(fptr+fstd*(n-3));d3 = *(dptr+dstd*(n-1));f2= *(fptr+fstd*(n-2)); } else if(n == 2){ d2=*dptr; d3=*(dptr+dstd); f1=0; f2=*fptr; } else { printf("should not be here (see svdStep_f)\n"); exit(-1); } mu = svdMu_f(d2,f1,d3,&f2,svd->eps0); if(f2 == 0.0) *(fptr+fstd*(n-2)) = 0.0; x1=*dptr; x2 = x1 * *fptr; x1 *= x1; x1 -= mu; g=givensCoef_f(x1,x2); x1=*dptr;x2=*fptr; *fptr=g.c*x2-g.s*x1; *dptr=g.c*x1+g.s*x2; t=*(dptr+dstd); *(dptr+dstd) *= g.c; t*=g.s; gtProd_f(0,1,g.c,g.s,svd); for(i=0; i<n-2; i++){ j=i+1; k=i+2; g = givensCoef_f(*(dptr+i*dstd),t); *(dptr+i*dstd)=g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t= x1 - x2; x1=*(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s ; *(f->block->array+(i*f->stride+f->offset)*f->block->rstride) = x1+x2; *(d->block->array+(j*d->stride+d->offset)*d->block->rstride) = t; x1=*(fptr+j*fstd); t=g.s * x1; *(fptr+j*fstd)=x1*g.c; prodG_f(svd,i, j, g.c, g.s); g=givensCoef_f(*(fptr+i*fstd),t); *(fptr+i*fstd)=g.r; x1=*(dptr+j*dstd); x2=*(fptr+j*fstd); *(dptr+j*dstd)=g.c * x1 + g.s * x2; *(fptr+j*fstd)=g.c * x2 - g.s * x1; x1=*(dptr+k*dstd); t=g.s * x1; *(dptr+k*dstd)=x1*g.c; gtProd_f(j,k, g.c, g.s,svd); } i=n-2; j=n-1; g = givensCoef_f(*(dptr+i*dstd),t); *(d->block->array+(i*d->stride+d->offset)*d->block->rstride) = g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t=x1 - x2; x1 = *(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s; *(f->block->array+(i*f->stride+f->offset)*f->block->rstride) = x1+x2; *(d->block->array+(j*d->stride+d->offset)*d->block->rstride) = t; prodG_f(svd,i, j, g.c, g.s); } static void svdStep2_f(svdObj_f *svd) /* save U */ { vsip_vview_f *d = &svd->ds; vsip_vview_f *f = &svd->fs; givensObj_f g; vsip_length n = d->length; vsip_scalar_f mu=0.0, x1=0.0, x2=0.0; vsip_scalar_f t=0.0; vsip_index i,j,k; vsip_scalar_f d2=0.0,f1=0.0,d3=0.0,f2=0.0; vsip_scalar_f *fptr,*dptr; vsip_stride fstd=f->stride*f->block->rstride, dstd=d->stride*d->block->rstride; dptr=d->block->array+d->offset*d->block->rstride; fptr=f->block->array+f->offset*f->block->rstride; if(n >= 3){ d2=*(dptr+dstd*(n-2));f1= *(fptr+fstd*(n-3));d3 = *(dptr+dstd*(n-1));f2= *(fptr+fstd*(n-2)); } else if(n == 2){ d2=*dptr; d3=*(dptr+dstd); f1=0; f2=*fptr; } else { printf("should not be here (see svdStep_f)\n"); exit(-1); } mu = svdMu_f(d2,f1,d3,&f2,svd->eps0); if(f2 == 0.0) *(fptr+fstd*(n-2)) = 0.0; x1=*dptr; x2 = x1 * *fptr; x1 *= x1; x1 -= mu; g=givensCoef_f(x1,x2); x1=*dptr;x2=*fptr; *fptr=g.c*x2-g.s*x1; *dptr=g.c*x1+g.s*x2; t=*(dptr+dstd); *(dptr+dstd) *= g.c; t*=g.s; for(i=0; i<n-2; i++){ j=i+1; k=i+2; g = givensCoef_f(*(dptr+i*dstd),t); *(dptr+i*dstd)=g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t= x1 - x2; x1=*(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s ; *(f->block->array+(i*f->stride+f->offset)*f->block->rstride) = x1+x2; *(d->block->array+(j*d->stride+d->offset)*d->block->rstride) = t; x1=*(fptr+j*fstd); t=g.s * x1; *(fptr+j*fstd)=x1*g.c; prodG_f(svd,i, j, g.c, g.s); g=givensCoef_f(*(fptr+i*fstd),t); *(fptr+i*fstd)=g.r; x1=*(dptr+j*dstd); x2=*(fptr+j*fstd); *(dptr+j*dstd)=g.c * x1 + g.s * x2; *(fptr+j*fstd)=g.c * x2 - g.s * x1; x1=*(dptr+k*dstd); t=g.s * x1; *(dptr+k*dstd)=x1*g.c; } i=n-2; j=n-1; g = givensCoef_f(*(dptr+i*dstd),t); *(d->block->array+(i*d->stride+d->offset)*d->block->rstride) = g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t=x1 - x2; x1 = *(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s; *(f->block->array+(i*f->stride+f->offset)*f->block->rstride) = x1+x2; *(d->block->array+(j*d->stride+d->offset)*d->block->rstride) = t; prodG_f(svd,i, j, g.c, g.s); } static void svdStep1_f(svdObj_f *svd) /* save V */ { vsip_vview_f *d = &svd->ds; vsip_vview_f *f = &svd->fs; givensObj_f g; vsip_length n = d->length; vsip_scalar_f mu=0.0, x1=0.0, x2=0.0; vsip_scalar_f t=0.0; vsip_index i,j,k; vsip_scalar_f d2=0.0,f1=0.0,d3=0.0,f2=0.0; vsip_scalar_f *fptr,*dptr; vsip_stride fstd=f->stride*f->block->rstride, dstd=d->stride*d->block->rstride; dptr=d->block->array+d->offset*d->block->rstride; fptr=f->block->array+f->offset*f->block->rstride; if(n >= 3){ d2=*(dptr+dstd*(n-2));f1= *(fptr+fstd*(n-3));d3 = *(dptr+dstd*(n-1));f2= *(fptr+fstd*(n-2)); } else if(n == 2){ d2=*dptr; d3=*(dptr+dstd); f1=0; f2=*fptr; } else { printf("should not be here (see svdStep_f)\n"); exit(-1); } mu = svdMu_f(d2,f1,d3,&f2,svd->eps0); if(f2 == 0.0) *(fptr+fstd*(n-2)) = 0.0; x1=*dptr; x2 = x1 * *fptr; x1 *= x1; x1 -= mu; g=givensCoef_f(x1,x2); x1=*dptr;x2=*fptr; *fptr=g.c*x2-g.s*x1; *dptr=g.c*x1+g.s*x2; t=*(dptr+dstd); *(dptr+dstd) *= g.c; t*=g.s; gtProd_f(0,1,g.c,g.s,svd); for(i=0; i<n-2; i++){ j=i+1; k=i+2; g = givensCoef_f(*(dptr+i*dstd),t); *(dptr+i*dstd)=g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t= x1 - x2; x1=*(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s ; *(f->block->array+(i*f->stride+f->offset)*f->block->rstride) = x1+x2; *(d->block->array+(j*d->stride+d->offset)*d->block->rstride) = t; x1=*(fptr+j*fstd); t=g.s * x1; *(fptr+j*fstd)=x1*g.c; g=givensCoef_f(*(fptr+i*fstd),t); *(fptr+i*fstd)=g.r; x1=*(dptr+j*dstd); x2=*(fptr+j*fstd); *(dptr+j*dstd)=g.c * x1 + g.s * x2; *(fptr+j*fstd)=g.c * x2 - g.s * x1; x1=*(dptr+k*dstd); t=g.s * x1; *(dptr+k*dstd)=x1*g.c; gtProd_f(j,k, g.c, g.s,svd); } i=n-2; j=n-1; g = givensCoef_f(*(dptr+i*dstd),t); *(d->block->array+(i*d->stride+d->offset)*d->block->rstride) = g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t=x1 - x2; x1 = *(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s; *(f->block->array+(i*f->stride+f->offset)*f->block->rstride) = x1+x2; *(d->block->array+(j*d->stride+d->offset)*d->block->rstride) = t; } static void svdStep0_f(svdObj_f *svd) { vsip_vview_f *d = &svd->ds; vsip_vview_f *f = &svd->fs; givensObj_f g; vsip_length n = d->length; vsip_scalar_f mu=0.0, x1=0.0, x2=0.0; vsip_scalar_f t=0.0; vsip_index i,j,k; vsip_scalar_f d2=0.0,f1=0.0,d3=0.0,f2=0.0; vsip_scalar_f *fptr,*dptr; vsip_stride fstd=f->stride*f->block->rstride, dstd=d->stride*d->block->rstride; dptr=d->block->array+d->offset*d->block->rstride; fptr=f->block->array+f->offset*f->block->rstride; if(n >= 3){ d2=*(dptr+dstd*(n-2));f1= *(fptr+fstd*(n-3));d3 = *(dptr+dstd*(n-1));f2= *(fptr+fstd*(n-2)); } else if(n == 2){ d2=*dptr; d3=*(dptr+dstd); f1=0; f2=*fptr; } else { printf("should not be here (see svdStep_f)\n"); exit(-1); } mu = svdMu_f(d2,f1,d3,&f2,svd->eps0); if(f2 == 0.0) *(fptr+fstd*(n-2)) = 0.0; x1=*dptr; x2 = x1 * *fptr; x1 *= x1; x1 -= mu; g=givensCoef_f(x1,x2); x1=*dptr;x2=*fptr; *fptr=g.c*x2-g.s*x1; *dptr=g.c*x1+g.s*x2; t=*(dptr+dstd); *(dptr+dstd) *= g.c; t*=g.s; for(i=0; i<n-2; i++){ j=i+1; k=i+2; g = givensCoef_f(*(dptr+i*dstd),t); *(dptr+i*dstd)=g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t= x1 - x2; x1=*(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s ; *(f->block->array+(i*f->stride+f->offset)*f->block->rstride) = x1+x2; *(d->block->array+(j*d->stride+d->offset)*d->block->rstride) = t; x1=*(fptr+j*fstd); t=g.s * x1; *(fptr+j*fstd)=x1*g.c; g=givensCoef_f(*(fptr+i*fstd),t); *(fptr+i*fstd)=g.r; x1=*(dptr+j*dstd); x2=*(fptr+j*fstd); *(dptr+j*dstd)=g.c * x1 + g.s * x2; *(fptr+j*fstd)=g.c * x2 - g.s * x1; x1=*(dptr+k*dstd); t=g.s * x1; *(dptr+k*dstd)=x1*g.c; } i=n-2; j=n-1; g = givensCoef_f(*(dptr+i*dstd),t); *(d->block->array+(i*d->stride+d->offset)*d->block->rstride) = g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t=x1 - x2; x1 = *(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s; *(f->block->array+(i*f->stride+f->offset)*f->block->rstride) = x1+x2; *(d->block->array+(j*d->stride+d->offset)*d->block->rstride) = t; } static vsip_cvview_f *cvsv_f(vsip_cvview_f *v,vsip_cvview_f *vs,vsip_index i) { *vs=*v; vs->offset += i * vs->stride; vs->length -= i; return vs; } static vsip_cmview_f* cmsv_f(vsip_cmview_f *B, vsip_cmview_f *BS, vsip_index i,vsip_index j) { *BS=*B; BS->row_length -= j; BS->col_length -= i; BS->offset += j * BS->row_stride + i * BS->col_stride; return BS; } static vsip_vview_f *vreal_sv_f(vsip_cvview_f *cv,vsip_vview_f*v) { v->block=cv->block->R; v->offset = cv->offset; v->length=cv->length;v->stride= cv->stride; v->markings = VSIP_VALID_STRUCTURE_OBJECT; return v; } static vsip_scalar_f cvnorm2_f(vsip_cvview_f *a) { vsip_length n = a->length; vsip_stride cast = a->block->cstride; vsip_scalar_f *apr = (vsip_scalar_f*) ((a->block->R->array) + cast * a->offset); vsip_scalar_f *api = (vsip_scalar_f*) ((a->block->I->array) + cast * a->offset); vsip_stride ast = (cast * a->stride); vsip_scalar_f t1=0,t2=0; while(n-- > 0){ t1 += *apr * *apr; t2 += *api * *api; apr += ast; api += ast; } return (vsip_scalar_f)sqrt(t1+t2); } static vsip_scalar_f cmnormFro_f(vsip_cmview_f *v) { vsip_length m=v->col_length,n=v->row_length; vsip_index i,j; vsip_stride rstrd=v->row_stride*v->block->R->rstride; vsip_stride cstrd=v->col_stride*v->block->R->rstride; vsip_scalar_f *vre=v->block->R->array+v->offset*v->block->R->rstride; vsip_scalar_f *vim=v->block->I->array+v->offset*v->block->I->rstride; vsip_scalar_f re=0.0; vsip_scalar_f im=0.0; for(i=0; i<m; i++){ vsip_offset o=i*cstrd; vsip_scalar_f *rp=vre+o; vsip_scalar_f *ip=vim+o; for(j=0; j<n; j++){ re += *rp * *rp; im += *ip * *ip; rp += rstrd; ip += rstrd; } } return (vsip_scalar_f)sqrt(re+im); } static void cmeye_f(vsip_cmview_f *v) { vsip_length m=v->col_length,n=v->row_length; vsip_index i,j; vsip_stride rstrd=v->row_stride*v->block->R->rstride; vsip_stride cstrd=v->col_stride*v->block->R->rstride; vsip_scalar_f *vre=v->block->R->array+v->offset*v->block->R->rstride; vsip_scalar_f *vim=v->block->I->array+v->offset*v->block->I->rstride; for(i=0; i<m; i++){ vsip_offset o=i*cstrd; vsip_scalar_f *rp=vre+o; vsip_scalar_f *ip=vim+o; for(j=0; j<n; j++){ *rp = (i==j) ? 1.0:0.0; *ip = 0.0; rp += rstrd; ip += rstrd; } } } static void cbiDiagPhaseToZero_f( csvdObj_f *svd) { vsip_cmview_f *L = svd->L; vsip_cvview_f *d = cdiag_sv_f(&svd->B,&svd->bs,0); vsip_cvview_f *f = cdiag_sv_f(&svd->B,&svd->bfs,1); vsip_cmview_f *R = svd->R; vsip_scalar_f eps0 = svd->eps0; vsip_length nd=d->length; vsip_length nf=f->length; vsip_index i,j; vsip_cscalar_f ps; vsip_scalar_f m; vsip_cvview_f *l = &svd->ls_one; vsip_cvview_f *r = &svd->rs_one; vsip_scalar_f *dptr_r=d->block->R->array+d->block->R->rstride*d->offset; vsip_scalar_f *dptr_i=d->block->I->array+d->block->R->rstride*d->offset; vsip_scalar_f *fptr_r=f->block->R->array+f->block->R->rstride*f->offset; vsip_scalar_f *fptr_i=f->block->I->array+f->block->R->rstride*f->offset; vsip_stride dstrd=d->stride*d->block->R->rstride; vsip_stride fstrd=f->stride*f->block->R->rstride; vsip_scalar_f re,im; for(i=0; i<nd; i++){ ps.r=*(dptr_r+i*dstrd); ps.i=*(dptr_i+i*dstrd); if(ps.i == 0.0){ m = ps.r; if (m < 0.0) ps.r=-1.0; else ps.r=1.0; m = (m<0) ? -m:m; } else { re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } if(m > eps0){ ccol_sv_f(L,l,i);csvmul_f(ps,l); *(d->block->R->array+(d->offset+i*d->stride)*d->block->cstride)=m; *(d->block->I->array+(d->offset+i*d->stride)*d->block->cstride)=0.0; if (i < nf){ vsip_scalar_f *fr=fptr_r+i*fstrd; vsip_scalar_f *fi=fptr_i+i*fstrd; re=*fr; im=*fi; *fr=re*ps.r+im*ps.i; *fi=-ps.i*re+ps.r*im; } }else{ *(dptr_r+i*dstrd)=0.0; *(dptr_i+i*dstrd)=0.0; } } for (i=0; i<nf-1; i++){ j=i+1; ps.r=*(fptr_r+i*fstrd); ps.i=*(fptr_i+i*fstrd); if (ps.i == 0.0){ m = ps.r; if (m < 0.0) ps.r =-1.0; else ps.r = 1.0; m = (m < 0.0) ? -m:m; }else{ re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } ccol_sv_f(L, l, j); ps.i=-ps.i;csvmul_f(ps,l);ps.i=-ps.i; crow_sv_f(R,r,j); csvmul_f(ps,r); *(fptr_r+i*fstrd)=m; *(fptr_i+i*fstrd)=0.0; re=*(fptr_r+ j * fstrd); im=*(fptr_i+ j * fstrd); *(fptr_r+ j * fstrd)=re*ps.r-im*ps.i; *(fptr_i+ j * fstrd)=re*ps.i+im*ps.r; } j=nf; i=j-1; ps.r=*(fptr_r+i*fstrd); ps.i=*(fptr_i+i*fstrd); if (ps.i == 0.0){ m = ps.r; if(m < 0.0) ps.r =-1.0; else ps.r = 1.0; m = (m<0) ? -m:m; }else{ re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } *(fptr_r+i*fstrd)=m; *(fptr_i+i*fstrd)=0.0; ccol_sv_f(L, l, j); ps.i=-ps.i;csvmul_f(ps,l);ps.i=-ps.i; crow_sv_f(R,r,j); csvmul_f(ps,r); } static void cbiDiagPhaseToZero2_f( csvdObj_f *svd) /* save U only */ { vsip_cmview_f *L = svd->L; vsip_cvview_f *d = cdiag_sv_f(&svd->B,&svd->bs,0); vsip_cvview_f *f = cdiag_sv_f(&svd->B,&svd->bfs,1); vsip_scalar_f eps0 = svd->eps0; vsip_length nd=d->length; vsip_length nf=f->length; vsip_index i,j; vsip_cscalar_f ps; vsip_scalar_f m; vsip_cvview_f *l = &svd->ls_one; vsip_scalar_f *dptr_r=d->block->R->array+d->block->R->rstride*d->offset; vsip_scalar_f *dptr_i=d->block->I->array+d->block->R->rstride*d->offset; vsip_scalar_f *fptr_r=f->block->R->array+f->block->R->rstride*f->offset; vsip_scalar_f *fptr_i=f->block->I->array+f->block->R->rstride*f->offset; vsip_stride dstrd=d->stride*d->block->R->rstride; vsip_stride fstrd=f->stride*f->block->R->rstride; vsip_scalar_f re,im; for(i=0; i<nd; i++){ ps.r=*(dptr_r+i*dstrd); ps.i=*(dptr_i+i*dstrd); if(ps.i == 0.0){ m = ps.r; if (m < 0.0) ps.r=-1.0; else ps.r=1.0; m = (m<0) ? -m:m; } else { re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } if(m > eps0){ ccol_sv_f(L,l,i);csvmul_f(ps,l); *(d->block->R->array+(d->offset+i*d->stride)*d->block->cstride)=m; *(d->block->I->array+(d->offset+i*d->stride)*d->block->cstride)=0.0; if (i < nf){ vsip_scalar_f *fr=fptr_r+i*fstrd; vsip_scalar_f *fi=fptr_i+i*fstrd; re=*fr; im=*fi; *fr=re*ps.r+im*ps.i; *fi=-ps.i*re+ps.r*im; } }else{ *(dptr_r+i*dstrd)=0.0; *(dptr_i+i*dstrd)=0.0; } } for (i=0; i<nf-1; i++){ j=i+1; ps.r=*(fptr_r+i*fstrd); ps.i=*(fptr_i+i*fstrd); if (ps.i == 0.0){ m = ps.r; if (m < 0.0) ps.r =-1.0; else ps.r = 1.0; m = (m < 0.0) ? -m:m; }else{ re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } ccol_sv_f(L, l, j); ps.i=-ps.i;csvmul_f(ps,l);ps.i=-ps.i; *(fptr_r+i*fstrd)=m; *(fptr_i+i*fstrd)=0.0; re=*(fptr_r+ j * fstrd); im=*(fptr_i+ j * fstrd); *(fptr_r+ j * fstrd)=re*ps.r-im*ps.i; *(fptr_i+ j * fstrd)=re*ps.i+im*ps.r; } j=nf; i=j-1; ps.r=*(fptr_r+i*fstrd); ps.i=*(fptr_i+i*fstrd); if (ps.i == 0.0){ m = ps.r; if(m < 0.0) ps.r =-1.0; else ps.r = 1.0; m = (m<0) ? -m:m; }else{ re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } *(fptr_r+i*fstrd)=m; *(fptr_i+i*fstrd)=0.0; ccol_sv_f(L, l, j); ps.i=-ps.i;csvmul_f(ps,l);ps.i=-ps.i; } static void cbiDiagPhaseToZero1_f( csvdObj_f *svd) /* save V only */ { vsip_cvview_f *d = cdiag_sv_f(&svd->B,&svd->bs,0); vsip_cvview_f *f = cdiag_sv_f(&svd->B,&svd->bfs,1); vsip_cmview_f *R = svd->R; vsip_scalar_f eps0 = svd->eps0; vsip_length nd=d->length; vsip_length nf=f->length; vsip_index i,j; vsip_cscalar_f ps; vsip_scalar_f m; vsip_cvview_f *r = &svd->rs_one; vsip_scalar_f *dptr_r=d->block->R->array+d->block->R->rstride*d->offset; vsip_scalar_f *dptr_i=d->block->I->array+d->block->R->rstride*d->offset; vsip_scalar_f *fptr_r=f->block->R->array+f->block->R->rstride*f->offset; vsip_scalar_f *fptr_i=f->block->I->array+f->block->R->rstride*f->offset; vsip_stride dstrd=d->stride*d->block->R->rstride; vsip_stride fstrd=f->stride*f->block->R->rstride; vsip_scalar_f re,im; for(i=0; i<nd; i++){ ps.r=*(dptr_r+i*dstrd); ps.i=*(dptr_i+i*dstrd); if(ps.i == 0.0){ m = ps.r; if (m < 0.0) ps.r=-1.0; else ps.r=1.0; m = (m<0) ? -m:m; } else { re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } if(m > eps0){ *(d->block->R->array+(d->offset+i*d->stride)*d->block->cstride)=m; *(d->block->I->array+(d->offset+i*d->stride)*d->block->cstride)=0.0; if (i < nf){ vsip_scalar_f *fr=fptr_r+i*fstrd; vsip_scalar_f *fi=fptr_i+i*fstrd; re=*fr; im=*fi; *fr=re*ps.r+im*ps.i; *fi=-ps.i*re+ps.r*im; } }else{ *(dptr_r+i*dstrd)=0.0; *(dptr_i+i*dstrd)=0.0; } } for (i=0; i<nf-1; i++){ j=i+1; ps.r=*(fptr_r+i*fstrd); ps.i=*(fptr_i+i*fstrd); if (ps.i == 0.0){ m = ps.r; if (m < 0.0) ps.r =-1.0; else ps.r = 1.0; m = (m < 0.0) ? -m:m; }else{ re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } crow_sv_f(R,r,j); csvmul_f(ps,r); *(fptr_r+i*fstrd)=m; *(fptr_i+i*fstrd)=0.0; re=*(fptr_r+ j * fstrd); im=*(fptr_i+ j * fstrd); *(fptr_r+ j * fstrd)=re*ps.r-im*ps.i; *(fptr_i+ j * fstrd)=re*ps.i+im*ps.r; } j=nf; i=j-1; ps.r=*(fptr_r+i*fstrd); ps.i=*(fptr_i+i*fstrd); if (ps.i == 0.0){ m = ps.r; if(m < 0.0) ps.r =-1.0; else ps.r = 1.0; m = (m<0) ? -m:m; }else{ re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } *(fptr_r+i*fstrd)=m; *(fptr_i+i*fstrd)=0.0; crow_sv_f(R,r,j); csvmul_f(ps,r); } static void cbiDiagPhaseToZero0_f( csvdObj_f *svd) { vsip_cvview_f *d = cdiag_sv_f(&svd->B,&svd->bs,0); vsip_cvview_f *f = cdiag_sv_f(&svd->B,&svd->bfs,1); vsip_scalar_f eps0 = svd->eps0; vsip_length nd=d->length; vsip_length nf=f->length; vsip_index i,j; vsip_cscalar_f ps; vsip_scalar_f m; vsip_scalar_f *dptr_r=d->block->R->array+d->block->R->rstride*d->offset; vsip_scalar_f *dptr_i=d->block->I->array+d->block->R->rstride*d->offset; vsip_scalar_f *fptr_r=f->block->R->array+f->block->R->rstride*f->offset; vsip_scalar_f *fptr_i=f->block->I->array+f->block->R->rstride*f->offset; vsip_stride dstrd=d->stride*d->block->R->rstride; vsip_stride fstrd=f->stride*f->block->R->rstride; vsip_scalar_f re,im; for(i=0; i<nd; i++){ ps.r=*(dptr_r+i*dstrd); ps.i=*(dptr_i+i*dstrd); if(ps.i == 0.0){ m = ps.r; if (m < 0.0) ps.r=-1.0; else ps.r=1.0; m = (m<0) ? -m:m; } else { re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } if(m > eps0){ *(d->block->R->array+(d->offset+i*d->stride)*d->block->cstride)=m; *(d->block->I->array+(d->offset+i*d->stride)*d->block->cstride)=0.0; if (i < nf){ vsip_scalar_f *fr=fptr_r+i*fstrd; vsip_scalar_f *fi=fptr_i+i*fstrd; re=*fr; im=*fi; *fr=re*ps.r+im*ps.i; *fi=-ps.i*re+ps.r*im; } }else{ *(dptr_r+i*dstrd)=0.0; *(dptr_i+i*dstrd)=0.0; } } for (i=0; i<nf-1; i++){ j=i+1; ps.r=*(fptr_r+i*fstrd); ps.i=*(fptr_i+i*fstrd); if (ps.i == 0.0){ m = ps.r; if (m < 0.0) ps.r =-1.0; else ps.r = 1.0; m = (m < 0.0) ? -m:m; }else{ re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } *(fptr_r+i*fstrd)=m; *(fptr_i+i*fstrd)=0.0; re=*(fptr_r+ j * fstrd); im=*(fptr_i+ j * fstrd); *(fptr_r+ j * fstrd)=re*ps.r-im*ps.i; *(fptr_i+ j * fstrd)=re*ps.i+im*ps.r; } j=nf; i=j-1; ps.r=*(fptr_r+i*fstrd); ps.i=*(fptr_i+i*fstrd); if (ps.i == 0.0){ m = ps.r; if(m < 0.0) ps.r =-1.0; else ps.r = 1.0; m = (m<0) ? -m:m; }else{ re=fabs(ps.r); im=fabs(ps.i); m = CMAG_F(re,im); ps.r /= m; ps.i/=m; } *(fptr_r+i*fstrd)=m; *(fptr_i+i*fstrd)=0.0; } static void cphaseCheck_f(csvdObj_f *svd) { vsip_cmview_f *L = &svd->Ls; vsip_vview_f *d = &svd->ds; vsip_vview_f *f = &svd->fs; vsip_scalar_f eps0 = svd->eps0; vsip_length nf=f->length; vsip_index i,k; vsip_scalar_f ps; vsip_scalar_f m; vsip_cvview_f *l = &svd->ls_one; vsip_scalar_f *fptr=f->block->array + f->offset * f->block->rstride; vsip_scalar_f *dptr=d->block->array + d->offset * d->block->rstride; vsip_scalar_f *re,*im; vsip_stride strd; for(i=0; i<d->length; i++){ ps=dptr[i]; m = (ps<0) ? -ps:ps; ps=sign_f(ps); if(m > eps0){ ccol_sv_f(L,l,i); strd=l->stride*l->block->R->rstride; re=l->block->R->array+l->offset*l->block->R->rstride; im=l->block->I->array+l->offset*l->block->R->rstride; for(k=0; k<l->length*strd; k+=strd){ re[k]*=ps; im[k]*=ps; } dptr[i]=m; if (i < nf) fptr[i]*=ps; } else { dptr[i]=0.0; } } for(i=0; i<nf; i++){ vsip_scalar_f f_i= fptr[i]; if(f_i < 0.0) f_i = -f_i; m = (dptr[i] + dptr[i+1]) * eps0; if (f_i < m) fptr[i] = 0.0; } } static void cphaseCheck2_f(csvdObj_f *svd) /* save U */ { vsip_cmview_f *L = &svd->Ls; vsip_vview_f *d = &svd->ds; vsip_vview_f *f = &svd->fs; vsip_scalar_f eps0 = svd->eps0; vsip_length nf=f->length; vsip_index i,k; vsip_scalar_f ps; vsip_scalar_f m; vsip_cvview_f *l = &svd->ls_one; vsip_scalar_f *fptr=f->block->array + f->offset * f->block->rstride; vsip_scalar_f *dptr=d->block->array + d->offset * d->block->rstride; vsip_scalar_f *re,*im; vsip_stride strd; for(i=0; i<d->length; i++){ ps=dptr[i]; m = (ps<0) ? -ps:ps; ps=sign_f(ps); if(m > eps0){ ccol_sv_f(L,l,i); strd=l->stride*l->block->R->rstride; re=l->block->R->array+l->offset*l->block->R->rstride; im=l->block->I->array+l->offset*l->block->R->rstride; for(k=0; k<l->length*strd; k+=strd){ re[k]*=ps; im[k]*=ps; } dptr[i]=m; if (i < nf) fptr[i]*=ps; } else { dptr[i]=0.0; } } for(i=0; i<nf; i++){ vsip_scalar_f f_i= fptr[i]; if(f_i < 0.0) f_i = -f_i; m = (dptr[i] + dptr[i+1]) * eps0; if (f_i < m) fptr[i] = 0.0; } } static void cphaseCheck1_f(csvdObj_f *svd) /* save V */ { vsip_vview_f *d = &svd->ds; vsip_vview_f *f = &svd->fs; vsip_scalar_f eps0 = svd->eps0; vsip_length nf=f->length; vsip_index i; vsip_scalar_f ps; vsip_scalar_f m; vsip_scalar_f *fptr=f->block->array + f->offset * f->block->rstride; vsip_scalar_f *dptr=d->block->array + d->offset * d->block->rstride; for(i=0; i<d->length; i++){ ps=dptr[i]; m = (ps<0) ? -ps:ps; ps=sign_f(ps); if(m > eps0){ dptr[i]=m; if (i < nf) fptr[i]*=ps; } else { dptr[i]=0.0; } } for(i=0; i<nf; i++){ vsip_scalar_f f_i= fptr[i]; if(f_i < 0.0) f_i = -f_i; m = (dptr[i] + dptr[i+1]) * eps0; if (f_i < m) fptr[i] = 0.0; } } static void chouseProd_f(vsip_cvview_f *v, vsip_cmview_f *A, vsip_cvview_f*w) { vsip_scalar_f *Aptr_r = A->block->R->array+A->offset * A->block->R->rstride; vsip_scalar_f *Aptr_i = A->block->I->array+A->offset * A->block->R->rstride; vsip_scalar_f *vptr_r = v->block->R->array+v->offset * v->block->R->rstride; vsip_scalar_f *vptr_i = v->block->I->array+v->offset * v->block->R->rstride; vsip_scalar_f *wptr_r = w->block->R->array+w->offset * w->block->R->rstride; vsip_scalar_f *wptr_i = w->block->I->array+w->offset * w->block->R->rstride; vsip_stride vstrd=v->stride * v->block->R->rstride; vsip_stride wstrd=w->stride * w->block->R->rstride; vsip_stride AcStrd=A->col_stride*A->block->R->rstride; vsip_stride ArStrd=A->row_stride*A->block->R->rstride; vsip_index i,j,vi,wi; vsip_length M = A->col_length * A->col_stride * A->block->R->rstride; vsip_length N = A->row_length * A->row_stride * A->block->R->rstride; vsip_scalar_f beta = 0.0; vsip_scalar_f t1=0,t2=0; for(i=0;i<v->length;i++){ vsip_scalar_f re=vptr_r[i*vstrd],im=vptr_i[i*vstrd]; t1 += re*re; t2 += im*im; } beta=2.0/(t1+t2); w->length = A->row_length; wi = 0; for(i=0; i<N; i+=ArStrd){ vsip_scalar_f *ar_r=&Aptr_r[i], *ar_i=&Aptr_i[i]; vsip_scalar_f re=0.0,im=0.0; vi = 0; for(j=0; j<M; j+=AcStrd){ re += ar_r[j] * vptr_r[vi] + ar_i[j] * vptr_i[vi]; im += -ar_r[j] * vptr_i[vi] + ar_i[j] * vptr_r[vi]; vi += vstrd; } wptr_r[wi] = re; wptr_i[wi] = -im; wi += wstrd; } vi = 0; for(i=0; i<M; i+=AcStrd){ vsip_scalar_f cr = beta * vptr_r[vi]; vsip_scalar_f ci = beta * vptr_i[vi]; vsip_scalar_f *aprp=Aptr_r+i; vsip_scalar_f *apip=Aptr_i+i; wi = 0; for(j=0; j<N; j+=ArStrd){ vsip_scalar_f yr = wptr_r[wi]; vsip_scalar_f yi = -wptr_i[wi]; aprp[j] -= (cr * yr - ci * yi); apip[j] -= (cr * yi + ci * yr); wi += wstrd; } vi += vstrd; } } static void cprodHouse_f(vsip_cmview_f *A, vsip_cvview_f *v, vsip_cvview_f *w) { vsip_scalar_f *Aptr_r = A->block->R->array+A->offset * A->block->R->rstride; vsip_scalar_f *Aptr_i = A->block->I->array+A->offset * A->block->R->rstride; vsip_scalar_f *vptr_r = v->block->R->array+v->offset * v->block->R->rstride; vsip_scalar_f *vptr_i = v->block->I->array+v->offset * v->block->R->rstride; vsip_scalar_f *wptr_r = w->block->R->array+w->offset * w->block->R->rstride; vsip_scalar_f *wptr_i = w->block->I->array+w->offset * w->block->R->rstride; vsip_stride vstrd=v->stride * v->block->R->rstride; vsip_stride wstrd=w->stride * w->block->R->rstride; vsip_stride AcStrd=A->col_stride*A->block->R->rstride; vsip_stride ArStrd=A->row_stride*A->block->R->rstride; vsip_index i,j,vi,wi; vsip_length M = A->col_length * A->col_stride * A->block->R->rstride; vsip_length N = A->row_length * A->row_stride * A->block->R->rstride; vsip_scalar_f beta = 0.0; vsip_scalar_f t1=0,t2=0; for(i=0;i<v->length;i++){ vsip_scalar_f re=vptr_r[i*vstrd],im=vptr_i[i*vstrd]; t1 += re*re; t2 += im*im; } beta=2.0/(t1+t2); w->length = A->col_length; wi = 0; for(i=0; i<M; i+=AcStrd){ vsip_scalar_f *ac_r=&Aptr_r[i], *ac_i=&Aptr_i[i]; vsip_scalar_f re=0.0,im=0.0; vi = 0; for(j=0; j<N; j+=ArStrd){ re += ac_r[j] * vptr_r[vi] - ac_i[j] * vptr_i[vi]; im += ac_r[j] * vptr_i[vi] + ac_i[j] * vptr_r[vi]; vi += vstrd; } wptr_r[wi] = -beta * re; wptr_i[wi] = -beta * im; wi += wstrd; } wi = 0; for(i=0; i<M; i+=AcStrd){ vsip_scalar_f cr = wptr_r[wi]; vsip_scalar_f ci = wptr_i[wi]; vsip_scalar_f *aprp=Aptr_r+i; vsip_scalar_f *apip=Aptr_i+i; vi = 0; for(j=0; j<N; j+=ArStrd){ vsip_scalar_f yr = vptr_r[vi]; vsip_scalar_f yi = -vptr_i[vi]; aprp[j] += (cr * yr - ci * yi); apip[j] += (cr * yi + ci * yr); vi += vstrd; } wi += wstrd; } } static vsip_cvview_f *chouseVector_f(vsip_cvview_f* x) { vsip_scalar_f *x0r=x->block->R->array + x->offset * x->block->R->rstride; vsip_scalar_f *x0i=x->block->I->array + x->offset * x->block->R->rstride; vsip_scalar_f nrm=cvnorm2_f(x); vsip_cscalar_f t,s; t.r=*x0r;t.i=*x0i; s=csign_f(t); s.r *= nrm; s.i *= nrm; s.r += t.r; s.i +=t.i; *x0r = s.r;*x0i=s.i; nrm = cvnorm2_f(x); if (nrm == 0.0){ *x0r=1.0;*x0i=0.0; }else{ vsip_index i; vsip_stride str=x->stride * x->block->R->rstride; vsip_length n = x->length * str; for(i=0; i<n; i+=str){ x0r[i] /= nrm; x0i[i] /= nrm; } } return x; } static void cVHmatExtract_f(csvdObj_f *svd) { vsip_cmview_f *B = &svd->B; vsip_index i,j; vsip_length n = B->row_length; vsip_cmview_f *Bs=&svd->Bs; vsip_cmview_f *V=svd->R; vsip_cmview_f *Vs=&svd->Rs; vsip_cvview_f *v=&svd->bs; vsip_cscalar_f t; if(n < 3) return; for(i=n-3; i>0; i--){ j=i+1; crow_sv_f(cmsv_f(B,Bs,i,j),v,0); t.r=*(v->block->R->array+v->offset*v->block->cstride); t.i=*(v->block->I->array+v->offset*v->block->cstride); *(v->block->R->array+v->offset*v->block->cstride)=1.0; *(v->block->I->array+v->offset*v->block->cstride)=0.0; cprodHouse_f(cmsv_f(V,Vs,j,j),v,svd->w); *(v->block->R->array+v->offset*v->block->cstride)=t.r; *(v->block->I->array+v->offset*v->block->cstride)=t.i; } crow_sv_f(cmsv_f(B,Bs,0,1),v,0); t.r=*(v->block->R->array+v->offset*v->block->cstride); t.i=*(v->block->I->array+v->offset*v->block->cstride); *(v->block->R->array+v->offset*v->block->cstride)=1.0; *(v->block->I->array+v->offset*v->block->cstride)=0.0; cprodHouse_f(cmsv_f(V,Vs,1,1),v,svd->w); *(v->block->R->array+v->offset*v->block->cstride)=t.r; *(v->block->I->array+v->offset*v->block->cstride)=t.i; } static void cUmatExtract_f(csvdObj_f *svd) { vsip_cmview_f* B=&svd->B; vsip_cmview_f* U=svd->L; vsip_index i; vsip_length m = B->col_length; vsip_length n = B->row_length; vsip_cmview_f *Bs=&svd->Bs; vsip_cmview_f *Us=&svd->Ls; vsip_cvview_f *v=&svd->bs; vsip_cscalar_f t; if (m > n){ i=n-1; ccol_sv_f(cmsv_f(B,Bs,i,i),v,0); t.r=*(v->block->R->array+v->offset*v->block->cstride); t.i=*(v->block->I->array+v->offset*v->block->cstride); *(v->block->R->array+v->offset*v->block->cstride)=1.0; *(v->block->I->array+v->offset*v->block->cstride)=0.0; chouseProd_f(v,cmsv_f(U,Us,i,i),svd->w); *(v->block->R->array+v->offset*v->block->cstride)=t.r; *(v->block->I->array+v->offset*v->block->cstride)=t.i; } for(i=n-2; i>0; i--){ ccol_sv_f(cmsv_f(B,Bs,i,i),v,0); t.r=*(v->block->R->array+v->offset*v->block->cstride); t.i=*(v->block->I->array+v->offset*v->block->cstride); *(v->block->R->array+v->offset*v->block->cstride)=1.0; *(v->block->I->array+v->offset*v->block->cstride)=0.0; chouseProd_f(v,cmsv_f(U,Us,i,i),svd->w); *(v->block->R->array+v->offset*v->block->cstride)=t.r; *(v->block->I->array+v->offset*v->block->cstride)=t.i; } ccol_sv_f(cmsv_f(B,Bs,0,0),v,0); t.r=*(v->block->R->array+v->offset*v->block->cstride); t.i=*(v->block->I->array+v->offset*v->block->cstride); *(v->block->R->array+v->offset*v->block->cstride)=1.0; *(v->block->I->array+v->offset*v->block->cstride)=0.0; chouseProd_f(v,cmsv_f(U,Us,0,0),svd->w); *(v->block->R->array+v->offset*v->block->cstride)=t.r; *(v->block->I->array+v->offset*v->block->cstride)=t.i; } static void cbidiag_f(csvdObj_f *svd) { vsip_cmview_f *B = &svd->B; vsip_cmview_f *Bs = &svd->Bs; vsip_length m = B->col_length; vsip_length n = B->row_length; vsip_cvview_f *x=ccol_sv_f(B,&svd->bs,0); vsip_cvview_f *v=svd->t; vsip_cvview_f *vs = &svd->ts; vsip_index i,j; vsip_cscalar_f z; vsip_scalar_f re,im; v->length = x->length; cvcopy_f(x,v); for(i=0; i<n-1; i++){ v->length=m-i; ccol_sv_f(cmsv_f(B,Bs,i,i),x,0); cvcopy_f(x,v);/*0*/ chouseVector_f(v); re=*(v->block->R->array+v->offset*v->block->cstride); im=*(v->block->I->array+v->offset*v->block->cstride); z.i=(re*re+im*im);z.r=re/z.i;z.i=-im/z.i; csvmul_f(z,v); chouseProd_f(v,Bs,svd->w); cvsv_f(v,vs,1);cvsv_f(x,x,1); cvcopy_f(vs,x);/*1*/ if(i < n-2){ j = i+1; v->length=n-j; crow_sv_f(cmsv_f(B,Bs,i,j),x,0); cvcopy_f(x,v);/*2*/ chouseVector_f(v); { vsip_length _n = v->length; vsip_scalar_f *vpi = v->block->I->array + v->block->cstride * v->offset; vsip_stride vst = v->block->cstride * v->stride; while(_n-- > 0){ *vpi = - *vpi; vpi += vst; } }/*v.conj*/ re=*(v->block->R->array+v->offset*v->block->cstride); im=*(v->block->I->array+v->offset*v->block->cstride); z.i=(re*re+im*im);z.r=re/z.i;z.i=-im/z.i; csvmul_f(z,v); cprodHouse_f(Bs,v,svd->w); cvsv_f(v,vs,1);cvsv_f(x,x,1); cvcopy_f(vs,x);/*3*/ } } if(m > n){ i=n-1; v->length=m-i; ccol_sv_f(cmsv_f(B,Bs,i,i),x,0); cvcopy_f(x,v);/*4*/ chouseVector_f(v); re=*(v->block->R->array+v->offset*v->block->cstride); im=*(v->block->I->array+v->offset*v->block->cstride); z.i=(re*re+im*im);z.r=re/z.i;z.i=-im/z.i; csvmul_f(z,v); chouseProd_f(v,Bs,svd->w); cvsv_f(v,vs,1);cvsv_f(x,x,1); cvcopy_f(vs,x);/*5*/ } } static void cgtProd_f(vsip_index i, vsip_index j,vsip_scalar_f c, vsip_scalar_f s,csvdObj_f *svd) { vsip_cmview_f* R=&svd->Rs; vsip_cvview_f *a1= crow_sv_f(R,&svd->rs_one,i); vsip_cvview_f *a2= crow_sv_f(R,&svd->rs_two,j); vsip_index k; vsip_offset o = a1->block->R->rstride * a1->offset; vsip_stride std=a1->stride * a1->block->R->rstride; vsip_length n = a1->length; register vsip_scalar_f *a1r= a1->block->R->array; register vsip_scalar_f *a1i= a1->block->I->array; register vsip_scalar_f *a2r= a1r; register vsip_scalar_f *a2i= a1i; register vsip_scalar_f b1r,b1i,b2r,b2i; a1r+=o; a1i+=o; o=a2->block->R->rstride * a2->offset; a2r+=o; a2i+=o; for(k=0; k<n; k++){ b1r = *a1r; b1i=*a1i; b2r=*a2r; b2i=*a2i; *a1r =c * b1r + s * b2r; *a1i =c * b1i + s * b2i; *a2r =c * b2r - s * b1r; *a2i =c * b2i - s * b1i; a1r+=std;a1i+=std;a2r+=std;a2i+=std; } } static void cprodG_f(csvdObj_f *svd,vsip_index i, vsip_index j,vsip_scalar_f c, vsip_scalar_f s) { vsip_cmview_f* L=&svd->Ls; vsip_cvview_f *a1= ccol_sv_f(L,&svd->ls_one,i); vsip_cvview_f *a2= ccol_sv_f(L,&svd->ls_two,j); vsip_index k; vsip_offset o = a1->block->R->rstride * a1->offset; register vsip_stride std=a1->stride * a1->block->R->rstride; vsip_length n = a1->length; register vsip_scalar_f *a1r= a1->block->R->array; register vsip_scalar_f *a1i= a1->block->I->array; register vsip_scalar_f *a2r= a1r; register vsip_scalar_f *a2i= a1i; register vsip_scalar_f b1r,b1i,b2r,b2i; a1r+=o; a1i+=o; o=a2->block->R->rstride * a2->offset; a2r+=o; a2i+=o; for(k=0; k<n; k++){ b1r = *a1r; b1i=*a1i; b2r=*a2r; b2i=*a2i; *a1r =c * b1r + s * b2r; *a1i =c * b1i + s * b2i; *a2r =c * b2r - s * b1r; *a2i =c * b2i - s * b1i; a1r+=std;a1i+=std;a2r+=std;a2i+=std; } } static void czeroCol_f(csvdObj_f *svd) { vsip_vview_f *d=&svd->ds; vsip_vview_f *f=&svd->fs; vsip_length n = f->length; givensObj_f g; vsip_scalar_f xd,xf,t; vsip_index i,j,k; if (n == 1){ xd=*(d->block->array + d->offset * d->block->rstride); xf=*(f->block->array + f->offset * f->block->rstride); g=givensCoef_f(xd,xf); *(d->block->array + d->offset * d->block->rstride)=g.r; *(f->block->array + f->offset * f->block->rstride)=0.0; cgtProd_f(0,1,g.c,g.s,svd); }else if (n == 2){ xd=VI_VGET_F(d,1); xf=VI_VGET_F(f,1); g=givensCoef_f(xd,xf); *(d->block->array + (d->offset+1) * d->block->rstride)=g.r; *(f->block->array + (f->offset+1) * f->block->rstride)=0.0; xf=VI_VGET_F(f,0); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset) * f->block->rstride)=xf; cgtProd_f(1,2,g.c,g.s,svd); xd=VI_VGET_F(d,0); g=givensCoef_f(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; cgtProd_f(0,2,g.c,g.s,svd); }else{ i=n-1; j=i-1; k=i; xd=*(d->block->array + (d->offset+i) * d->block->rstride); xf=*(f->block->array + (f->offset+i) * f->block->rstride); g=givensCoef_f(xd,xf); xf=*(f->block->array + (f->offset+j) * f->block->rstride); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; *(f->block->array + (f->offset+i) * f->block->rstride)=0.0; t=-xf*g.s; xf*=g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; cgtProd_f(i,k+1,g.c,g.s,svd); while (i > 1){ i = j; j = i-1; xd=*(d->block->array + (d->offset+i) * d->block->rstride); g=givensCoef_f(xd,t); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; xf=*(f->block->array + (f->offset+j) * f->block->rstride); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; cgtProd_f(i,k+1,g.c,g.s,svd); } xd=*(d->block->array + d->offset * d->block->rstride); g=givensCoef_f(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; cgtProd_f(0,k+1,g.c,g.s,svd); } } static void czeroRow_f(csvdObj_f *svd) { vsip_vview_f *d = &svd->ds; vsip_vview_f *f = &svd->fs; vsip_length n = d->length; givensObj_f g; vsip_scalar_f xd,xf,t; vsip_index i; vsip_scalar_f *dptr=d->block->array+d->block->rstride*d->offset; vsip_scalar_f *fptr=f->block->array+f->block->rstride*f->offset; vsip_stride dstrd=d->stride*d->block->rstride; vsip_stride fstrd=f->stride*f->block->rstride; xd=*dptr; xf=*fptr; g=givensCoef_f(xd,xf); if (n == 1){ *dptr=g.r; *fptr=0.0; cprodG_f(svd,1,0,g.c,g.s); }else{ *dptr=g.r; *fptr=0.0; xf=*(fptr+fstrd); t= -xf * g.s; xf *= g.c; *(fptr+fstrd)=xf; cprodG_f(svd,1,0,g.c,g.s); for(i=1; i<n-1; i++){ xd=*(dptr+i*dstrd); g=givensCoef_f(xd,t); cprodG_f(svd,i+1,0,g.c,g.s); *(dptr+i*dstrd)=g.r; xf=*(fptr+(i+1)*fstrd); t=-xf * g.s; xf *= g.c; *(fptr+(i+1)*fstrd)=xf; } xd=*(dptr+(n-1)*dstrd); g=givensCoef_f(xd,t); *(dptr+(n-1)*dstrd)=g.r; cprodG_f(svd,n,0,g.c,g.s); } } static void czeroCol2_f(csvdObj_f *svd) /* save U */ { vsip_vview_f *d=&svd->ds; vsip_vview_f *f=&svd->fs; vsip_length n = f->length; givensObj_f g; vsip_scalar_f xd,xf,t; vsip_index i,j; if (n == 1){ xd=*(d->block->array + d->offset * d->block->rstride); xf=*(f->block->array + f->offset * f->block->rstride); g=givensCoef_f(xd,xf); *(d->block->array + d->offset * d->block->rstride)=g.r; *(f->block->array + f->offset * f->block->rstride)=0.0; }else if (n == 2){ xd=VI_VGET_F(d,1); xf=VI_VGET_F(f,1); g=givensCoef_f(xd,xf); *(d->block->array + (d->offset+1) * d->block->rstride)=g.r; *(f->block->array + (f->offset+1) * f->block->rstride)=0.0; xf=VI_VGET_F(f,0); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset) * f->block->rstride)=xf; xd=VI_VGET_F(d,0); g=givensCoef_f(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; }else{ i=n-1; j=i-1; xd=*(d->block->array + (d->offset+i) * d->block->rstride); xf=*(f->block->array + (f->offset+i) * f->block->rstride); g=givensCoef_f(xd,xf); xf=*(f->block->array + (f->offset+j) * f->block->rstride); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; *(f->block->array + (f->offset+i) * f->block->rstride)=0.0; t=-xf*g.s; xf*=g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; while (i > 1){ i = j; j = i-1; xd=*(d->block->array + (d->offset+i) * d->block->rstride); g=givensCoef_f(xd,t); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; xf=*(f->block->array + (f->offset+j) * f->block->rstride); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; } xd=*(d->block->array + d->offset * d->block->rstride); g=givensCoef_f(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; } } static void czeroRow2_f(csvdObj_f *svd) /* save U */ { vsip_vview_f *d = &svd->ds; vsip_vview_f *f = &svd->fs; vsip_length n = d->length; givensObj_f g; vsip_scalar_f xd,xf,t; vsip_index i; vsip_scalar_f *dptr=d->block->array+d->block->rstride*d->offset; vsip_scalar_f *fptr=f->block->array+f->block->rstride*f->offset; vsip_stride dstrd=d->stride*d->block->rstride; vsip_stride fstrd=f->stride*f->block->rstride; xd=*dptr; xf=*fptr; g=givensCoef_f(xd,xf); if (n == 1){ *dptr=g.r; *fptr=0.0; cprodG_f(svd,1,0,g.c,g.s); }else{ *dptr=g.r; *fptr=0.0; xf=*(fptr+fstrd); t= -xf * g.s; xf *= g.c; *(fptr+fstrd)=xf; cprodG_f(svd,1,0,g.c,g.s); for(i=1; i<n-1; i++){ xd=*(dptr+i*dstrd); g=givensCoef_f(xd,t); cprodG_f(svd,i+1,0,g.c,g.s); *(dptr+i*dstrd)=g.r; xf=*(fptr+(i+1)*fstrd); t=-xf * g.s; xf *= g.c; *(fptr+(i+1)*fstrd)=xf; } xd=*(dptr+(n-1)*dstrd); g=givensCoef_f(xd,t); *(dptr+(n-1)*dstrd)=g.r; cprodG_f(svd,n,0,g.c,g.s); } } static void czeroCol1_f(csvdObj_f *svd) /* save V */ { vsip_vview_f *d=&svd->ds; vsip_vview_f *f=&svd->fs; vsip_length n = f->length; givensObj_f g; vsip_scalar_f xd,xf,t; vsip_index i,j,k; if (n == 1){ xd=*(d->block->array + d->offset * d->block->rstride); xf=*(f->block->array + f->offset * f->block->rstride); g=givensCoef_f(xd,xf); *(d->block->array + d->offset * d->block->rstride)=g.r; *(f->block->array + f->offset * f->block->rstride)=0.0; cgtProd_f(0,1,g.c,g.s,svd); }else if (n == 2){ xd=VI_VGET_F(d,1); xf=VI_VGET_F(f,1); g=givensCoef_f(xd,xf); *(d->block->array + (d->offset+1) * d->block->rstride)=g.r; *(f->block->array + (f->offset+1) * f->block->rstride)=0.0; xf=VI_VGET_F(f,0); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset) * f->block->rstride)=xf; cgtProd_f(1,2,g.c,g.s,svd); xd=VI_VGET_F(d,0); g=givensCoef_f(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; cgtProd_f(0,2,g.c,g.s,svd); }else{ i=n-1; j=i-1; k=i; xd=*(d->block->array + (d->offset+i) * d->block->rstride); xf=*(f->block->array + (f->offset+i) * f->block->rstride); g=givensCoef_f(xd,xf); xf=*(f->block->array + (f->offset+j) * f->block->rstride); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; *(f->block->array + (f->offset+i) * f->block->rstride)=0.0; t=-xf*g.s; xf*=g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; cgtProd_f(i,k+1,g.c,g.s,svd); while (i > 1){ i = j; j = i-1; xd=*(d->block->array + (d->offset+i) * d->block->rstride); g=givensCoef_f(xd,t); *(d->block->array + (d->offset+i) * d->block->rstride)=g.r; xf=*(f->block->array + (f->offset+j) * f->block->rstride); t= -xf * g.s; xf *= g.c; *(f->block->array + (f->offset+j) * f->block->rstride)=xf; cgtProd_f(i,k+1,g.c,g.s,svd); } xd=*(d->block->array + d->offset * d->block->rstride); g=givensCoef_f(xd,t); *(d->block->array + d->offset * d->block->rstride)=g.r; cgtProd_f(0,k+1,g.c,g.s,svd); } } static void czeroRow1_f(csvdObj_f *svd) /* save V */ { vsip_vview_f *d = &svd->ds; vsip_vview_f *f = &svd->fs; vsip_length n = d->length; givensObj_f g; vsip_scalar_f xd,xf,t; vsip_index i; vsip_scalar_f *dptr=d->block->array+d->block->rstride*d->offset; vsip_scalar_f *fptr=f->block->array+f->block->rstride*f->offset; vsip_stride dstrd=d->stride*d->block->rstride; vsip_stride fstrd=f->stride*f->block->rstride; xd=*dptr; xf=*fptr; g=givensCoef_f(xd,xf); if (n == 1){ *dptr=g.r; *fptr=0.0; }else{ *dptr=g.r; *fptr=0.0; xf=*(fptr+fstrd); t= -xf * g.s; xf *= g.c; *(fptr+fstrd)=xf; for(i=1; i<n-1; i++){ xd=*(dptr+i*dstrd); g=givensCoef_f(xd,t); *(dptr+i*dstrd)=g.r; xf=*(fptr+(i+1)*fstrd); t=-xf * g.s; xf *= g.c; *(fptr+(i+1)*fstrd)=xf; } xd=*(dptr+(n-1)*dstrd); g=givensCoef_f(xd,t); *(dptr+(n-1)*dstrd)=g.r; } } static void csvdStep_f(csvdObj_f *svd) { vsip_vview_f *d = &svd->ds; vsip_vview_f *f = &svd->fs; givensObj_f g; vsip_length n = d->length; vsip_scalar_f mu=0.0, x1=0.0, x2=0.0; vsip_scalar_f t=0.0; vsip_index i,j,k; vsip_scalar_f d2=0.0,f1=0.0,d3=0.0,f2=0.0; vsip_scalar_f *fptr,*dptr,*tdptr,*tfptr; vsip_stride fstd=f->stride*f->block->rstride, dstd=d->stride*d->block->rstride; dptr=d->block->array+d->offset*d->block->rstride; fptr=f->block->array+f->offset*f->block->rstride; if(n >= 3){ d2=*(dptr+dstd*(n-2));f1= *(fptr+fstd*(n-3));d3 = *(dptr+dstd*(n-1));f2= *(fptr+fstd*(n-2)); } else if(n == 2){ d2=*dptr; d3=*(dptr+dstd); f1=0; f2=*fptr; } else { printf("should not be here (see svdStep_f"); exit(-1); } mu = svdMu_f(d2,f1,d3,&f2,svd->eps0); if(f2 == 0.0) *(fptr+fstd*(n-2)) = 0.0; x1=*dptr; x2 = x1 * *fptr; x1 *= x1; x1 -= mu; g=givensCoef_f(x1,x2); x1=*dptr;x2=*fptr; *fptr=g.c * x2 - g.s * x1; *dptr=x1 * g.c + x2 * g.s; tdptr=dptr+dstd; t=*tdptr; *tdptr=t*g.c; t*=g.s; cgtProd_f(0,1,g.c,g.s,svd); for(i=0; i<n-2; i++){ j=i+1; k=i+2; tdptr=dptr+i*dstd; tfptr=fptr+i*fstd; g = givensCoef_f(*tdptr,t); *tdptr=g.r; x1 = *(tdptr+dstd)*g.c; x2=*tfptr*g.s; t= x1 - x2; x1=*(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s ; *(fptr+i*fstd)= x1+x2; *(dptr+j*dstd) = t; x1=*(fptr+j*fstd); t=g.s * x1; *(fptr+j*fstd) = x1*g.c; cprodG_f(svd,i, j, g.c, g.s); g=givensCoef_f(*(fptr+i*fstd),t); *(fptr+i*fstd)=g.r; x1=*(dptr+j*dstd); x2=*(fptr+j*fstd); *(dptr+j*dstd)=g.c * x1 + g.s * x2; *(fptr+j*fstd)=g.c * x2 - g.s * x1; x1=*(dptr+k*dstd); t=g.s * x1; *(dptr+k*dstd)=x1*g.c; cgtProd_f(j,k, g.c, g.s,svd); } i=n-2; j=n-1; g = givensCoef_f(*(dptr+i*dstd),t); *(dptr+i*dstd)=g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t=x1 - x2; x1 = *(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s; *(fptr+i*fstd)=x1+x2; *(dptr+j*dstd)=t; cprodG_f(svd,i, j, g.c, g.s); } static void csvdStep2_f(csvdObj_f *svd) /* save U */ { vsip_vview_f *d = &svd->ds; vsip_vview_f *f = &svd->fs; givensObj_f g; vsip_length n = d->length; vsip_scalar_f mu=0.0, x1=0.0, x2=0.0; vsip_scalar_f t=0.0; vsip_index i,j,k; vsip_scalar_f d2=0.0,f1=0.0,d3=0.0,f2=0.0; vsip_scalar_f *fptr,*dptr,*tdptr,*tfptr; vsip_stride fstd=f->stride*f->block->rstride, dstd=d->stride*d->block->rstride; dptr=d->block->array+d->offset*d->block->rstride; fptr=f->block->array+f->offset*f->block->rstride; if(n >= 3){ d2=*(dptr+dstd*(n-2));f1= *(fptr+fstd*(n-3));d3 = *(dptr+dstd*(n-1));f2= *(fptr+fstd*(n-2)); } else if(n == 2){ d2=*dptr; d3=*(dptr+dstd); f1=0; f2=*fptr; } else { printf("should not be here (see svdStep_f"); exit(-1); } mu = svdMu_f(d2,f1,d3,&f2,svd->eps0); if(f2 == 0.0) *(fptr+fstd*(n-2)) = 0.0; x1=*dptr; x2 = x1 * *fptr; x1 *= x1; x1 -= mu; g=givensCoef_f(x1,x2); x1=*dptr;x2=*fptr; *fptr=g.c * x2 - g.s * x1; *dptr=x1 * g.c + x2 * g.s; tdptr=dptr+dstd; t=*tdptr; *tdptr=t*g.c; t*=g.s; for(i=0; i<n-2; i++){ j=i+1; k=i+2; tdptr=dptr+i*dstd; tfptr=fptr+i*fstd; g = givensCoef_f(*tdptr,t); *tdptr=g.r; x1 = *(tdptr+dstd)*g.c; x2=*tfptr*g.s; t= x1 - x2; x1=*(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s ; *(fptr+i*fstd)= x1+x2; *(dptr+j*dstd) = t; x1=*(fptr+j*fstd); t=g.s * x1; *(fptr+j*fstd) = x1*g.c; cprodG_f(svd,i, j, g.c, g.s); g=givensCoef_f(*(fptr+i*fstd),t); *(fptr+i*fstd)=g.r; x1=*(dptr+j*dstd); x2=*(fptr+j*fstd); *(dptr+j*dstd)=g.c * x1 + g.s * x2; *(fptr+j*fstd)=g.c * x2 - g.s * x1; x1=*(dptr+k*dstd); t=g.s * x1; *(dptr+k*dstd)=x1*g.c; } i=n-2; j=n-1; g = givensCoef_f(*(dptr+i*dstd),t); *(dptr+i*dstd)=g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t=x1 - x2; x1 = *(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s; *(fptr+i*fstd)=x1+x2; *(dptr+j*dstd)=t; cprodG_f(svd,i, j, g.c, g.s); } static void csvdStep1_f(csvdObj_f *svd) /* save V */ { vsip_vview_f *d = &svd->ds; vsip_vview_f *f = &svd->fs; givensObj_f g; vsip_length n = d->length; vsip_scalar_f mu=0.0, x1=0.0, x2=0.0; vsip_scalar_f t=0.0; vsip_index i,j,k; vsip_scalar_f d2=0.0,f1=0.0,d3=0.0,f2=0.0; vsip_scalar_f *fptr,*dptr,*tdptr,*tfptr; vsip_stride fstd=f->stride*f->block->rstride, dstd=d->stride*d->block->rstride; dptr=d->block->array+d->offset*d->block->rstride; fptr=f->block->array+f->offset*f->block->rstride; if(n >= 3){ d2=*(dptr+dstd*(n-2));f1= *(fptr+fstd*(n-3));d3 = *(dptr+dstd*(n-1));f2= *(fptr+fstd*(n-2)); } else if(n == 2){ d2=*dptr; d3=*(dptr+dstd); f1=0; f2=*fptr; } else { printf("should not be here (see svdStep_f"); exit(-1); } mu = svdMu_f(d2,f1,d3,&f2,svd->eps0); if(f2 == 0.0) *(fptr+fstd*(n-2)) = 0.0; x1=*dptr; x2 = x1 * *fptr; x1 *= x1; x1 -= mu; g=givensCoef_f(x1,x2); x1=*dptr;x2=*fptr; *fptr=g.c * x2 - g.s * x1; *dptr=x1 * g.c + x2 * g.s; tdptr=dptr+dstd; t=*tdptr; *tdptr=t*g.c; t*=g.s; cgtProd_f(0,1,g.c,g.s,svd); for(i=0; i<n-2; i++){ j=i+1; k=i+2; tdptr=dptr+i*dstd; tfptr=fptr+i*fstd; g = givensCoef_f(*tdptr,t); *tdptr=g.r; x1 = *(tdptr+dstd)*g.c; x2=*tfptr*g.s; t= x1 - x2; x1=*(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s ; *(fptr+i*fstd)= x1+x2; *(dptr+j*dstd) = t; x1=*(fptr+j*fstd); t=g.s * x1; *(fptr+j*fstd) = x1*g.c; g=givensCoef_f(*(fptr+i*fstd),t); *(fptr+i*fstd)=g.r; x1=*(dptr+j*dstd); x2=*(fptr+j*fstd); *(dptr+j*dstd)=g.c * x1 + g.s * x2; *(fptr+j*fstd)=g.c * x2 - g.s * x1; x1=*(dptr+k*dstd); t=g.s * x1; *(dptr+k*dstd)=x1*g.c; cgtProd_f(j,k, g.c, g.s,svd); } i=n-2; j=n-1; g = givensCoef_f(*(dptr+i*dstd),t); *(dptr+i*dstd)=g.r; x1=*(dptr+j*dstd)*g.c; x2=*(fptr+i*fstd)*g.s; t=x1 - x2; x1 = *(fptr+i*fstd) * g.c; x2=*(dptr+j*dstd) * g.s; *(fptr+i*fstd)=x1+x2; *(dptr+j*dstd)=t; } static void svdFinalize_f(svdObj_f *s) { if(s) { vsip_valldestroy_f(s->t); vsip_valldestroy_f(s->w); vsip_malldestroy_f(s->R); vsip_malldestroy_f(s->L); vsip_valldestroy_vi(s->indx_L); vsip_valldestroy_vi(s->indx_R); vsip_valldestroy_f(s->d); vsip_valldestroy_f(s->f); free(s); } s=NULL; } static svdObj_f* svdInit_f(vsip_length m, vsip_length n,int Usave,int Vsave) { svdObj_f *s; if(m < n){ printf("Column length must not be less than row length"); return NULL; } s=malloc(sizeof(svdObj_f)); if(!s) { printf("\nfailed to allocate svd object\n"); return NULL; } s->init=0; if(!(s->t = vsip_vcreate_f(m,VSIP_MEM_NONE)))s->init++;else s->ts = *s->t; if(!(s->w = vsip_vcreate_f(m,VSIP_MEM_NONE)))s->init++; if(Usave){ if(Usave == 1 ){ if(!(s->L=vsip_mcreate_f(m,m,VSIP_ROW,VSIP_MEM_NONE)))s->init++; if(!(s->indx_L=vsip_vcreate_vi(n,VSIP_MEM_NONE))) s->init++; }else{ /* must be part */ if(!(s->L=vsip_mcreate_f(m,n,VSIP_ROW,VSIP_MEM_NONE)))s->init++; if(!(s->indx_L=vsip_vcreate_vi(n,VSIP_MEM_NONE))) s->init++; } } else { s->L=NULL; s->indx_L=NULL; } if(Vsave){ if(!(s->R=vsip_mcreate_f(n,n,VSIP_ROW,VSIP_MEM_NONE)))s->init++; if(!(s->indx_R=vsip_vcreate_vi(n,VSIP_MEM_NONE))) s->init++; } else { s->R=NULL; s->indx_R=NULL; } if(!(s->d = vsip_vcreate_f(n,VSIP_MEM_NONE)))s->init++; if(!(s->f = vsip_vcreate_f(n-1,VSIP_MEM_NONE)))s->init++; if(s->init){ svdFinalize_f(s); return NULL; } if(Usave) meye_f(s->L); if(Vsave) meye_f(s->R); return s; } static void svdBidiag_f(svdObj_f *svd) { svd->eps0=(mnormFro_f((&svd->B))/(vsip_scalar_f)svd->B.row_length)*EPS; bidiag_f(svd); UmatExtract_f(svd); VHmatExtract_f(svd); biDiagPhaseToZero_f(svd); } static void svdBidiag2_f(svdObj_f *svd) /* save U */ { svd->eps0=(mnormFro_f((&svd->B))/(vsip_scalar_f)svd->B.row_length)*EPS; bidiag_f(svd); UmatExtract_f(svd); biDiagPhaseToZero2_f(svd); } static void svdBidiag1_f(svdObj_f *svd) /* save V */ { svd->eps0=(mnormFro_f((&svd->B))/(vsip_scalar_f)svd->B.row_length)*EPS; bidiag_f(svd); VHmatExtract_f(svd); biDiagPhaseToZero1_f(svd); } static void svdBidiag0_f(svdObj_f *svd) { svd->eps0=(mnormFro_f(&svd->B)/(vsip_scalar_f)svd->B.row_length)*EPS; bidiag_f(svd); biDiagPhaseToZero0_f(svd); } static void svdIteration_f(svdObj_f* svd) { vsip_mview_f *L0 = svd->L; vsip_mview_f *L = &svd->Ls; vsip_vview_f *d0 = svd->d; vsip_vview_f *d = &svd->ds; vsip_vview_f *f0 = svd->f; vsip_vview_f *f = &svd->fs; vsip_mview_f *R0 = svd->R; vsip_mview_f *R= &svd->Rs; vsip_scalar_f eps0 = svd->eps0; vsip_length n; svdCorner cnr; vsip_index k; vsip_length cntr=0; vsip_length maxcntr=5*d0->length; *d=*d0;*f=*f0;*L=*L0; *R=*R0; while (cntr++ < maxcntr){ cnr=svdCorners_f(f0); if (cnr.j == 0) break; ivsv_f(d0,d,cnr.i,cnr.j); ivsv_f(f0,f,cnr.i,cnr.j-1); imsv_f(L0,L,0,0,cnr.i,cnr.j); imsv_f(R0,R,cnr.i,cnr.j,0,0); n=f->length; k=zeroFind_f(d,eps0); if (k > 0 ){ k=k-1; if(VI_VGET_F(d,n) == 0.0){ zeroCol_f(svd); }else{ imsv_f(L,L,0,0,k,0); d->length-=k+1; d->offset += k+1; f->length -= k; f->offset += k; zeroRow_f(svd); } }else{ svdStep_f(svd); } phaseCheck_f(svd); } } static void svdIteration2_f(svdObj_f* svd) /* save U */ { vsip_mview_f *L0 = svd->L; vsip_mview_f *L = &svd->Ls; vsip_vview_f *d0 = svd->d; vsip_vview_f *d = &svd->ds; vsip_vview_f *f0 = svd->f; vsip_vview_f *f = &svd->fs; vsip_scalar_f eps0 = svd->eps0; vsip_length n; svdCorner cnr; vsip_index k; vsip_length cntr=0; vsip_length maxcntr=5*d0->length; *d=*d0;*f=*f0;*L=*L0; while (cntr++ < maxcntr){ cnr=svdCorners_f(f0); if (cnr.j == 0) break; ivsv_f(d0,d,cnr.i,cnr.j); ivsv_f(f0,f,cnr.i,cnr.j-1); imsv_f(L0,L,0,0,cnr.i,cnr.j); n=f->length; k=zeroFind_f(d,eps0); if (k > 0 ){ k=k-1; if(VI_VGET_F(d,n) == 0.0){ zeroCol2_f(svd); }else{ imsv_f(L,L,0,0,k,0); d->length-=k+1; d->offset += k+1; f->length -= k; f->offset += k; zeroRow2_f(svd); } }else{ svdStep2_f(svd); } phaseCheck2_f(svd); } } static void svdIteration1_f(svdObj_f* svd) /* save V */ { vsip_vview_f *d0 = svd->d; vsip_vview_f *d = &svd->ds; vsip_vview_f *f0 = svd->f; vsip_vview_f *f = &svd->fs; vsip_mview_f *R0 = svd->R; vsip_mview_f *R= &svd->Rs; vsip_scalar_f eps0 = svd->eps0; vsip_length n; svdCorner cnr; vsip_index k; vsip_length cntr=0; vsip_length maxcntr=5*d0->length; *d=*d0;*f=*f0; *R=*R0; while (cntr++ < maxcntr){ cnr=svdCorners_f(f0); if (cnr.j == 0) break; ivsv_f(d0,d,cnr.i,cnr.j); ivsv_f(f0,f,cnr.i,cnr.j-1); imsv_f(R0,R,cnr.i,cnr.j,0,0); n=f->length; k=zeroFind_f(d,eps0); if (k > 0 ){ k=k-1; if(VI_VGET_F(d,n) == 0.0){ zeroCol1_f(svd); }else{ d->length-=k+1; d->offset += k+1; f->length -= k; f->offset += k; zeroRow1_f(svd); } }else{ svdStep1_f(svd); } phaseCheck1_f(svd); } } static void svdIteration0_f(svdObj_f* svd) { vsip_vview_f *d0 = svd->d; vsip_vview_f *d = &svd->ds; vsip_vview_f *f0 = svd->f; vsip_vview_f *f = &svd->fs; vsip_scalar_f eps0 = svd->eps0; vsip_length n; svdCorner cnr; vsip_index k; vsip_length cntr=0; vsip_length maxcntr=5*d0->length; *d=*d0;*f=*f0; while (cntr++ < maxcntr){ cnr=svdCorners_f(f0); if (cnr.j == 0) break; ivsv_f(d0,d,cnr.i,cnr.j); ivsv_f(f0,f,cnr.i,cnr.j-1); n=f->length; k=zeroFind_f(d,eps0); if (k > 0 ){ k=k-1; if(VI_VGET_F(d,n) == 0.0){ zeroCol0_f(svd); }else{ d->length-=k+1; d->offset += k+1; f->length -= k; f->offset += k; zeroRow0_f(svd); } }else{ svdStep0_f(svd); } phaseCheck0_f(svd); } } static void svdSort_f(svdObj_f *svd) { vsip_vview_f *d = svd->d; vsip_length n=d->length; vsip_vview_vi* indx_L = svd->indx_L; vsip_vview_vi* indx_R = svd->indx_R; vsip_mview_f *L0 = svd->L; vsip_mview_f *L=&svd->Ls; vsip_mview_f *R0 = svd->R; vsip_vsortip_f(d,VSIP_SORT_BYVALUE,VSIP_SORT_DESCENDING,VSIP_TRUE,indx_L); vcopy_vi(indx_L,indx_R); imsv_f( L0, L, 0,0, 0, n); mpermute_onceCol_f(L,indx_L); mpermute_onceRow_f(R0,indx_R); } static void svdSort2_f(svdObj_f *svd) /* save U */ { vsip_vview_f *d = svd->d; vsip_length n=d->length; vsip_vview_vi* indx_L = svd->indx_L; vsip_mview_f *L0 = svd->L; vsip_mview_f *L=&svd->Ls; vsip_vsortip_f(d,VSIP_SORT_BYVALUE,VSIP_SORT_DESCENDING,VSIP_TRUE,indx_L); imsv_f( L0, L, 0,0, 0, n); mpermute_onceCol_f(L,indx_L); } static void svdSort1_f(svdObj_f *svd) /* save V */ { vsip_vview_f *d = svd->d; vsip_vview_vi* indx_R = svd->indx_R; vsip_mview_f *R0 = svd->R; vsip_vsortip_f(d,VSIP_SORT_BYVALUE,VSIP_SORT_DESCENDING,VSIP_TRUE,indx_R); mpermute_onceRow_f(R0,indx_R); } static void svdSort0_f(svdObj_f *svd) { vsip_vview_f *d = svd->d; vsip_vsortip_f(d,VSIP_SORT_BYVALUE,VSIP_SORT_DESCENDING,VSIP_FALSE,NULL); } static void svd_f(svdObj_f *s,int Usave, int Vsave) { if(Usave && Vsave){ svdBidiag_f(s); svdIteration_f(s); svdSort_f(s); }else if(Usave){ svdBidiag2_f(s); svdIteration2_f(s); svdSort2_f(s); }else if (Vsave){ svdBidiag1_f(s); svdIteration1_f(s); svdSort1_f(s); }else{ svdBidiag0_f(s); svdIteration0_f(s); svdSort0_f(s); } } static void csvdFinalize_f(csvdObj_f *s) { if(s) { vsip_cvalldestroy_f((s)->t); vsip_cvalldestroy_f((s)->w); vsip_cmalldestroy_f((s)->R); vsip_cmalldestroy_f((s)->L); vsip_valldestroy_vi((s)->indx_L); vsip_valldestroy_vi((s)->indx_R); vsip_valldestroy_f((s)->d); vsip_valldestroy_f((s)->f); free(s); } s=NULL; } static csvdObj_f* csvdInit_f(vsip_length m, vsip_length n,int Usave,int Vsave) { csvdObj_f *s; if(m < n){ printf("Column length must not be less than row length"); return NULL; } s=malloc(sizeof(csvdObj_f)); if(!s) { printf("\nfailed to allocate svd object\n"); return NULL; } s->init=0; if(!(s->t = vsip_cvcreate_f(m,VSIP_MEM_NONE)))s->init++;else s->ts = *s->t; if(!(s->w = vsip_cvcreate_f(m,VSIP_MEM_NONE)))s->init++; if(Usave){ if(Usave == 1 ){ if(!(s->L=vsip_cmcreate_f(m,m,VSIP_ROW,VSIP_MEM_NONE)))s->init++; if(!(s->indx_L=vsip_vcreate_vi(n,VSIP_MEM_NONE))) s->init++; }else{ /* must be part */ if(!(s->L=vsip_cmcreate_f(m,n,VSIP_ROW,VSIP_MEM_NONE)))s->init++; if(!(s->indx_L=vsip_vcreate_vi(n,VSIP_MEM_NONE))) s->init++; } } else { s->L=NULL; s->indx_L=NULL; } if(Vsave){ if(!(s->R=vsip_cmcreate_f(n,n,VSIP_ROW,VSIP_MEM_NONE)))s->init++; if(!(s->indx_R=vsip_vcreate_vi(n,VSIP_MEM_NONE))) s->init++; } else { s->R=NULL; s->indx_R=NULL; } if(!(s->d = vsip_vcreate_f(n,VSIP_MEM_NONE)))s->init++; if(!(s->f = vsip_vcreate_f(n-1,VSIP_MEM_NONE)))s->init++; if(s->init){ csvdFinalize_f(s); return NULL; } if(Usave) cmeye_f(s->L); if(Vsave) cmeye_f(s->R); return s; } static void csvdBidiag_f(csvdObj_f *svd) { svd->eps0=cmnormFro_f(&svd->B)/(vsip_scalar_f)(svd->B.row_length) * EPS; cbidiag_f(svd); cUmatExtract_f(svd); cVHmatExtract_f(svd); cbiDiagPhaseToZero_f(svd); vreal_sv_f(cdiag_sv_f(&svd->B, &svd->bs, 0),(&svd->rbs)); vcopy_f((&svd->rbs),svd->d); vreal_sv_f(cdiag_sv_f(&svd->B, &svd->bs, 1),(&svd->rbs)); vcopy_f((&svd->rbs),svd->f); } static void csvdBidiag2_f(csvdObj_f *svd) { svd->eps0=cmnormFro_f(&svd->B)/(vsip_scalar_f)(svd->B.row_length) * EPS; cbidiag_f(svd); cUmatExtract_f(svd); cbiDiagPhaseToZero2_f(svd); vreal_sv_f(cdiag_sv_f(&svd->B, &svd->bs, 0),(&svd->rbs)); vcopy_f((&svd->rbs),svd->d); vreal_sv_f(cdiag_sv_f(&svd->B, &svd->bs, 1),(&svd->rbs)); vcopy_f((&svd->rbs),svd->f); } static void csvdBidiag1_f(csvdObj_f *svd) { svd->eps0=cmnormFro_f(&svd->B)/(vsip_scalar_f)(svd->B.row_length) * EPS; cbidiag_f(svd); cVHmatExtract_f(svd); cbiDiagPhaseToZero1_f(svd); vreal_sv_f(cdiag_sv_f(&svd->B, &svd->bs, 0),(&svd->rbs)); vcopy_f((&svd->rbs),svd->d); vreal_sv_f(cdiag_sv_f(&svd->B, &svd->bs, 1),(&svd->rbs)); vcopy_f((&svd->rbs),svd->f); } static void csvdBidiag0_f(csvdObj_f *svd) { svd->eps0=cmnormFro_f(&svd->B)/(vsip_scalar_f)(svd->B.row_length) * EPS; cbidiag_f(svd); cbiDiagPhaseToZero0_f(svd); vreal_sv_f(cdiag_sv_f(&svd->B, &svd->bs, 0),(&svd->rbs)); vcopy_f((&svd->rbs),svd->d); vreal_sv_f(cdiag_sv_f(&svd->B, &svd->bs, 1),(&svd->rbs)); vcopy_f((&svd->rbs),svd->f); } static void csvdIteration_f(csvdObj_f *svd) { vsip_cmview_f *L0 = svd->L; vsip_vview_f *d0 = svd->d; vsip_vview_f *f0 = svd->f; vsip_cmview_f *R0 = svd->R; vsip_scalar_f eps0 = svd->eps0; vsip_vview_f *d=&svd->ds; vsip_vview_f *f=&svd->fs; vsip_cmview_f *L=&svd->Ls; vsip_cmview_f *R=&svd->Rs; vsip_length n; svdCorner cnr; vsip_index k; vsip_length cntr=0; vsip_length maxcntr=5*d0->length; *d=*d0;*f=*f0;*L=*L0; *R=*R0; while (cntr++ < maxcntr){ cnr=svdCorners_f(f0); if (cnr.j == 0) break; ivsv_f(d0,d,cnr.i,cnr.j); ivsv_f(f0,f,cnr.i,cnr.j-1); cimsv_f(L0,L,0,0,cnr.i,cnr.j); cimsv_f(R0,R,cnr.i,cnr.j,0,0); n=f->length; k=zeroFind_f(d,eps0); if (k > 0){ k=k-1; if(VI_VGET_F(d,n) == 0.0){ czeroCol_f(svd); }else{ cimsv_f(L,L,0,0,k,0); d->length-=(k+1); d->offset += (k+1); f->length -= k; f->offset += k; czeroRow_f(svd); } }else{ csvdStep_f(svd); } cphaseCheck_f(svd); } } static void csvdIteration2_f(csvdObj_f *svd) /* save U */ { vsip_cmview_f *L0 = svd->L; vsip_vview_f *d0 = svd->d; vsip_vview_f *f0 = svd->f; vsip_scalar_f eps0 = svd->eps0; vsip_vview_f *d=&svd->ds; vsip_vview_f *f=&svd->fs; vsip_cmview_f *L=&svd->Ls; vsip_length n; svdCorner cnr; vsip_index k; vsip_length cntr=0; vsip_length maxcntr=5*d0->length; *d=*d0;*f=*f0;*L=*L0; while (cntr++ < maxcntr){ cnr=svdCorners_f(f0); if (cnr.j == 0) break; ivsv_f(d0,d,cnr.i,cnr.j); ivsv_f(f0,f,cnr.i,cnr.j-1); cimsv_f(L0,L,0,0,cnr.i,cnr.j); n=f->length; k=zeroFind_f(d,eps0); if (k > 0){ k=k-1; if(VI_VGET_F(d,n) == 0.0){ czeroCol2_f(svd); }else{ cimsv_f(L,L,0,0,k,0); d->length-=(k+1); d->offset += (k+1); f->length -= k; f->offset += k; czeroRow2_f(svd); } }else{ csvdStep2_f(svd); } cphaseCheck2_f(svd); } } static void csvdIteration1_f(csvdObj_f *svd) /* save V */ { vsip_vview_f *d0 = svd->d; vsip_vview_f *f0 = svd->f; vsip_cmview_f *R0 = svd->R; vsip_scalar_f eps0 = svd->eps0; vsip_vview_f *d=&svd->ds; vsip_vview_f *f=&svd->fs; vsip_cmview_f *R=&svd->Rs; vsip_length n; svdCorner cnr; vsip_index k; vsip_length cntr=0; vsip_length maxcntr=5*d0->length; *d=*d0;*f=*f0;*R=*R0; while (cntr++ < maxcntr){ cnr=svdCorners_f(f0); if (cnr.j == 0) break; ivsv_f(d0,d,cnr.i,cnr.j); ivsv_f(f0,f,cnr.i,cnr.j-1); cimsv_f(R0,R,cnr.i,cnr.j,0,0); n=f->length; k=zeroFind_f(d,eps0); if (k > 0){ k=k-1; if(VI_VGET_F(d,n) == 0.0){ czeroCol1_f(svd); }else{ d->length-=(k+1); d->offset += (k+1); f->length -= k; f->offset += k; czeroRow1_f(svd); } }else{ csvdStep1_f(svd); } cphaseCheck1_f(svd); } } static void csvdSort_f(csvdObj_f *svd) { vsip_cmview_f* L0 = svd->L; vsip_vview_f* d = svd->d; vsip_cmview_f* R0 = svd->R; vsip_length n=d->length; vsip_vview_vi* indx_L = svd->indx_L; vsip_vview_vi* indx_R = svd->indx_R; vsip_cmview_f *L=&svd->Ls; vsip_vsortip_f(d,VSIP_SORT_BYVALUE,VSIP_SORT_DESCENDING,VSIP_TRUE,indx_L); vcopy_vi(indx_L,indx_R); cimsv_f( L0, L, 0,0, 0, n); cmpermute_onceCol_f(L,indx_L); cmpermute_onceRow_f(R0,indx_R); } static void csvdSort2_f(csvdObj_f *svd) /* save U */ { vsip_cmview_f* L0 = svd->L; vsip_vview_f* d = svd->d; vsip_length n=d->length; vsip_vview_vi* indx_L = svd->indx_L; vsip_cmview_f *L=&svd->Ls; vsip_vsortip_f(d,VSIP_SORT_BYVALUE,VSIP_SORT_DESCENDING,VSIP_TRUE,indx_L); cimsv_f( L0, L, 0,0, 0, n); cmpermute_onceCol_f(L,indx_L); } static void csvdSort1_f(csvdObj_f *svd) /* save V */ { vsip_vview_f* d = svd->d; vsip_cmview_f* R0 = svd->R; vsip_vview_vi* indx_R = svd->indx_R; vsip_vsortip_f(d,VSIP_SORT_BYVALUE,VSIP_SORT_DESCENDING,VSIP_TRUE,indx_R); cmpermute_onceRow_f(R0,indx_R); } static void csvd_f(csvdObj_f *s,int Usave,int Vsave) { if(Usave && Vsave){ csvdBidiag_f(s); csvdIteration_f(s); csvdSort_f(s); }else if(Usave){ csvdBidiag2_f(s); csvdIteration2_f(s); csvdSort2_f(s); }else if (Vsave){ csvdBidiag1_f(s); csvdIteration1_f(s); csvdSort1_f(s); }else{ svdObj_f t; csvdBidiag0_f(s); /* after bidiag this path same as real */ t.eps0=s->eps0; t.d=s->d;t.ds=s->ds;t.f=s->f;t.fs=s->fs; svdIteration0_f(&t); svdSort0_f(&t); } } /* Real */ int vsip_svd_destroy_f(vsip_sv_f* s) { if(s){ svdObj_f* svd=(svdObj_f*)s->svd; svdFinalize_f(svd); free((void*)s); s=NULL; } return 0; } vsip_sv_f * vsip_svd_create_f(vsip_length M, vsip_length N, vsip_svd_uv Usave, vsip_svd_uv Vsave) { vsip_sv_f *s = (vsip_sv_f*) malloc(sizeof(vsip_sv_f)); if(s){ if(M < N){ s->svd = (void*) svdInit_f(N,M,Vsave,Usave); }else{ s->svd = (void*) svdInit_f(M,N,Usave,Vsave); } if(s->svd){ s->attr.Usave=Usave; s->attr.Vsave=Vsave; s->attr.m=M; s->attr.n=N; s->transpose = M < N ? 1:0; } else { vsip_svd_destroy_f(s); s = NULL; } } return s; } int vsip_svd_f(vsip_sv_f *svd, const vsip_mview_f *A, vsip_vview_f *sv) { svdObj_f *s = (svdObj_f*) svd->svd; if(svd->transpose){ s->B = *A; s->B.col_length=A->row_length; s->B.row_length=A->col_length; s->B.col_stride=A->row_stride; s->B.row_stride=A->col_stride; } else { s->B=*A; } if(svd->transpose){ svd_f(s,svd->attr.Vsave,svd->attr.Usave); } else { svd_f(s,svd->attr.Usave,svd->attr.Vsave); } vcopy_f(s->d,sv) return 0; } void vsip_svd_getattr_f(const vsip_sv_f *svd, vsip_sv_attr_f *attrib) { attrib->Usave = svd->attr.Usave; attrib->Vsave = svd->attr.Vsave; attrib->m = svd->attr.m; attrib->n = svd->attr.n; } int vsip_svdmatu_f(const vsip_sv_f *svd, vsip_scalar_vi low, vsip_scalar_vi high, const vsip_mview_f *C) { svdObj_f *s = (svdObj_f*) svd->svd; sv_attr attr = svd->attr; int retval = 0; if(attr.Usave){ if(svd->transpose){ vsip_mview_f *L = s->R; vsip_mview_f *Ls = &s->Rs; Ls->offset=L->offset + L->col_stride * low; Ls->row_stride=L->col_stride; Ls->col_stride=L->row_stride; Ls->row_length = (high-low) + 1; Ls->col_length=L->row_length; mcopy_f(Ls,C); } else { vsip_mview_f *L = s->L; vsip_mview_f *Ls = &s->Ls; Ls->offset = L->offset + L->row_stride * low; Ls->row_length = (high-low) + 1; Ls->col_length = L->col_length; Ls->row_stride = L->row_stride; Ls->col_stride = L->col_stride; mcopy_f(Ls,C); } } else { retval = 1; } return retval; } int vsip_svdmatv_f(const vsip_sv_f *svd, vsip_scalar_vi low, vsip_scalar_vi high, const vsip_mview_f *C) { svdObj_f *s = (svdObj_f*) svd->svd; sv_attr attr = svd->attr; int retval = 0; if(attr.Vsave){ if(svd->transpose){ vsip_mview_f *R = s->L; vsip_mview_f *Rs = &s->Ls; *Rs=*R; Rs->offset += Rs->row_stride * low; Rs->row_length = (high-low) + 1; mcopy_f(Rs,C); } else { vsip_mview_f *R = s->R; vsip_mview_f *Rs = &s->Rs; Rs->offset=R->offset; Rs->row_stride=R->col_stride; Rs->col_stride=R->row_stride; Rs->row_length=R->col_length; Rs->col_length=R->row_length; Rs->offset += Rs->row_stride * low; Rs->row_length = (high-low) + 1; mcopy_f(Rs,C); } } else { retval = 1; } return retval; } int vsip_svdprodu_f(const vsip_sv_f *svd, vsip_mat_op OpU, vsip_mat_side ApU, const vsip_mview_f *In) { svdObj_f* svdObj=(svdObj_f*)svd->svd; vsip_mview_f c = *In; vsip_mview_f C = *In; vsip_index i; vsip_vview_f y; vsip_mview_f U; if(svd->attr.Usave == VSIP_SVD_UVNOS) return 1; if((OpU != VSIP_MAT_NTRANS) && (OpU != VSIP_MAT_TRANS)) return 2; if( (ApU != VSIP_MAT_LSIDE) && (ApU != VSIP_MAT_RSIDE)) return 3; if(svd->transpose){ U = *(svdObj->R); U.row_stride = svdObj->R->col_stride; U.col_stride=svdObj->R->row_stride; U.row_length = svdObj->R->col_length; U.col_length=svdObj->R->row_length; } else { U = *(svdObj->L); } /* UVPART and UVFULL operate the same */ if (ApU == VSIP_MAT_LSIDE){ if(OpU == VSIP_MAT_NTRANS){ vsip_vview_f x = *(svdObj->w); x.offset=0;x.length=U.col_length;x.stride=1; c.col_length=U.col_length; for(i=0; i<c.row_length; i++){ mvprod_f(&U,col_sv_f(&C,&y,i),&x); vcopy_f(&x,col_sv_f(&c,&y,i)) } } else { /* must be TRANS */ vsip_vview_f x = *(svdObj->w); vsip_length rl=U.row_length; vsip_stride rs=U.row_stride; U.row_length = U.col_length; U.col_length = rl; U.row_stride = U.col_stride; U.col_stride = rs; x.offset=0;x.length=U.col_length;x.stride=1; c.col_length=U.col_length; for(i=0; i<c.row_length; i++){ mvprod_f(&U,col_sv_f(&C,&y,i),&x); vcopy_f(&x,col_sv_f(&c,&y,i)) } } } else { /* must be MAT_RSIDE */ if(OpU == VSIP_MAT_NTRANS){ vsip_vview_f x = *(svdObj->w); x.offset=0;x.length=U.row_length;x.stride=1; c.row_length = U.row_length; for(i=0; i<c.col_length; i++){ vmprod_f(row_sv_f(&C,&y,i),&U,&x); vcopy_f(&x,row_sv_f(&c,&y,i)) } } else { vsip_vview_f x = *(svdObj->w); vsip_length rl=U.row_length; vsip_stride rs=U.row_stride; U.row_length = U.col_length; U.col_length = rl; U.row_stride = U.col_stride; U.col_stride = rs; x.offset=0;x.length=U.row_length;x.stride=1; c.row_length=U.row_length; for(i=0; i<c.col_length; i++){ vmprod_f(row_sv_f(&C,&y,i),&U,&x); vcopy_f(&x,row_sv_f(&c,&y,i)) } } } return 0; } int vsip_svdprodv_f(const vsip_sv_f *svd, vsip_mat_op OpV, vsip_mat_side ApV,const vsip_mview_f *In) { svdObj_f* svdObj=(svdObj_f*)svd->svd; vsip_mview_f c = *In; vsip_mview_f C = *In; vsip_index i; vsip_vview_f y; vsip_mview_f V; if(svd->attr.Vsave == VSIP_SVD_UVNOS) return 1; if((OpV != VSIP_MAT_NTRANS) && (OpV != VSIP_MAT_TRANS)) return 2; if( (ApV != VSIP_MAT_LSIDE) && (ApV != VSIP_MAT_RSIDE)) return 3; if(svd->transpose){ V = *(svdObj->L); } else { V = *(svdObj->R); V.row_stride = svdObj->R->col_stride; V.col_stride=svdObj->R->row_stride; V.row_length = svdObj->R->col_length; V.col_length=svdObj->R->row_length; } /* UVPART and UVFULL operate the same */ if (ApV == VSIP_MAT_LSIDE){ if(OpV == VSIP_MAT_NTRANS){ vsip_vview_f x = *(svdObj->w); x.offset=0;x.length=V.row_length;x.stride=1; c.col_length=V.col_length; for(i=0; i<c.row_length; i++){ mvprod_f(&V,col_sv_f(&C,&y,i),&x); vcopy_f(&x,col_sv_f(&c,&y,i)) } } else { /* must be TRANS */ vsip_vview_f x = *(svdObj->w); vsip_length rl=V.row_length; vsip_stride rs=V.row_stride; V.row_length = V.col_length; V.col_length = rl; V.row_stride = V.col_stride; V.col_stride = rs; x.offset=0;x.length=V.col_length;x.stride=1; c.col_length=V.col_length; for(i=0; i<c.row_length; i++){ mvprod_f(&V,col_sv_f(&C,&y,i),&x); vcopy_f(&x,col_sv_f(&c,&y,i)) } } } else { /* must be MAT_RSIDE */ if(OpV == VSIP_MAT_NTRANS){ vsip_vview_f x = *(svdObj->w); x.offset=0;x.length=V.row_length;x.stride=1; c.row_length = V.row_length; for(i=0; i<c.col_length; i++){ vmprod_f(row_sv_f(&C,&y,i),&V,&x); vcopy_f(&x,row_sv_f(&c,&y,i)) } } else { vsip_vview_f x = *(svdObj->w); vsip_length rl=V.row_length; vsip_stride rs=V.row_stride; V.row_length = V.col_length; V.col_length = rl; V.row_stride = V.col_stride; V.col_stride = rs; x.offset=0;x.length=V.row_length;x.stride=1; c.row_length=V.row_length; for(i=0; i<c.col_length; i++){ vmprod_f(row_sv_f(&C,&y,i),&V,&x); vcopy_f(&x,row_sv_f(&c,&y,i)) } } } return 0; } /* Complex */ int vsip_csvd_destroy_f(vsip_csv_f* s) { if(s){ csvdObj_f* svd=(csvdObj_f*)s->svd; csvdFinalize_f(svd); s->svd=NULL; free((void*)s); s=NULL; } return 0; } vsip_csv_f * vsip_csvd_create_f(vsip_length M, vsip_length N, vsip_svd_uv Usave, vsip_svd_uv Vsave) { vsip_csv_f *s = (vsip_csv_f*) malloc(sizeof(vsip_csv_f)); if(s){ if(M < N){ s->svd = (void*) csvdInit_f(N,M,Vsave,Usave); }else{ s->svd = (void*)csvdInit_f(M,N,Usave,Vsave); } if(s->svd){ s->attr.Usave=Usave; s->attr.Vsave=Vsave; s->attr.m=M; s->attr.n=N; s->transpose = M < N ? 1:0; } else { vsip_svd_destroy_f(s); s=NULL; } } return s; } int vsip_csvd_f(vsip_csv_f *svd, const vsip_cmview_f *A, vsip_vview_f *sv) { csvdObj_f *s = (csvdObj_f*) svd->svd; if(svd->transpose){ s->B=*A; s->B.row_length=A->col_length; s->B.col_length=A->row_length; s->B.row_stride=A->col_stride; s->B.col_stride=A->row_stride; cmconj_f(A, A); } else { s->B=*A; } if(svd->transpose){ csvd_f(s,svd->attr.Vsave,svd->attr.Usave); } else { csvd_f(s,svd->attr.Usave,svd->attr.Vsave); } vcopy_f(s->d,sv); return 0; } void vsip_csvd_getattr_f(const vsip_csv_f *svd, vsip_csv_attr_f *attrib) { attrib->Usave = svd->attr.Usave; attrib->Vsave = svd->attr.Vsave; attrib->m = svd->attr.m; attrib->n = svd->attr.n; } int vsip_csvdmatu_f(const vsip_csv_f *svd, vsip_scalar_vi low, vsip_scalar_vi high, const vsip_cmview_f *C) { csvdObj_f *s = (csvdObj_f*) svd->svd; sv_attr attr = svd->attr; int retval = 0; if(attr.Usave){ if(svd->transpose){ vsip_cmview_f *L = s->R; vsip_cmview_f *Ls = &s->Rs; Ls->offset=L->offset + L->col_stride * low; Ls->row_stride=L->col_stride; Ls->col_stride=L->row_stride; Ls->row_length = (high-low) + 1; Ls->col_length=L->row_length; cmconj_f(Ls,C); } else { vsip_cmview_f *L = s->L; vsip_cmview_f *Ls = &s->Ls; Ls->offset = L->offset + L->row_stride * low; Ls->row_length = (high-low) + 1; Ls->row_stride = L->row_stride; Ls->col_length = L->col_length; Ls->col_stride = L->col_stride; cmcopy_f(Ls,C); } } else { retval = 1; } return retval; } int vsip_csvdmatv_f(const vsip_csv_f *svd, vsip_scalar_vi low, vsip_scalar_vi high, const vsip_cmview_f *C) { csvdObj_f *s = (csvdObj_f*) svd->svd; sv_attr attr = svd->attr; int retval = 0; if(attr.Vsave){ if(svd->transpose){ vsip_cmview_f *R = s->L; vsip_cmview_f *Rs = &s->Ls; *Rs=*R; Rs->offset += Rs->row_stride * low; Rs->row_length = (high-low) + 1; cmcopy_f(Rs,C); } else { vsip_cmview_f *R = s->R; vsip_cmview_f *Rs = &s->Rs; Rs->offset=R->offset; Rs->row_stride=R->col_stride; Rs->col_stride=R->row_stride; Rs->row_length=R->col_length; Rs->col_length=R->row_length; Rs->offset += Rs->row_stride * low; Rs->row_length = (high-low) + 1; cmconj_f(Rs,C); } } else { retval = 1; } return retval; } int vsip_csvdprodu_f(const vsip_csv_f *svd, vsip_mat_op OpU, vsip_mat_side ApU, const vsip_cmview_f *In) { csvdObj_f* svdObj=(csvdObj_f*)svd->svd; vsip_cmview_f c = *In; vsip_cmview_f C = *In; vsip_index i; vsip_cvview_f y; vsip_cmview_f U; if(svd->attr.Usave == VSIP_SVD_UVNOS) return 1; if((OpU != VSIP_MAT_NTRANS) && (OpU != VSIP_MAT_HERM)) return 2; if( (ApU != VSIP_MAT_LSIDE) && (ApU != VSIP_MAT_RSIDE)) return 3; if(svd->transpose){ U = *(svdObj->R); U.row_stride = svdObj->R->col_stride; U.col_stride=svdObj->R->row_stride; U.row_length = svdObj->R->col_length; U.col_length=svdObj->R->row_length; } else { U = *(svdObj->L); } /* UVPART and UVFULL operate the same */ if (ApU == VSIP_MAT_LSIDE){ if(OpU == VSIP_MAT_NTRANS){ vsip_cvview_f *x = svdObj->w; x->offset=0;x->length=U.col_length;x->stride=1; c.col_length=U.col_length; for(i=0; i<c.row_length; i++){ cmvprod_f(&U,ccol_sv_f(&C,&y,i),x); cvcopy_f(x,ccol_sv_f(&c,&y,i)) } if(svd->transpose) cmconj_f(&c,&c); } else { /* must be HERM */ vsip_cvview_f *x = svdObj->w; vsip_length rl=U.row_length; vsip_stride rs=U.row_stride; U.row_length = U.col_length; U.col_length = rl; U.row_stride = U.col_stride; U.col_stride = rs; x->offset=0;x->length=U.col_length;x->stride=1; c.col_length=U.col_length; if(svd->transpose){ U = *(svdObj->R); for(i=0; i<c.row_length; i++){ cmvprod_f(&U,ccol_sv_f(&C,&y,i),x) cvcopy_f(x,ccol_sv_f(&c,&y,i)) } } else { for(i=0; i<c.row_length; i++){ cmvjprod_f(&U,ccol_sv_f(&C,&y,i),x) cvcopy_f(x,ccol_sv_f(&c,&y,i)) } } } } else { /* must be MAT_RSIDE */ if(OpU == VSIP_MAT_NTRANS){ vsip_cvview_f *x = svdObj->w; x->offset=0;x->length=U.row_length;x->stride=1; c.row_length = U.row_length; for(i=0; i<c.col_length; i++){ cvmprod_f(crow_sv_f(&C,&y,i),&U,x); cvcopy_f(x,crow_sv_f(&c,&y,i)) } if(svd->transpose) cmconj_f(&c,&c); } else {/* must be herm */ vsip_cvview_f *x = svdObj->w; vsip_length rl=U.row_length; vsip_stride rs=U.row_stride; U.row_length = U.col_length; U.col_length = rl; U.row_stride = U.col_stride; U.col_stride = rs; x->offset=0;x->length=U.row_length;x->stride=1; c.row_length=U.row_length; if(svd->transpose){ U = *(svdObj->R); for(i=0; i<c.row_length; i++){ cvmprod_f(crow_sv_f(&C,&y,i),&U,x) cvcopy_f(x,crow_sv_f(&c,&y,i)) } } else { for(i=0; i<c.col_length; i++){ cvmprodj_f(crow_sv_f(&C,&y,i),&U,x); cvcopy_f(x,crow_sv_f(&c,&y,i)) } } } } return 0; } int vsip_csvdprodv_f(const vsip_csv_f *svd, vsip_mat_op OpV, vsip_mat_side ApV,const vsip_cmview_f *In) { csvdObj_f* svdObj=(csvdObj_f*)svd->svd; vsip_cmview_f c = *In; vsip_cmview_f C = *In; vsip_index i; vsip_cvview_f y; vsip_cmview_f V; if(svd->attr.Vsave == VSIP_SVD_UVNOS) return 1; if((OpV != VSIP_MAT_NTRANS) && (OpV != VSIP_MAT_HERM)) return 2; if( (ApV != VSIP_MAT_LSIDE) && (ApV != VSIP_MAT_RSIDE)) return 3; if(svd->transpose){ V = *(svdObj->L); } else { V = *(svdObj->R); V.row_stride = svdObj->R->col_stride; V.col_stride=svdObj->R->row_stride; V.row_length = svdObj->R->col_length; V.col_length=svdObj->R->row_length; } /* UVPART and UVFULL operate the same */ if (ApV == VSIP_MAT_LSIDE){ if(OpV == VSIP_MAT_NTRANS){ vsip_cvview_f x = *(svdObj->w); x.offset=0;x.length=V.row_length;x.stride=1; c.col_length=V.col_length; for(i=0; i<c.row_length; i++){ if(svd->transpose) cmvprod_f(&V,ccol_sv_f(&C,&y,i),&x) else cmvjprod_f(&V,ccol_sv_f(&C,&y,i),&x) cvcopy_f(&x,ccol_sv_f(&c,&y,i)) } } else { /* must be HERM */ vsip_cvview_f x = *(svdObj->w); if(!svd->transpose) V=*(svdObj->R); else { vsip_length rl=V.row_length; vsip_stride rs=V.row_stride; V.row_length = V.col_length; V.col_length = rl; V.row_stride = V.col_stride; V.col_stride = rs; } x.offset=0;x.length=V.col_length;x.stride=1; c.col_length=V.col_length; for(i=0; i<c.row_length; i++){ if(!svd->transpose) cmvprod_f(&V,ccol_sv_f(&C,&y,i),&x) else cmvjprod_f(&V,ccol_sv_f(&C,&y,i),&x) cvcopy_f(&x,ccol_sv_f(&c,&y,i)) } } } else { /* must be MAT_RSIDE */ if(OpV == VSIP_MAT_NTRANS){ vsip_cvview_f x = *(svdObj->w); x.offset=0;x.length=V.row_length;x.stride=1; c.row_length = V.row_length; for(i=0; i<c.col_length; i++){ if(svd->transpose) cvmprod_f(crow_sv_f(&C,&y,i),&V,&x) else cvmprodj_f(crow_sv_f(&C,&y,i),&V,&x) cvcopy_f(&x,crow_sv_f(&c,&y,i)) } } else { /* must be HERM */ vsip_cvview_f x = *(svdObj->w); if(!svd->transpose) V=*(svdObj->R); else { vsip_length rl=V.row_length; vsip_stride rs=V.row_stride; V.row_length = V.col_length; V.col_length = rl; V.row_stride = V.col_stride; V.col_stride = rs; } x.offset=0;x.length=V.row_length;x.stride=1; c.row_length=V.row_length; for(i=0; i<c.col_length; i++){ if(!svd->transpose) cvmprod_f(crow_sv_f(&C,&y,i),&V,&x) else cvmprodj_f(crow_sv_f(&C,&y,i),&V,&x) cvcopy_f(&x,crow_sv_f(&c,&y,i)) } } } return 0; } <file_sep>import Foundation import vsip func oddNumber(_ n: Int) -> Bool { return (n % 2) == 1 } public class KW { public let Nfreq: Int /* Nts/2 + 1 */ public let Navg:Int /* Scale factor for number of averages */ public var cm_freq: OpaquePointer? /* (Nsens, Nfreq) col maj vsip_cmview_d */ public var rm_freq: OpaquePointer? /* (Nsens, Nts) rwo maj vsip_mview_d */ public var m_gram: OpaquePointer? /* (Nsens, Nfreq) col maj */ public var rcfftm: OpaquePointer? /* by row Nsens by Nts */ var ccfftm: OpaquePointer? /* by col Nsens by Nfreq */ public var ts_taper: OpaquePointer? /* of length Nts */ public var array_taper: OpaquePointer? /* of length Nsens */ public init(param: Param){ if oddNumber(param.Nts!){ preconditionFailure("Data Length must be even") } Navg = param.Navg! Nfreq = param.Nts!/2 + 1 if let cm_freq = vsip_cmcreate_d(vsip_length(param.Nsens!),vsip_length(Nfreq),VSIP_COL,VSIP_MEM_NONE) { self.cm_freq = cm_freq if let rm_freq = vsip_mrealview_d(self.cm_freq){ self.rm_freq = rm_freq } } if let m_gram = vsip_mcreate_d(vsip_length(param.Nsens!), vsip_length(Nfreq), VSIP_COL,VSIP_MEM_NONE){ self.m_gram = m_gram } if let rcfftm = vsip_rcfftmop_create_d(vsip_length(param.Nsens!),vsip_length(param.Nts!),1,VSIP_ROW,0,vsip_alg_hint(rawValue: 0)) { self.rcfftm = rcfftm } if let ccfftm = vsip_ccfftmip_create_d(vsip_length(param.Nsens!),vsip_length(Nfreq),1.0,VSIP_FFT_FWD,VSIP_COL,0,vsip_alg_hint(rawValue: 0)){ self.ccfftm = ccfftm } if let ts_taper = vsip_vcreate_hanning_d(vsip_length(param.Nts!),VSIP_MEM_NONE){ self.ts_taper = ts_taper } if let array_taper = vsip_vcreate_hanning_d(vsip_length(param.Nsens!),VSIP_MEM_NONE) { self.array_taper = array_taper } } deinit { vsip_malldestroy_d(m_gram); vsip_fftm_destroy_d(rcfftm); vsip_fftm_destroy_d(ccfftm); vsip_valldestroy_d(ts_taper); vsip_valldestroy_d(array_taper); vsip_mdestroy_d(rm_freq); vsip_cmalldestroy_d(cm_freq); } public func komega(m_data: OpaquePointer){ /* Data tapers for time and space */ vsip_vmmul_d(self.ts_taper,m_data,VSIP_ROW,m_data) vsip_vmmul_d(self.array_taper,m_data,VSIP_COL,m_data) /* FFT for time and space */ vsip_rcfftmop_d(rcfftm,m_data,cm_freq); vsip_ccfftmip_d(ccfftm,cm_freq) /* power estimate */ /* to save memory place estimate in real part of spectral matrix */ vsip_mcmagsq_d(cm_freq,rm_freq) /* scaling for average */ vsip_smmul_d(1.0/Double(Navg),rm_freq,rm_freq) /* add in new values to gram estimate */ vsip_madd_d(rm_freq,m_gram,m_gram) } public func zero(){ vsip_mfill_d(0.0,m_gram) } public func instance() -> OpaquePointer { return self.m_gram! } } <file_sep>import Foundation import SJVsip public func checkSvd(_ svd:Svd, against M: Matrix) -> Bool { let chk = M.empty chk.fill(Scalar(0.0)) let tmp = chk.newCopy let U = svd.matU! let Vt = svd.matV!.transview let s = svd.vecS copy(from: s, to: chk.diagview) prod(chk, times: Vt, resultsIn: tmp) prod(U, times: tmp, resultsIn:chk) sub(chk, subtract: M, resultsIn: chk) let aNumber = sumsqval(chk).reald/sumsqval(M).reald print(aNumber) return aNumber < 1E-10 } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: crvdiv_d.h,v 2.0 2003/02/22 15:23:22 judd Exp $ */ #include"VU_vprintm_d.include" #include"VU_cvprintm_d.include" static void crvdiv_d(void){ printf("\n********\nTEST crvdiv_d\n"); { vsip_vview_d *b = vsip_vcreate_d(7,VSIP_MEM_NONE); vsip_cvview_d *a = vsip_cvcreate_d(7,VSIP_MEM_NONE); vsip_cvview_d *c = vsip_cvcreate_d(7,VSIP_MEM_NONE); vsip_vview_d *c_i = vsip_vimagview_d(c); vsip_cvview_d *chk = vsip_cvcreate_d(7,VSIP_MEM_NONE); vsip_vview_d *chk_i = vsip_vimagview_d(chk); vsip_scalar_d data[] = {1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7}; vsip_scalar_d data_r[] ={.1, .2, .3, .4, .5, .6, .7}; vsip_scalar_d data_i[] ={7,6,5,4,3,2,1}; vsip_scalar_d data_ans[] ={ 0.1000, 7.0000, 0.1818, 5.4545, 0.2500, 4.1667, 0.3077, 3.0769, 0.3571, 2.1429, 0.4000 , 1.3333, 0.4375 , 0.6250}; vsip_block_d *block = vsip_blockbind_d(data,7,VSIP_MEM_NONE); vsip_cblock_d *cblock = vsip_cblockbind_d(data_r,data_i,7,VSIP_MEM_NONE); vsip_cblock_d *cblock_ans = vsip_cblockbind_d(data_ans, (vsip_scalar_d*)NULL,7,VSIP_MEM_NONE); vsip_vview_d *u_b = vsip_vbind_d(block,0,1,7); vsip_cvview_d *u_a = vsip_cvbind_d(cblock,0,1,7); vsip_cvview_d *u_ans = vsip_cvbind_d(cblock_ans,0,1,7); vsip_blockadmit_d(block,VSIP_TRUE); vsip_cblockadmit_d(cblock,VSIP_TRUE); vsip_cblockadmit_d(cblock_ans,VSIP_TRUE); vsip_vcopy_d_d(u_b,b); vsip_cvcopy_d_d(u_a,a); printf("call vsip_crvdiv_d(a,b,c)\n"); printf("a =\n");VU_cvprintm_d("8.6",a); printf("b =\n");VU_vprintm_d("8.6",b); printf("test normal out of place\n"); vsip_crvdiv_d(a,b,c); printf("c =\n");VU_cvprintm_d("8.6",c); printf("right answer =\n");VU_cvprintm_d("8.4",u_ans); vsip_cvsub_d(u_ans,c,chk); vsip_cvmag_d(chk,chk_i); vsip_vclip_d(chk_i,.0002,.0002,0,1,chk_i); if(vsip_vsumval_d(chk_i) > .5) printf("error\n"); else printf("correct\n"); printf("test a,c inplace\n"); vsip_crvdiv_d(a,b,a); vsip_cvsub_d(u_ans,a,chk); vsip_cvmag_d(chk,chk_i); vsip_vclip_d(chk_i,.0002,.0002,0,1,chk_i); if(vsip_vsumval_d(chk_i) > .5) printf("error\n"); else printf("correct\n"); printf("test in place b= imaginary(c)\n"); vsip_vcopy_d_d(u_b,c_i); vsip_cvcopy_d_d(u_a,a); vsip_crvdiv_d(a,c_i,c); vsip_cvsub_d(u_ans,c,chk); vsip_cvmag_d(chk,chk_i); vsip_vclip_d(chk_i,.0002,.0002,0,1,chk_i); if(vsip_vsumval_d(chk_i) > .5) printf("error\n"); else printf("correct\n"); vsip_valldestroy_d(b); vsip_cvalldestroy_d(a); vsip_vdestroy_d(c_i); vsip_cvalldestroy_d(c); vsip_vdestroy_d(chk_i); vsip_cvalldestroy_d(chk); vsip_valldestroy_d(u_b); vsip_cvalldestroy_d(u_a); vsip_cvalldestroy_d(u_ans); } return; } <file_sep>/* Created By RJudd August 3, 2002 */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_nuV.h,v 2.0 2003/02/22 15:18:33 judd Exp $ */ #ifndef VI_NUV__H #define VI_NUV__H #include"vsip.h" /* nuV*/ /* calculate number of factors of 2,3,4,5,7,8,n in N */ /* so that N = 2^n2 * 4^n4 * 8^n8 * 3^n3 * 5^n5 *7^n7 * n */ static vsip_length VI_nuV(vsip_length N, vsip_scalar_vi *pn, vsip_scalar_vi *p0, vsip_scalar_vi *pF) { vsip_scalar_vi n2=0,n3=0,n4=0,n5=0,n8=0,n7=0; vsip_scalar_vi k = 0; vsip_scalar_vi n = N; while((n % 3) == 0){ n /= 3; n3++; } if(n3 != 0){ p0[k]=3; if(n != 1) { pF[k] = n; pn[k] = n3 + 1; }else{ pF[k] = 3; pn[k] = n3; } k++; } while((n % 5) == 0){ n /= 5; n5++; } if(n5 != 0){ p0[k] = 5; if(n != 1) { pF[k] = n; pn[k] = n5 + 1; }else{ pF[k] = 5; pn[k] = n5; } k++; } while((n % 7) == 0){ n /= 7; n7++; } if(n7 != 0){ p0[k] = 7; if(n != 1) { pF[k] = n; pn[k] = n7 + 1; }else{ pF[k] = 7; pn[k] = n7; } k++; } while((n % 8) == 0) { n /= 8; n8++; } if(n8 != 0){ p0[k] = 8; if(n != 1) { pF[k] = n; pn[k] = n8 + 1; }else{ pF[k] = 8; pn[k] = n8; } k++; } while((n % 4) == 0) { n /= 4; n4++; } if(n4 != 0){ p0[k] = 4; if(n != 1) { pF[k] = n; pn[k] = n4 + 1; }else{ pF[k] = 4; pn[k] = n4; } k++; } while((n % 2) == 0) { n /= 2; n2++; } if(n2 != 0){ p0[k] = 2; if(n != 1) { pF[k] = n; pn[k] = n2 + 1; }else{ pF[k] = 2; pn[k] = n2; } k++; } if((n != 1) && (k == 0)){ p0[k] = 1; pF[k] = n; pn[k] = 1; k++; } return (vsip_length)k; } #endif <file_sep>/* Created RJudd */ /********************************************************************** // TASP VSIPL Documentation and Code includes no warranty, / // express or implied, including the warranties of merchantability / // and fitness for a particular purpose. No person or organization / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vinterp_nearest_d.c,v 2.1 2008/09/14 20:48:40 judd Exp $ */ #include"vsip.h" #include"vsip_vviewattributes_d.h" #define F2(x1,x2,y1,y2,x,y) { \ vsip_scalar_d dif1 = x - x1;\ vsip_scalar_d dif2 = x2 - x;\ if(dif1 > dif2) \ y = y2;\ else \ y = y1; \ } void vsip_vinterp_nearest_d( const vsip_vview_d *x0, const vsip_vview_d *y0, const vsip_vview_d *x, const vsip_vview_d *y){ vsip_length N0 = x0->length; vsip_length N = x->length; vsip_stride x0_str = x0->stride * x0->block->rstride, y0_str = y0->stride * y0->block->rstride, x_str = x->stride * x->block->rstride, y_str = y->stride * y->block->rstride; vsip_scalar_d *x0_ptr = x0->block->array + x0->offset * x0->block->rstride, *y0_ptr = y0->block->array + y0->offset * y0->block->rstride, *x_ptr = x->block->array + x->offset * x->block->rstride, *y_ptr = y->block->array + y->offset * y->block->rstride; vsip_index i=0,j=0; vsip_scalar_d sx1,sx2,sy1,sy2,sx; while((j < N) && (i < N0-1)){ sx1 = x0_ptr[i * x0_str]; sx2 = x0_ptr[(i+1)*x0_str]; sy1 = y0_ptr[i * y0_str]; sy2 = y0_ptr[(i+1) * y0_str]; sx = x_ptr[j * x_str]; if(sx < sx2) { vsip_scalar_d a; F2(sx1,sx2,sy1,sy2,sx,a); y_ptr[j * y_str] = a; j++; } else i++; } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: marg_f.h,v 2.0 2003/02/22 15:23:24 judd Exp $ */ #include"VU_mprintm_f.include" #include"VU_cmprintm_f.include" static void marg_f(void){ printf("\n*****\nTEST marg_f\n"); { vsip_cmview_f *a = vsip_cmcreate_f(22,22,VSIP_COL,VSIP_MEM_NONE); vsip_cvview_f *a_v = vsip_cvbind_f(vsip_cmgetblock_f(a),0,1,22*22); vsip_cmview_f *b = vsip_cmsubview_f(a,0,0,3,3); vsip_mview_f *chk = vsip_mcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_vview_f *a_r, *a_i; vsip_mview_f *arg = vsip_mcreate_f(3,3,VSIP_COL,VSIP_MEM_NONE); vsip_scalar_f data[] = {1.5708, 0.5880, -.1651, 1.3258, .2450, -.2783, .9828, 0.0, -.3588}; vsip_block_f *block = vsip_blockbind_f(data,9,VSIP_MEM_NONE); vsip_mview_f *ans = vsip_mbind_f(block,0,3,3,1,3); vsip_blockadmit_f(block,VSIP_TRUE); vsip_cmputrowstride_f(b,6); vsip_cmputcolstride_f(b,2); a_r = vsip_vrealview_f(a_v); a_i = vsip_vimagview_f(a_v); vsip_vramp_f(0,.1,a_r); vsip_vramp_f(1,-.1,a_i); printf("call vsip_marg_f(b,arg)\n"); printf("input matrix b\n"); VU_cmprintm_f("8.6",b); vsip_marg_f(b,arg); printf("output arg\n"); VU_mprintm_f("8.6",arg); printf("answer to 4 digits\n"); VU_mprintm_f("8.4",ans); vsip_msub_f(arg,ans,chk); vsip_mmag_f(chk,chk); if(vsip_msumval_f(chk) > .0009) printf("error\n"); else printf("correct\n"); vsip_cmdestroy_f(b); vsip_vdestroy_f(a_i); vsip_vdestroy_f(a_r); vsip_cvdestroy_f(a_v); vsip_cmalldestroy_f(a); vsip_malldestroy_f(arg); vsip_malldestroy_f(ans); vsip_malldestroy_f(chk); } return; } <file_sep>from vsip import * def __isSizeCompatible(a,b): if 'mview' in a.type and 'mview' in b.type: if (a.rowlength == b.rowlength) and (a.collength == b.collength): return True elif 'vview' in a.type and 'vview' in b.type: if a.length == b.length: return True else: return False # vsip_dscopy_p_p def copy(a,b): f={'cmview_dcmview_d':vsip_cmcopy_d_d, 'cmview_dcmview_f':vsip_cmcopy_d_f, 'cmview_fcmview_d':vsip_cmcopy_f_d, 'cmview_fcmview_f':vsip_cmcopy_f_f, 'cvview_dcvview_d':vsip_cvcopy_d_d, 'cvview_dcvview_f':vsip_cvcopy_d_f, 'cvview_fcvview_d':vsip_cvcopy_f_d, 'cvview_fcvview_f':vsip_cvcopy_f_f, 'mview_blmview_bl':vsip_mcopy_bl_bl, 'mview_blmview_d':vsip_mcopy_bl_d, 'mview_blmview_f':vsip_mcopy_bl_f, 'mview_dmview_bl':vsip_mcopy_d_bl, 'mview_dmview_d':vsip_mcopy_d_d, 'mview_dmview_f':vsip_mcopy_d_f, 'mview_dmview_i':vsip_mcopy_d_i, 'mview_dmview_uc':vsip_mcopy_d_uc, 'mview_fmview_bl':vsip_mcopy_f_bl, 'mview_fmview_d':vsip_mcopy_f_d, 'mview_fmview_f':vsip_mcopy_f_f, 'mview_fmview_i':vsip_mcopy_f_i, 'mview_fmview_uc':vsip_mcopy_f_uc, 'mview_imview_f':vsip_mcopy_i_f, 'mview_simview_f':vsip_mcopy_si_f, 'mview_imview_i':vsip_mcopy_i_i, 'vview_blvview_bl':vsip_vcopy_bl_bl, 'vview_blvview_d':vsip_vcopy_bl_d, 'vview_blvview_f':vsip_vcopy_bl_f, 'vview_dvview_bl':vsip_vcopy_d_bl, 'vview_dvview_d':vsip_vcopy_d_d, 'vview_dvview_f':vsip_vcopy_d_f, 'vview_dvview_i':vsip_vcopy_d_i, 'vview_dvview_si':vsip_vcopy_d_si, 'vview_dvview_uc':vsip_vcopy_d_uc, 'vview_dvview_vi':vsip_vcopy_d_vi, 'vview_fvview_bl':vsip_vcopy_f_bl, 'vview_fvview_d':vsip_vcopy_f_d, 'vview_fvview_f':vsip_vcopy_f_f, 'vview_fvview_i':vsip_vcopy_f_i, 'vview_fvview_si':vsip_vcopy_f_si, 'vview_fvview_uc':vsip_vcopy_f_uc, 'vview_fvview_vi':vsip_vcopy_f_vi, 'vview_ivview_d':vsip_vcopy_i_d, 'vview_ivview_f':vsip_vcopy_i_f, 'vview_ivview_i':vsip_vcopy_i_i, 'vview_ivview_uc':vsip_vcopy_i_uc, 'vview_ivview_vi':vsip_vcopy_i_vi, 'vview_mivview_mi':vsip_vcopy_mi_mi, 'vview_sivview_d':vsip_vcopy_si_d, 'vview_sivview_f':vsip_vcopy_si_f, 'vview_sivview_si':vsip_vcopy_si_si, 'vview_vivview_i':vsip_vcopy_vi_i, 'vview_vivview_vi':vsip_vcopy_vi_vi, 'vview_vivview_f':vsip_vcopy_vi_f, 'vview_vivview_d':vsip_vcopy_vi_d} assert 'pyJvsip' in repr(a),\ 'Argument one must be a pyJvsip view object in copy' assert 'pyJvsip' in repr(b),\ 'Argument two must be a pyJvsip view object in copy' assert __isSizeCompatible(a,b),'Input and output for copy must be the same size' t = a.type+b.type assert t in f,'Type <:'+t+':> not recognizedfor copy' f[t](a.vsip,b.vsip) return b # copy to and from user space don't seem to make sense for pyJvsip # see the view list method and jvsipNumpyUtils module for comparable routines # vsip_dscopyto_user_p vsip_dscopyfrom_user_p # fill and ramp are only supported as methods on views #vsip_dsfill_p vsip_vramp_p <file_sep>// // Scalar.swift // SJVsip // // Created by <NAME> on 11/4/17. // Copyright © 2017 JVSIP. All rights reserved. // import Foundation import vsip public struct Scalar { public enum Types: String{ case f case d case cf case cd case si case i case li case uc case vi case mi case bl } var value: (Types?, NSNumber?, NSNumber?) public init(_ type: Types,_ valueOne: NSNumber?,_ valueTwo: NSNumber?){ value.0 = type value.1 = valueOne value.2 = valueTwo } public init(_ value: Double){ self.value.0 = .d self.value.1 = NSNumber(value: value) self.value.2 = nil } public init(_ value: Float){ self.value.0 = .f self.value.1 = NSNumber(value: value) self.value.2 = nil } public init(_ value: Int){ self.value.0 = .i self.value.1 = NSNumber(value: value) self.value.2 = nil } public init(_ value: vsip_cscalar_d){ self.value.0 = .cd self.value.1 = NSNumber(value: value.r) self.value.2 = NSNumber(value: value.i) } public init(_ value: vsip_cscalar_f){ self.value.0 = .cf self.value.1 = NSNumber(value: value.r) self.value.2 = NSNumber(value: value.i) } public init(_ value: vsip_scalar_mi){ self.value.0 = .mi self.value.1 = NSNumber(value: value.r) self.value.2 = NSNumber(value: value.c) } public init(_ value: vsip_scalar_i){ self.value.0 = .i self.value.1 = NSNumber(value: value) self.value.2 = nil } public init(_ value: vsip_scalar_vi){ self.value.0 = .vi self.value.1 = NSNumber(value: value) self.value.2 = nil } public init(_ value: vsip_scalar_si){ self.value.0 = .si self.value.1 = NSNumber(value: value) self.value.2 = nil } public init(_ value: vsip_scalar_uc){ self.value.0 = .uc self.value.1 = NSNumber(value: value) self.value.2 = nil } public var type: Types { return value.0! } public var realf: Float{ return Float((value.1?.floatValue)!) } public var reald: Double{ return Double((value.1?.doubleValue)!) } public var imagf: Float{ if let i = value.2 { return i.floatValue } else { return Float(0.0) } } public var imagd: Double{ if let i = value.2 { return i.doubleValue } else { return Double(0.0) } } public var int: Int{ return Int((value.1?.intValue)!) } public var row: Int{ return Int((value.1?.intValue)!) } public var col: Int{ return Int((value.2?.intValue)!) } public var cmplxf: Scalar{ var c = vsip_cmplx_f(vsip_scalar_f(0.0),(0.0)) if let r = value.1 { c.r = vsip_scalar_f(r.floatValue) } if let i = value.2 { c.i = vsip_scalar_f(i.floatValue) } return Scalar(c) } public var cmplxd: Scalar{ var c = vsip_cmplx_d(vsip_scalar_d(0.0),vsip_scalar_d(0.0)) if let r = value.1 { c.r = vsip_scalar_d(r.doubleValue) } if let i = value.2 { c.i = vsip_scalar_d(i.doubleValue) } return Scalar(c) } public var vsip_f: vsip_scalar_f { return vsip_scalar_f((value.1?.floatValue)!) } public var vsip_d: vsip_scalar_d { return vsip_scalar_d((value.1?.doubleValue)!) } public var vsip_cf: vsip_cscalar_f { var c = vsip_cmplx_f(vsip_scalar_f(0.0),vsip_scalar_f(0.0)) if let r = value.1 { c.r = vsip_scalar_f(r.floatValue) } if let i = value.2 { c.i = vsip_scalar_f(i.floatValue) } return c } public var vsip_cd: vsip_cscalar_d { var c = vsip_cmplx_d(vsip_scalar_d(0.0),vsip_scalar_d(0.0)) if let r = value.1 { c.r = vsip_scalar_d(r.doubleValue) } if let i = value.2 { c.i = vsip_scalar_d(i.doubleValue) } return c } public var vsip_i: vsip_scalar_i{ return vsip_scalar_i((value.1?.int32Value)!) } public var vsip_li: vsip_scalar_li{ return vsip_scalar_li((value.1?.intValue)!) } public var vsip_vi: vsip_scalar_vi{ return vsip_scalar_vi((value.1?.uintValue)!) } public var vsip_si: vsip_scalar_si{ return vsip_scalar_si((value.1?.int16Value)!) } public var vsip_uc: vsip_scalar_uc{ return vsip_scalar_uc((value.1?.uint8Value)!) } public var vsip_mi: vsip_scalar_mi{ var i = vsip_matindex(vsip_scalar_vi(0), vsip_scalar_vi(0)) if let row = value.1 { i.r = vsip_scalar_vi(row.uintValue) } if let col = value.2 { i.c = vsip_scalar_vi(col.uintValue) } return i } public static func + (left: Scalar, right: Scalar) -> Scalar { switch (left.type, right.type) { case (.f, .f): return Scalar( left.realf + right.realf) case (.d, .d): return Scalar( left.reald + right.reald) case (.cf, .f): return Scalar(vsip_cmplx_f(left.realf + right.realf, left.imagf)) case (.cd, .d): return Scalar(vsip_cmplx_d(left.reald + right.reald, left.imagd)) case (.f, .cf): return Scalar(vsip_cmplx_f(left.realf + right.realf, right.imagf)) case (.d, .cd): return Scalar(vsip_cmplx_d(left.reald + right.reald, right.imagd)) case(.cf, .cf): return Scalar(vsip_cmplx_f(left.realf + right.realf, left.imagf + right.imagf)) case(.cd, .cd): return Scalar(vsip_cmplx_d(left.reald + right.reald, left.imagd + right.imagd)) default: preconditionFailure("Vsip Scalar types (\(left.type), \(right.type)) not supported for +") } } public static func * (left: Scalar, right: Scalar) -> Scalar { switch (left.type, right.type) { case (.f, .f): return Scalar( left.realf * right.realf) case (.d, .d): return Scalar( left.reald * right.reald) case (.cf, .f): return Scalar(vsip_rcmul_f(right.vsip_f, left.vsip_cf)) case (.cd, .d): return Scalar(vsip_rcmul_d(right.vsip_d, left.vsip_cd)) case (.f, .cf): return Scalar(vsip_rcmul_f(left.vsip_f, right.vsip_cf)) case (.d, .cd): return Scalar(vsip_rcmul_d(left.vsip_d, right.vsip_cd)) case(.cf, .cf): return Scalar(vsip_cmul_f(left.vsip_cf, right.vsip_cf)) case(.cd, .cd): return Scalar(vsip_cmul_d(left.vsip_cd, right.vsip_cd)) default: preconditionFailure("Vsip Scalar types (\(left.type), \(right.type)) not supported for *") } } public static func - (left: Scalar, right: Scalar) -> Scalar { switch (left.type, right.type) { case (.f, .f): return Scalar( left.realf - right.realf) case (.d, .d): return Scalar( left.reald - right.reald) case (.cf, .f): return Scalar(vsip_cmplx_f(left.realf - right.realf, left.imagf)) case (.cd, .d): return Scalar(vsip_cmplx_d(left.reald - right.reald, left.imagd)) case (.f, .cf): return Scalar(vsip_cmplx_f(left.realf - right.realf, -right.imagf)) case (.d, .cd): return Scalar(vsip_cmplx_d(left.reald - right.reald, -right.imagd)) case(.cf, .cf): return Scalar(vsip_cmplx_f(left.realf - right.realf, left.imagf - right.imagf)) case(.cd, .cd): return Scalar(vsip_cmplx_d(left.reald - right.reald, left.imagd - right.imagd)) case(.f, .i): return Scalar( left.realf - right.realf) case(.i, .f): return Scalar( left.realf - right.realf) case(.d, .i): return Scalar( left.reald - right.reald) case(.i, .d): return Scalar( left.reald - right.reald) default: preconditionFailure("Vsip Scalar types (\(left.type), \(right.type)) not supported for - ") } } public var sqrt: Scalar { switch self.type { case .f: return Scalar(sqrtf(self.realf)) case .d: let x = Foundation.sqrt(self.reald) return Scalar(x) case .cf: return Scalar(vsip_csqrt_f(self.vsip_cf)) case .cd: return Scalar(vsip_csqrt_d(self.vsip_cd)) default: preconditionFailure("sqrt not supported for type \(self.type)") } } public func string(format fmt: String) -> String { return scalarString(formatFmt(fmt), value:self) } } <file_sep># Created RJudd # Converted from chold tests in c_VSIP_testing Directory # Note that blockbinds are not functional at this time in python so they have been removed # This code includes # no warranty, express or implied, including the warranties # of merchantability and fitness for a particular purpose. # No person or entity # assumes any legal liability or responsibility for the accuracy, # completeness, or usefulness of any information, apparatus, # product, or process disclosed, or represents that its use would # not infringe privately owned rights import vsiputils as vsip import vsipUser as VU from vsip import vsip_init, vsip_finalize def chol(p): print("********\nTEST chol"+p+"\n") ablock = vsip.create('block'+p,(200,vsip.VSIP_MEM_NONE)) R = vsip.create('mview'+p,(4,4,vsip.VSIP_ROW,vsip.VSIP_MEM_NONE)) RH = vsip.create('mview'+p,(4,4,vsip.VSIP_ROW,vsip.VSIP_MEM_NONE)) A = vsip.bind(ablock,(99,-11,4,-2,4)) B = vsip.bind(ablock,(100,20,4,2,3)) ans = vsip.create('mview'+p,(4,3,vsip.VSIP_ROW,vsip.VSIP_MEM_NONE)) chol = vsip.create('chol'+p,(vsip.VSIP_TR_UPP,4)) data_R = [ [1.0, -2.0, 3.0, 1.0], [0.0, 2.0, 4.0, -1.0], [0.0, 0.0, 4.0, 3.0], [0.0, 0.0, 0.0, 6.0] ] data_Br = [ [ 1.0, 2.0, 3.0], [ 0.0, 1.0, 2.0], [ 3.0, 0.0, 1.0], [ 3.0, 4.0, 5.0]] data_ans = [[ 4.6250, 13.9062, 21.0000], [ 1.3333, 4.1667, 6.3333], [ -0.3750, -1.3438, -2.0000], [ 0.1667, 0.4583, 0.6667]] for i in range(4): for j in range(4): vsip.put(R,(i,j),data_R[i][j]) for i in range(4): for j in range(3): vsip.put(B,(i,j),data_Br[i][j]) vsip.put(ans,(i,j),data_ans[i][j]) vsip.trans(R,RH) vsip.prod(RH,R,A) print("R = \n");VU.mprint(R,"%4.2f") print("RH = \n");VU.mprint(RH,"%4.2f") print("A = R * RH\n");VU.mprint(A,"%4.2f") print("B \n");VU.mprint(B,"%4.2f") vsip.chold(chol,A) vsip.cholsol(chol,B) print("Solve using cholesky AX = B\n X = \n");VU.mprint(B,"%4.2f") vsip.destroy(chol) print("right answer \n ans = \n");VU.mprint(ans,"%4.2f") vsip.sub(ans,B,B) chk = vsip.sumsqval(B) if chk > .001: print("error\n") else: print("correct\n") lu = vsip.create('lu'+p,4) Bans = vsip.create('mview'+p,(4,3,vsip.VSIP_ROW,vsip.VSIP_MEM_NONE)) vsip.prod(RH,R,A) for i in range(4): for j in range(3): vsip.put(B,(i,j),data_Br[i][j]) vsip.lud(lu,A) vsip.lusol(lu,vsip.VSIP_MAT_NTRANS,B) print("Solve using LUD AX = B\n X = \n");VU.mprint(B,"%4.2f") vsip.destroy(lu) vsip.prod(RH,R,A) vsip.prod(A,B,Bans) print("Bans = A X\n");VU.mprint(Bans,"%4.2f") vsip.sub(ans,B,B) chk = vsip.sumsqval(B) if chk > .001: print("error\n") else: print("correct\n") vsip.allDestroy(Bans) vsip.allDestroy(R) vsip.allDestroy(RH) vsip.destroy(B) vsip.allDestroy(A) def cchol(p): print("********\nTEST cchol"+p+"\n") ablock = vsip.create('cblock'+p,(200,vsip.VSIP_MEM_NONE)) R = vsip.create('cmview'+p,(4,4,vsip.VSIP_ROW,vsip.VSIP_MEM_NONE)) RH = vsip.create('cmview'+p,(4,4,vsip.VSIP_ROW,vsip.VSIP_MEM_NONE)) A = vsip.bind(ablock,(40,-9,4,-2,4)) B = vsip.bind(ablock,(100,10,4,3,3)) chol = vsip.create('cchol'+p,(vsip.VSIP_TR_UPP,4)) ans = vsip.create('cmview'+p,(4,3,vsip.VSIP_ROW,vsip.VSIP_MEM_NONE)) data_R = [ [1.0, -2.0, 3.0, 1.0], [0.0, 2.0, 4.0, -1.0], [0.0, 0.0, 4.0, 3.0], [0.0, 0.0, 0.0, 6.0] ] data_I = [ [0.0, 2.0, 2.0, 1.0], [0.0, 0.0, 2.0, -4.0], [0.0, 0.0, 0.0, 2.0], [0.0, 0.0, 0.0, 0.0] ] data_Br = [ [1.0, 2.0, 3.0], [0.0, 1.0, 2.0], [3.0, 0.0, 1.0], [3.0, 4.0, 5.0]] data_Bi = [ [1.0, 0.5, 3.2], [2.0, 0.0, 0.6], [0.6, 2.0, 0.0], [5.0, 7.0, 8.0]] data_ans_r = [ [13.6236, 27.5451, 43.1573], [-0.1104, 5.2370, 3.3312], [-0.8403, -1.9410, -2.9823], [ 0.7000, 0.8125, 1.7375] ] data_ans_i = [ [19.4965, 5.3707, 40.9604], [ 6.7292, 5.4896, 15.8781], [-1.4021, -0.3776, -2.9688], [0.3694, -0.1632, 0.4667] ] for i in range(4): for j in range(4): vsip.put(R,(i,j),vsip.complexToCscalar('cscalar'+p,(data_R[i][j] + 1j * data_I[i][j]))) for i in range(4): for j in range(3): vsip.put(B,(i,j),vsip.complexToCscalar('cscalar'+p,(data_Br[i][j] + 1j * data_Bi[i][j]))) vsip.put(ans,(i,j),vsip.complexToCscalar('cscalar'+p,(data_ans_r[i][j] + 1j * data_ans_i[i][j]))) vsip.herm(R,RH) vsip.prod(RH,R,A) print("R = \n");VU.mprint(R,"%4.2f") print("RH = \n");VU.mprint(RH,"%4.2f") print("A = R * RH\n");VU.mprint(A,"%4.2f") print("B \n");VU.mprint(B,"%4.2f") vsip.chold(chol,A) vsip.cholsol(chol,B) print("Solve using cholesky AX = B\n X = \n");VU.mprint(B,"%4.2f") vsip.destroy(chol) print("right answer \n ans = \n");VU.mprint(ans,"%4.2f") vsip.sub(ans,B,B) chk = vsip.meansqval(B) if chk > .001: print("error\n") else: print("correct\n") lu = vsip.create('clu'+p,4) Bans = vsip.create('cmview'+p,(4,3,vsip.VSIP_ROW,vsip.VSIP_MEM_NONE)) vsip.prod(RH,R,A) for i in range(4): for j in range(3): vsip.put(B,(i,j),vsip.complexToCscalar('cscalar'+p,(data_Br[i][j] + 1j * data_Bi[i][j]))) vsip.lud(lu,A) vsip.lusol(lu,vsip.VSIP_MAT_NTRANS,B) print("Solve using LUD AX = B\n X = \n");VU.mprint(B,"%4.2f") vsip.destroy(lu) vsip.prod(RH,R,A) vsip.prod(A,B,Bans) print("Bans = A X \n");VU.mprint(Bans,"%4.2f") vsip.sub(ans,B,B) chk = vsip.meansqval(B) if chk > .001: print("error\n") else: print("correct\n") vsip.allDestroy(Bans) vsip.allDestroy(R) vsip.allDestroy(RH) vsip.destroy(B) vsip.allDestroy(A) vsip_init(None) chol('_f') cchol('_f') chol('_d') cchol('_d') vsip_finalize(None) <file_sep>from vsip import * def __isSizeCompatible(a,b): if 'mview' in a.type and 'mview' in b.type: if (a.rowlength == b.rowlength) and (a.collength == b.collength): return True elif 'vview' in a.type and 'vview' in b.type: if a.length == b.length: return True else: return False # alltrue and anytrue are done only as properties on a view # vsip_salltrue_bl # vsip_sanytrue_bl # vsip_dsleq_p # vsip_dssleq_p def leq(a,b,c): f={'mview_dmview_dmview_bl':vsip_mleq_d, 'mview_fmview_fmview_bl':vsip_mleq_f, 'scalarvview_fvview_bl':vsip_svleq_f, 'scalarvview_dvview_bl':vsip_svleq_d, 'vview_dvview_dvview_bl':vsip_vleq_d, 'vview_fvview_fvview_bl':vsip_vleq_f, 'vview_ivview_ivview_bl':vsip_vleq_i, 'vview_sivview_sivview_bl':vsip_vleq_si, 'vview_ucvview_ucvview_bl':vsip_vleq_uc} assert 'pyJvsip' in repr(b),\ 'Argument two must be a pyJvsip view object in leq' assert 'pyJvsip' in repr(c),\ 'Argument three must be a pyJvsip view object in leq' assert __isSizeCompatible(b,c),'Size error in leq' assert 'view_bl' in c.type, 'Argument c must be a boolean' if isinstance(a,int) or isinstance(a,float): t1='scalar' a0=a else: assert 'pyJvsip' in repr(a),\ 'Argument one must be a pyJvsip view object or scalar in leq' assert __isSizeCompatible(a,c),'Size error in leq' t1=a.type a0=a.vsip t=t1+b.type+c.type assert t in f,'Type <:'+t+':> not recognized for leq' f[t](a0,b.vsip,c.vsip) return c # vsip_slge_p # vsip_sslge_p def lge(a,b,c): f={'mview_dmview_dmview_bl':vsip_mlge_d, 'mview_fmview_fmview_bl':vsip_mlge_f, 'scalarvview_fvview_bl':vsip_svlge_f, 'scalarvview_dvview_bl':vsip_svlge_d, 'vview_dvview_dvview_bl':vsip_vlge_d, 'vview_fvview_fvview_bl':vsip_vlge_f, 'vview_ivview_ivview_bl':vsip_vlge_i, 'vview_sivview_sivview_bl':vsip_vlge_si, 'vview_ucvview_ucvview_bl':vsip_vlge_uc} assert 'pyJvsip' in repr(b),\ 'Argument two must be a pyJvsip view object in lge' assert 'pyJvsip' in repr(c),\ 'Argument three must be a pyJvsip view object in lge' assert __isSizeCompatible(b,c),'Size error in lge' assert 'view_bl' in c.type, 'Argument c must be a boolean' if isinstance(a,int) or isinstance(a,float): t1='scalar' a0=a else: assert 'pyJvsip' in repr(a),\ 'Argument one must be a pyJvsip view object or scalar in lge' assert __isSizeCompatible(a,c),'Size error in lge' t1=a.type a0=a.vsip t=t1+b.type+c.type assert t in f,'Type <:'+t+':> not recognized for lge' f[t](a0,b.vsip,c.vsip) return c # vsip_slgt_p # vsip_sslgt_p def lgt(a,b,c): f={'mview_dmview_dmview_bl':vsip_mlgt_d, 'mview_fmview_fmview_bl':vsip_mlgt_f, 'scalarvview_fvview_bl':vsip_svlgt_f, 'scalarvview_dvview_bl':vsip_svlgt_d, 'vview_dvview_dvview_bl':vsip_vlgt_d, 'vview_fvview_fvview_bl':vsip_vlgt_f, 'vview_ivview_ivview_bl':vsip_vlgt_i, 'vview_sivview_sivview_bl':vsip_vlgt_si, 'vview_ucvview_ucvview_bl':vsip_vlgt_uc} assert 'pyJvsip' in repr(b),\ 'Argument two must be a pyJvsip view object in lgt' assert 'pyJvsip' in repr(c),\ 'Argument three must be a pyJvsip view object in lgt' assert __isSizeCompatible(b,c),'Size error in lgt' assert 'view_bl' in c.type, 'Argument c must be a boolean' if isinstance(a,int) or isinstance(a,float): t1='scalar' a0=a else: assert 'pyJvsip' in repr(a),\ 'Argument one must be a pyJvsip view object or scalar in lgt' assert __isSizeCompatible(a,c),'Size error in lgt' t1=a.type a0=a.vsip t=t1+b.type+c.type assert t in f,'Type <:'+t+':> not recognized for lgt' f[t](a0,b.vsip,c.vsip) return c # vsip_slle_p # vsip_sslle_p def lle(a,b,c): f={'mview_dmview_dmview_bl':vsip_mlle_d, 'mview_fmview_fmview_bl':vsip_mlle_f, 'scalarvview_fvview_bl':vsip_svlle_f, 'scalarvview_dvview_bl':vsip_svlle_d, 'vview_dvview_dvview_bl':vsip_vlle_d, 'vview_fvview_fvview_bl':vsip_vlle_f, 'vview_ivview_ivview_bl':vsip_vlle_i, 'vview_sivview_sivview_bl':vsip_vlle_si, 'vview_ucvview_ucvview_bl':vsip_vlle_uc} assert 'pyJvsip' in repr(b),\ 'Argument two must be a pyJvsip view object in lle' assert 'pyJvsip' in repr(c),\ 'Argument three must be a pyJvsip view object in lle' assert __isSizeCompatible(b,c),'Size error in lle' assert 'view_bl' in c.type, 'Argument c must be a boolean' if isinstance(a,int) or isinstance(a,float): t1='scalar' a0=a else: assert 'pyJvsip' in repr(a),\ 'Argument one must be a pyJvsip view object or scalar in lle' assert __isSizeCompatible(a,c),'Size error in lle' t1=a.type a0=a.vsip t=t1+b.type+c.type assert t in f,'Type <:'+t+':> not recognized for lle' f[t](a0,b.vsip,c.vsip) return c # vsip_sllt_p # vsip_ssllt_p def llt(a,b,c): f={'mview_dmview_dmview_bl':vsip_mllt_d, 'mview_fmview_fmview_bl':vsip_mllt_f, 'scalarvview_fvview_bl':vsip_svllt_f, 'scalarvview_dvview_bl':vsip_svllt_d, 'vview_dvview_dvview_bl':vsip_vllt_d, 'vview_fvview_fvview_bl':vsip_vllt_f, 'vview_ivview_ivview_bl':vsip_vllt_i, 'vview_sivview_sivview_bl':vsip_vllt_si, 'vview_ucvview_ucvview_bl':vsip_vllt_uc} assert 'pyJvsip' in repr(b),\ 'Argument two must be a pyJvsip view object in llt' assert 'pyJvsip' in repr(c),\ 'Argument three must be a pyJvsip view object in llt' assert __isSizeCompatible(b,c),'Size error in llt' assert 'view_bl' in c.type, 'Argument c must be a boolean' if isinstance(a,int) or isinstance(a,float): t1='scalar' a0=a else: assert 'pyJvsip' in repr(a),\ 'Argument one must be a pyJvsip view object or scalar in llt' assert __isSizeCompatible(a,c),'Size error in llt' t1=a.type a0=a.vsip t=t1+b.type+c.type assert t in f,'Type <:'+t+':> not recognized for llt' f[t](a0,b.vsip,c.vsip) return c # vsip_dslne_p # vsip_dsslne_p def lne(a,b,c): f={'mview_dmview_dmview_bl':vsip_mlne_d, 'mview_fmview_fmview_bl':vsip_mlne_f, 'scalarvview_fvview_bl':vsip_svlne_f, 'scalarvview_dvview_bl':vsip_svlne_d, 'vview_dvview_dvview_bl':vsip_vlne_d, 'vview_fvview_fvview_bl':vsip_vlne_f, 'vview_ivview_ivview_bl':vsip_vlne_i, 'vview_sivview_sivview_bl':vsip_vlne_si, 'vview_ucvview_ucvview_bl':vsip_vlne_uc} assert 'pyJvsip' in repr(b),\ 'Argument two must be a pyJvsip view object in lne' assert 'pyJvsip' in repr(c),\ 'Argument three must be a pyJvsip view object in lne' assert __isSizeCompatible(b,c),'Size error in lne' assert 'view_bl' in c.type, 'Argument c must be a boolean' if isinstance(a,int) or isinstance(a,float): t1='scalar' a0=a else: assert 'pyJvsip' in repr(a),\ 'Argument one must be a pyJvsip view object or scalar in lne' assert __isSizeCompatible(a,c),'Size error in lne' t1=a.type a0=a.vsip t=t1+b.type+c.type assert t in f,'Type <:'+t+':> not recognized for lne' f[t](a0,b.vsip,c.vsip) return c<file_sep>// // jvsiph.h // jvsip_pp0 // // Created by <NAME> on 1/30/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #ifndef jvsip_pp0_jvsiph_h #define jvsip_pp0_jvsiph_h #include<cstring> #include<iostream> #include"View.h" #endif <file_sep>/* Created RJudd */ /* */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* */ /* $Id: mprod3_d.h,v 2.1 2006/04/27 01:40:55 judd Exp $ */ #include"VU_mprintm_d.include" static void mprod3_d(void){ printf("********\nTEST mprod4_d\n"); { vsip_scalar_d datal[] = {1.0, 2.0, 4.0, 5.0, 5.0, 0.2, 2.0, 0.0, 1.0}; vsip_scalar_d datar[] = {0.1, 0.2, 0.3, 0.4, 1.0, 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 2.4, -1.1, -1.2, -1.3, -1.4, 2.1, 2.2, 0.3, 3.2, 2.1, 2.2, 1.0, 5.1}; vsip_scalar_d ans_data[] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; vsip_block_d *blockl = vsip_blockbind_d(datal,9,VSIP_MEM_NONE); vsip_block_d *blockr = vsip_blockbind_d(datar,24,VSIP_MEM_NONE); vsip_block_d *block_ans = vsip_blockbind_d(ans_data,24,VSIP_MEM_NONE); vsip_block_d *block = vsip_blockcreate_d(200,VSIP_MEM_NONE); vsip_mview_d *ml = vsip_mbind_d(blockl,0,3,3,1,3); vsip_mview_d *mr = vsip_mbind_d(blockr,0,8,3,1,8); vsip_mview_d *ans = vsip_mbind_d(block_ans,0,8,3,1,8); vsip_mview_d *a = vsip_mbind_d(block,20,-1,3,-4,3); vsip_mview_d *a_cm = vsip_mcreate_d(3,3,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *a_rm = vsip_mcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *b_cm = vsip_mcreate_d(3,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *b_rm = vsip_mcreate_d(3,8,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *c_cm = vsip_mcreate_d(3,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *c_rm = vsip_mcreate_d(3,8,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *b = vsip_mbind_d(block,100,-1,3,-6,8); vsip_mview_d *c = vsip_mbind_d(block,150,-8,3,-1,8); vsip_mview_d *chk = vsip_mcreate_d(3,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *aa = vsip_mcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *bb = vsip_mcreate_d(3,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *cc = vsip_mcreate_d(3,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *c_cc = vsip_cmcreate_d(3,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *c_bb = vsip_cmcreate_d(3,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *i_cc = vsip_mimagview_d(c_cc); vsip_mview_d *r_bb = vsip_mrealview_d(c_bb); vsip_blockadmit_d(blockl,VSIP_TRUE); vsip_blockadmit_d(blockr,VSIP_TRUE); vsip_blockadmit_d(block_ans,VSIP_TRUE); vsip_mcopy_d_d(ml,a); vsip_mcopy_d_d(ml,a_cm); vsip_mcopy_d_d(ml,a_rm); vsip_mcopy_d_d(mr,b); vsip_mcopy_d_d(mr,b_cm); vsip_mcopy_d_d(mr,b_rm); vsip_mcopy_d_d(mr,r_bb); vsip_mcopy_d_d(a,aa); vsip_mcopy_d_d(b,bb); vsip_mprod_d(a,b,ans); vsip_mprod3_d(a,b,c); printf("vsip_mprod3_d(a,b,c)\n"); printf("a\n"); VU_mprintm_d("6.4",a); printf("b\n"); VU_mprintm_d("6.4",b); printf("c\n"); VU_mprintm_d("6.4",c); printf("right answer\n"); VU_mprintm_d("6.4",ans); vsip_msub_d(c,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_mprod3_d(aa,bb,cc); printf("vsip_mprod3_d(aa,bb,cc)\n"); printf("aa\n"); VU_mprintm_d("6.4",aa); printf("bb\n"); VU_mprintm_d("6.4",bb); printf("cc\n"); VU_mprintm_d("6.4",cc); printf("right answer\n"); VU_mprintm_d("6.4",ans); vsip_msub_d(cc,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_mprod3_d(aa,r_bb,i_cc); printf("vsip_mprod3_d(aa,bb,cc)\n"); printf("aa\n"); VU_mprintm_d("6.4",aa); printf("bb\n"); VU_mprintm_d("6.4",r_bb); printf("cc\n"); VU_mprintm_d("6.4",i_cc); printf("right answer\n"); VU_mprintm_d("6.4",ans); vsip_msub_d(i_cc,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check ccc\n"); vsip_mprod3_d(a_cm,b_cm,c_cm); vsip_msub_d(c_cm,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check ccr\n"); vsip_mprod3_d(a_cm,b_cm,c_rm); vsip_msub_d(c_rm,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check crc\n"); vsip_mprod3_d(a_cm,b_rm,c_cm); vsip_msub_d(c_cm,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check crr\n"); vsip_mprod3_d(a_cm,b_rm,c_rm); vsip_msub_d(c_rm,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check rcc\n"); vsip_mprod3_d(a_rm,b_cm,c_cm); vsip_msub_d(c_cm,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check rcr\n"); vsip_mprod3_d(a_rm,b_cm,c_rm); vsip_msub_d(c_rm,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check rrc\n"); vsip_mprod3_d(a_rm,b_rm,c_cm); vsip_msub_d(c_cm,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); printf("check rrr\n"); vsip_mprod3_d(a_rm,b_rm,c_rm); vsip_msub_d(c_rm,ans,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_d(ml); vsip_malldestroy_d(mr); vsip_mdestroy_d(a); vsip_malldestroy_d(aa); vsip_mdestroy_d(b); vsip_malldestroy_d(bb); vsip_malldestroy_d(c); vsip_malldestroy_d(cc); vsip_malldestroy_d(ans); vsip_malldestroy_d(chk); vsip_mdestroy_d(i_cc); vsip_mdestroy_d(r_bb); vsip_cmalldestroy_d(c_cc); vsip_cmalldestroy_d(c_bb); vsip_malldestroy_d(a_cm); vsip_malldestroy_d(a_rm); vsip_malldestroy_d(b_cm); vsip_malldestroy_d(b_rm); vsip_malldestroy_d(c_cm); vsip_malldestroy_d(c_rm); } return; } <file_sep>import Foundation import Accelerate var vec = Vector(length: 15, type: .d) print("local ramp") vec.ramp(start: Scalar(0.1), increment: Scalar(0.2)) for i in 0..<vec.length { print(vec[i].string(format: "4.2")) } vec.length = vec.length/2 vec.stride = vec.stride * 2 print("\nvdsp_Ramp") vec.vdsp_ramp(start: Scalar(1.0), increment: Scalar(2.0)) for i in 0..<vec.length { print(vec[i].string(format: "4.2")) } vec.stride = 1 vec.length = 15 print("\n Combined Ramp") for i in 0..<vec.length { print(vec[i].string(format: "4.2")) } vec.length = vec.length/2 vec.stride = vec.stride * 2 vec.offset = 1 print("\new vdsp_ramp") vec.vdsp_ramp(start: Scalar(1.0), increment: Scalar(2.0)) for i in 0..<vec.length { print(vec[i].string(format: "4.2")) } vec.stride = 1 vec.length = 15 vec.offset = 0 print("\n New Combined Ramp") for i in 0..<vec.length { print(vec[i].string(format: "4.2")) } print("\nsumval " + vec.sumval.string(format: "5.3")) print("\nvdsp_sumval " + vec.vdsp_sumval.string(format: "5.3")) let blk = Block(length: 1000, type: .d) var mat = Matrix(block: blk, offset: 10, colstride: 15, collength: 5, rowstride: 2, rowlength: 5) var v = Vector(block: blk, offset: 0, stride: 1, length: blk.count) v.ramp(start: Scalar(0.0), increment: Scalar(1.0)) print(mat.string(format: "3.1")) var r = mat.row(2) r.ramp(start: Scalar(0.1), increment: Scalar(0.3)) print(mat.row(1).string(format: "3.2")) print(mat.col(2).string(format: "3.2")) print(mat.diag(-1).string(format: "3.2)")) print(mat.string(format: "3.2")) var b = Block(length: 100, type: .d) b[5] = Scalar(3.2) print(b[5].string(format: "4.2")) var v_b = Vector(block: b, offset: 7, stride: 2, length: 8) v_b.vdsp_fill(value: Scalar(5.0)) print(v_b.string(format: "4.2")) <file_sep># -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <markdowncell> # ### Discrete Fourier Transform Coefficients # In this notebook I explore the baseline DFT and examine the decomposition of the coefficient matrix. At the moment this is mostly play to see what I can learn. # # ####Reference # My primary reference is <NAME>'s Computational Frameworks for the Fast Fourier Transform. # There are many references available but I won't try and list them here. # <codecell> import pyJvsip as pv # <markdowncell> # The DFT matrix is square and complex. We designate it as $F_n$ where n is the size of the matrix. If we have a (column) vector $\vec x$ of size $n$ then the dft is # $\vec X = F_n \vec x$. # Elements of $F_n$ are designated $f_{q,p}$. These elements are equally spaced around the unit circle in the complex plane at increments of ${2 \pi} \over {n}$ so that # $f_{q,p}$ = `complex`$\left(\cos(2 q p \pi/n),-\sin(2 q p \pi/n)\right)$ # Since $q$ and $p$ traverse all value pairs between $0$ and $n-1$ and go around the unit circle more than once if we set $t$ to the $pq$ modulo $n$ then we can compute just a vector of DFT weights from $0$ to $n-1$ and look up the proper value with index $t$. # <markdowncell> # Below we define functions to return the matrix of DFT weights for matrix of size n. The function dftCoefE returns the actual weight. The function dftCoef returns the matrix of index values $t$ described above. # <codecell> def dftCoefE(n): m=pv.create('cmview_d',n,n) for i in range(n): for j in range(n): t=(i*j)%n x=2.0*pi/n * float(t) m[i,j]=complex(cos(x),-sin(x)) return m def dftCoef(n): m=pv.create('mview_d',n,n) for i in range(n): for j in range(n): m[i,j]=(i*j)%n return m # <codecell> A=dftCoefE(4) A.mprint('%.3f') # <codecell> B=dftCoef(4) B.mprint('%.3f') # <codecell> dftCoef(5).mprint('%.1f') # <codecell> dftCoef(3).sv.mprint('%.3f') # <codecell> dftCoef(5).sv.mprint('%.3f') # <codecell> dftCoef(7).sv.mprint('%.3f') # <codecell> dftCoef(11).sv.mprint('%.3f') # <codecell> dftCoef(13).sv.mprint('%.3f') # <codecell> dftCoef(17).sv.mprint('%.3f') # <codecell> dftCoef(3*2).sv.mprint('%.3f') # <codecell> dftCoef(2).sv.mprint('%.3f') # <markdowncell> # So, playing, I notice if I find the singular values of the $t$ values matrix and I use a prime number for $n$ then the largest singular value is an integer equal to (n-1)/2 * n. Don't know if this is of use but is interesting. # <codecell> 136/17 (17-1)/2*17 # <codecell> print('%d, %d'%(78/13, (13-1)/2*13)) # <codecell> print('%d, %d'%(55/11, (11-1)/2*11)) # <codecell> 21/7 # <codecell> 3/3 # <codecell> #try it for not prime 6 print('%f, %f'%(12.97, (6.-1.)/2.*6.)) # <codecell> <file_sep>/* Created RJudd March 6, 2000*/ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mindexbool.c,v 2.0 2003/02/22 15:18:57 judd Exp $ */ #include"vsip.h" #include"vsip_vviewattributes_mi.h" #include"vsip_mviewattributes_bl.h" vsip_length vsip_mindexbool( const vsip_mview_bl *r, vsip_vview_mi *x){ vsip_length retval = 0; { vsip_length n_mj, /* major length */ n_mn; /* minor length */ vsip_stride mn_i = -1, mj_i = -1; vsip_stride rst_mj, rst_mn; vsip_scalar_bl *rp = r->block->array + r->offset; vsip_scalar_bl *rp0 = rp; vsip_scalar_vi *xp = x->block->array + x->offset, *xp_mj, *xp_mn; vsip_stride xst = 2 * x->stride; /* pick search direction */ if(r->row_stride < r->col_stride){ xp_mj = xp + 1; xp_mn = xp; n_mj = r->row_length; n_mn = r->col_length; rst_mj = r->row_stride; rst_mn = r->col_stride; } else { xp_mj = xp; xp_mn = xp + 1; n_mn = r->row_length; n_mj = r->col_length; rst_mn = r->row_stride; rst_mj = r->col_stride; } /* end define */ while(mn_i++ < (vsip_stride)(n_mn - 1)){ mj_i = -1; while(mj_i++ < (vsip_stride)(n_mj - 1)){ if(*rp != VSIP_FALSE){ *xp_mj = (vsip_index)mj_i; *xp_mn = (vsip_index)mn_i; xp_mj += xst; xp_mn+= xst; retval++; } rp += rst_mj; } rp0 += rst_mn; rp = rp0; } if(retval > 0) x->length = retval; } return retval; } <file_sep>/* Created by RJudd September 9, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_ccfftmip_d_loop.h,v 2.0 2003/02/22 15:18:29 judd Exp $ */ /* Use a loop of vsip_ccfftip_d.h to calculate fftm */ /* input matrix x, output matrix y, fftm object fftm */ #include"VI_cmrowview_d.h" #include"VI_cmcolview_d.h" void vsip_ccfftmip_d(const vsip_fftm_d *Offt, const vsip_cmview_d *y) { vsip_fftm_d Nfft = *Offt; vsip_fftm_d *fftm = &Nfft; vsip_fft_d *fft = (vsip_fft_d*)fftm->ext_fftm_obj; vsip_index k = 0; vsip_cvview_d zz; if(fftm->major == VSIP_ROW){ while(k < y->col_length){ vsip_ccfftip_d(fft, VI_cmrowview_d(y,k,&zz)); k++; } } else { /* must be column */ while(k < y->row_length){ vsip_ccfftip_d(fft, VI_cmcolview_d(y,k,&zz)); k++; } } } <file_sep>from vsip import * from vsipElementwiseElementary import * from vsipElementwiseManipulation import * from vsipElementwiseUnary import * from vsipElementwiseBinary import * from vsipElementwiseTernary import * from vsipElementwiseLogical import * from vsipElementwiseSelection import * from vsipElementwiseBandB import * from vsipElementwiseCopy import * from vsipSignalProcessing import * from vsipLinearAlgebra import * from vsipAddendum import * __version__='0.5.0' #Functions between here and Block are meant to be used internal to pyJvsip implementation. #For the adventuresome your mileage may vary. def vsipScalar(t,scl): """ alpha=(t,beta) where alpha equivalent to beta This function produces a scalar value suitable for storing into a view of type t. Float input to integers will be converted using the python int() function. Integer values outside the precision range of the view are not checked for. """ tScl=getType(scl) ft=tScl[2] assert tScl[1] == 'scalar','Input must be a python or pyJvsip scalar' assert 'view' in t,'Type must corespond to a view object' if t == 'cvview_d' or t == 'cmview_d': if tScl[0] == 'python': return vsip_cmplx_d(scl.real,scl.imag) else: assert 'cscalar' in tScl[2],'Type <:%s:> not a suitable type for complex scalar'%tScl[2] return vsip_cmplx_d(scl.r,scl.i) elif t == 'cvview_f' or t == 'cmview_f': if tScl[0] == 'python': return vsip_cmplx_f(scl.real,scl.imag) else: assert 'cscalar' in tScl[2],'Type <:%s:> not a suitable type for complex scalar'%tScl[2] return vsip_cmplx_f(scl.r,scl.i) elif '_d' in t or '_f' in t: assert ft is float or ft is int,\ 'For real views of type double or float input scalar must be a real number.' return float(scl) elif '_i' in t or '_si' in t: assert ft is float or ft is int,\ 'For signed integer views input must be a number that can be converted to an integer' return int(scl) elif t == 'vview_vi' or t == 'vview_uc' or t == 'mview_uc': assert float is ft or int is ft ,'Need a number such that int(aNumber) has a return value of int' assert scl >= 0,'The precision of type vector index (_vi) is an integer >= 0' return int(scl) elif t == 'vview_mi': assert (ft is tuple and len(scl)== 2) or ft == 'scalar_mi',\ 'Input to views of precision matrix index (_mi) should be of type scalar_mi or a tuple of length 2' if ft is tuple: r=scl[0];c=scl[1] else: r=scl.r; c=scl.c assert isinstance(r,int) and isinstance(c,int) ,\ 'Index values are of type integer.' assert r >=0 and c >= 0,'Index values are integers >= 0' return vsip_matindex(int(r),int(c)) elif t == 'vview_bl' or t == 'mview_bl': assert isinstance(scl,bool) or isinstance(scl,int) or isinstance(scl,float),\ 'Value <:%s:> not suitable for storing in view of precision _bl'%repr(scl) if scl == False or scl == 0: return 0 else: return 1 else: assert False,'Should not be able to fail here. Implementation error.' def vsipGetType(v): """ Returns a tuple with True if a vsip type is found, plus a string indicating the type. For instance for a = vsip_vcreate_f(10,VSIP_MEM_NONE) will return for the call getType(a) (True,'vview_f') also returns types of scalars derived from structure. for instance c = vsip_cscalar_d() will return for getType(c) the tuple (True, 'cscalar_d'). attr = vsip_mattr_d() will return for getType(attr) the tuple (True, 'mattr_d') If float or int type is passed in returns (True,'scalar') If called with a non VSIPL type returns (False, 'Not a VSIPL Type') """ t = repr(v).rpartition('vsip_') if t[1] == 'vsip_': return(True,t[2].partition(" ")[0]) elif isinstance(v,float): return(True,'scalar') elif isinstance(v,int): return(True,'scalar') else: return(False,'Not a VSIPL Type') def getType(v): """ Returns a tuple with type information. Most of the time getType(v)[2] will be the information needed. getType(v)[0] is the module (python, vsip, or pyJvsip). getType(v)[1] is the class (scalar, View, Block, etc). getType(v)[2] is the type which is dependent on the module and class. """ if isinstance(v,int) or isinstance(v,float) or isinstance(v,complex): return ('python','scalar',type(v)) elif 'vsip_scalar_mi' in repr(v): return ('vsip','scalar','scalar_mi') elif 'vsip_cscalar_f' in repr(v): return ('vsip','scalar','cscalar_f') elif 'vsip_cscalar_d' in repr(v): return ('vsip','scalar','cscalar_d') elif 'pyJvsip' in repr(v): return ('pyJvsip','View',v.type) elif 'pyJvsip.Block' in repr(v): return ('pyJvsip','Block',v.type) elif 'pyJvsip.Rand' in repr(v): return ('pyJvsip','Rand',v.type) elif 'pyJvsip.FFT' in repr(v): return ('pyJvsip','FFT',v.type) elif 'pyJvsip.LU' in repr(v): return('pyJvsip','LU',v.type) elif 'pyJvsip.QR' in repr(v): return('pyJvsip','QR',v.type) else: return (repr(v),None,None) def vsipGetAttrib(v): f={ 'vview_f': (vsip_vgetattrib_f,vsip_vattr_f), 'vview_d': (vsip_vgetattrib_d,vsip_vattr_d), 'mview_f': (vsip_mgetattrib_f,vsip_mattr_f), 'mview_d': (vsip_mgetattrib_d,vsip_mattr_d), 'cvview_f':(vsip_cvgetattrib_f,vsip_cvattr_f), 'cvview_d':(vsip_cvgetattrib_d,vsip_cvattr_d), 'cmview_f':(vsip_cmgetattrib_f,vsip_cmattr_f), 'cmview_d':(vsip_cmgetattrib_d,vsip_cmattr_d), 'vview_i': (vsip_vgetattrib_i,vsip_vattr_i), 'mview_i': (vsip_mgetattrib_i,vsip_mattr_i), 'vview_si':(vsip_vgetattrib_si,vsip_vattr_si), 'mview_si':(vsip_mgetattrib_si,vsip_mattr_si), 'vview_uc':(vsip_vgetattrib_uc,vsip_vattr_uc), 'mview_uc':(vsip_mgetattrib_uc,vsip_mattr_uc), 'vview_vi':(vsip_vgetattrib_vi,vsip_vattr_vi), 'vview_bl':(vsip_vgetattrib_bl,vsip_vattr_bl), 'mview_bl':(vsip_mgetattrib_bl,vsip_mattr_bl), 'vview_mi':(vsip_vgetattrib_mi,vsip_vattr_mi), 'cfir_d':(vsip_cfir_getattr_d,vsip_cfir_attr), 'cfir_f':(vsip_cfir_getattr_f,vsip_cfir_attr), 'fir_d':(vsip_fir_getattr_f,vsip_fir_attr), 'fir_f':(vsip_fir_getattr_f,vsip_fir_attr), 'lu_f':(vsip_lud_getattr_f,vsip_lu_attr_f), 'clu_f':(vsip_clud_getattr_f,vsip_clu_attr_f), 'lu_d':(vsip_lud_getattr_d,vsip_lu_attr_d), 'clu_d':(vsip_clud_getattr_d,vsip_clu_attr_d), 'chol_f':(vsip_chold_getattr_f,vsip_chol_attr_f), 'cchol_f':(vsip_cchold_getattr_f,vsip_cchol_attr_f), 'chol_d':(vsip_chold_getattr_d,vsip_chol_attr_d), 'cchold_d':(vsip_cchold_getattr_d,vsip_cchol_attr_d), 'qr_f':( vsip_qrd_getattr_f,vsip_qr_attr_f), 'cqr_f':(vsip_cqrd_getattr_f,vsip_cqr_attr_f), 'qr_d':( vsip_qrd_getattr_d,vsip_qr_attr_d), 'cqr_d':(vsip_cqrd_getattr_d,vsip_cqr_attr_d)} # svd getattr not implemented yet #'sv_f':(vsip_svd_getattr_f,vsip_sv_attr_f), #'sv_d':(vsip_svd_getattr_d,vsip_sv_attr_d), #'csv_f':(vsip_csvd_getattr_f,vsip_sv_attr_f), #'csv_d':(vsip_csvd_gatattr_d,vsip_sv_attr_d) assert 'pyJvsip' in repr(v),'vsipGetAttrib does not support %s.'%repr(v) assert v.type in f,'Type <:%s:> not recognized for vsipGetAttrib'%v.type attr=f[v.type][1]() f[v.type][0](v.vsip,attr) return attr def vsipPutAttrib(v,attrib): """ Change the attributes of a view object """ fv={ 'vview_f':vsip_vputattrib_f, 'vview_d':vsip_vputattrib_d, 'cvview_f':vsip_cvputattrib_f, 'cvview_d':vsip_cvputattrib_d, 'vview_vi':vsip_vputattrib_vi, 'vview_mi':vsip_vputattrib_mi, 'vview_bl':vsip_vputattrib_bl, 'vview_i':vsip_vputattrib_i, 'vview_si':vsip_vputattrib_si, 'vview_uc':vsip_vputattrib_uc} fm={ 'mview_f':vsip_mputattrib_f, 'mview_d':vsip_mputattrib_d, 'cmview_f':vsip_cmputattrib_f, 'cmview_d':vsip_cmputattrib_d, 'mview_bl':vsip_mputattrib_bl, 'mview_i':vsip_mputattrib_i, 'mview_si':vsip_mputattrib_si, 'mview_uc':vsip_mputattrib_uc} assert 'pyJvsip' in repr(v),'vsipPutAttrib only works on pyJvsip objects' assert 'offset' in attrib,'Key Value Error' attr=vsipGetAttrib(v) if 'mview' in v.type: assert isinstance(attrib,dict),'Attribute is a dictionary object in pyJvsip' assert len(attrib) == 5,'Matrix view attributes have five key value pairs' assert 'rowlength' in attrib and 'collength' in attrib,'Key Value Error' assert 'rowstride'in attrib and 'colstride' in attrib,'Key Value Error' attr.offset = attrib['offset'] attr.row_length = attrib['rowlength'] attr.col_length = attrib['collength'] attr.row_stride = attrib['rowstride'] attr.col_stride = attrib['colstride'] assert attr.offset + (attr.row_length-1) * attr.row_stride + (attr.col_length-1) * attr.col_stride < v.block.length, \ 'Attribute not allowed. Will allow access beyond the space of the block.' fm[v.type](v.vsip,attr) elif 'vview' in v.type: assert isinstance(attrib,dict),'Attribute is a dictionary object in pyJvsip' assert len(attrib) == 3,'Vector view attributes have three key value pairs' assert 'length' in attrib and 'stride' in attrib,'Key Value Error' attr.offset = attrib['offset'] attr.length = attrib['length'] attr.stride = attrib['stride'] assert attr.offset + (attr.length-1) * attr.stride < v.block.length, \ 'Attribute not allowed. Will allow access beyond the space of the block.' fv[v.type](v.vsip,attr) else: assert False,'vsipPutAttrib does not support type <:%s:> at this time'%v.stype return v class GetAttrib(object): def __init__(self,v): assert 'pyJvsip' in repr(v),'PyJvsipGetAttrib only works on python objects' self.__attr = vsipGetAttrib(v) #VSIPL attribute pointer self.__type = 'attrib'+v.type #Unique string to identify attribute attr=self.__attr if 'vview' in self.__type: self.__attrib = {'offset':attr.offset,'stride':attr.stride,'length':attr.length} elif 'mview' in self.type: self.__attrib = {'offset':attr.offset, 'colstride':attr.col_stride,'collength':attr.col_length, 'rowstride':attr.row_stride,'rowlength':attr.row_length} else: self.__attrib = None # This section to set pyJvsip attribute dictionary @property def type(self): return self.__type @property def vsip(self): return self.__attr @property def attrib(self): return self.__attrib class JVSIP (object): init = 0 def __init__(self): if JVSIP.init: self.vsipInit=0; JVSIP.init +=1; else: self.vsipInit = vsip_init(None) assert self.vsipInit == 0,'VSIP failed to initialize' JVSIP.init = 1; def __del__(self): JVSIP.init -= 1 if JVSIP.init == 0: vsip_finalize(None) class Block (object): tBlock = ['block_f','block_d','cblock_f','cblock_d', 'block_vi','block_mi','block_bl', 'block_si','block_i','block_uc'] derivedTypes = ['real_f','real_d','imag_f','imag_d'] matrixTypes=['mview_f','mview_d','cmview_f','cmview_d', 'mview_si','mview_i','mview_uc','mview_bl'] vectorTypes=['vview_f','vview_d','cvview_f','cvview_d', 'vview_si','vview_i',\ 'vview_uc','vview_mi', 'vview_vi','vview_bl'] windowTypes=['blackman_d','blackman_f','cheby_d','cheby_f',\ 'kaiser_d','kaiser_f','hanning_d','hanning_f'] complexTypes=['cvview_f','cmview_f','cvview_d','cmview_d','cblock_f','cblock_d'] blkSel={'vview_f':'block_f','vview_d':'block_d','cvview_f':'cblock_f',\ 'cvview_d':'cblock_d', 'vview_si':'block_si','vview_i':'block_i',\ 'vview_uc':'block_uc', 'vview_mi':'block_mi', 'vview_vi':'block_vi',\ 'vview_bl':'block_bl','mview_f':'block_f','mview_d':'block_d',\ 'cmview_f':'cblock_f','cmview_d':'cblock_d','mview_si':'block_si',\ 'mview_i':'block_i','mview_uc':'block_uc','mview_bl':'block_bl'} #Block specific class below def __init__(self,block_type,*args): bc={'block_f':vsip_blockcreate_f, 'block_d':vsip_blockcreate_d, 'cblock_f':vsip_cblockcreate_f, 'cblock_d':vsip_cblockcreate_d, 'block_i':vsip_blockcreate_i, 'block_si':vsip_blockcreate_si, 'block_uc':vsip_blockcreate_uc, 'block_vi':vsip_blockcreate_vi, 'block_mi':vsip_blockcreate_mi, 'block_bl':vsip_blockcreate_bl} other = Block.derivedTypes assert isinstance(block_type,str),'The type argument should be a string' keyError='Block type <:%s:> not support by Block class'%block_type assert block_type in bc or block_type in other or block_type in Block.windowTypes,keyError self.__jvsip = JVSIP() if block_type in Block.tBlock: #Regular block constructor self.__vsipBlock = bc[block_type](args[0],VSIP_MEM_NONE) self.__length = args[0] self.__type = block_type elif block_type in other: #Derived block constructor for real, imag views self.__vsipBlock = args[0] self.__length = args[1] self.__type = block_type else: #must be window assert block_type in Block.windowTypes,'Should not be here. Block type not a window type' # window functions selector f={'blackman_d':'vsip_vcreate_blackman_d(args[0],0)',\ 'blackman_f':'vsip_vcreate_blackman_f(args[0],0)',\ 'cheby_d':'vsip_vcreate_cheby_d(args[0],args[1],0)',\ 'cheby_f':'vsip_vcreate_cheby_f(args[0],args[1],0)',\ 'kaiser_d':'vsip_vcreate_kaiser_d(args[0],args[1],0)',\ 'kaiser_f':'vsip_vcreate_kaiser_f(args[0],args[1],0)',\ 'hanning_d':'vsip_vcreate_hanning_d(args[0],0)',\ 'hanning_f':'vsip_vcreate_hanning_f(args[0],0)'} # block type selector bt={'blackman_d':'block_d','blackman_f':'block_f','cheby_d':'block_d',\ 'cheby_f':'block_f','kaiser_d':'block_d','kaiser_f':'block_f',\ 'hanning_d':'block_d','hanning_f':'block_f'} # get block selector gb={'block_d':vsip_vgetblock_d,'block_f':vsip_vgetblock_f} v=eval(f[block_type]) # create vsip window vector b=bt[block_type] # get block type for window created blk = gb[b](v) # get pointer to vectors C VSIPL block # construct pyJvsip block self.__vsipBlock=blk self.__type=b self.__length=args[0] self.w = self.__View({'block_d':'vview_d','block_f':'vview_f'}[b],v,self) #create a pyJvsip view object with window in it. def __del__(self): bd={'block_f':vsip_blockdestroy_f, 'block_bl':vsip_blockdestroy_bl, 'block_d':vsip_blockdestroy_d, 'block_i':vsip_blockdestroy_i, 'block_mi':vsip_blockdestroy_mi, 'block_si': vsip_blockdestroy_si, 'block_uc':vsip_blockdestroy_uc, 'block_vi':vsip_blockdestroy_vi, 'cblock_d':vsip_cblockdestroy_d, 'cblock_f':vsip_cblockdestroy_f} t = self.__type if t in bd: bd[t](self.__vsipBlock) del(self.__jvsip) @property def vsip(self): return self.__vsipBlock # major for bind of matrix in attr is 'ROW', or 'COL' def bind(self,*args): def vsipBind(blkType,blk,l): f={ 'block_fvector':('vview_f','vsip_vbind_f(blk,l[0],l[1],l[2])' ), 'block_dvector':('vview_d','vsip_vbind_d(blk,l[0],l[1],l[2])' ), 'cblock_fvector':('cvview_f','vsip_cvbind_f(blk,l[0],l[1],l[2])'), 'cblock_dvector':('cvview_d','vsip_cvbind_d(blk,l[0],l[1],l[2])'), 'block_ivector':('vview_i','vsip_vbind_i(blk,l[0],l[1],l[2])' ), 'block_sivector':('vview_si','vsip_vbind_si(blk,l[0],l[1],l[2])'), 'block_ucvector':('vview_uc','vsip_vbind_uc(blk,l[0],l[1],l[2])'), 'block_vivector':('vview_vi','vsip_vbind_vi(blk,l[0],l[1],l[2])'), 'block_mivector':('vview_mi','vsip_vbind_mi(blk,l[0],l[1],l[2])'), 'block_blvector':('vview_bl','vsip_vbind_bl(blk,l[0],l[1],l[2])'), 'block_fmatrix':('mview_f','vsip_mbind_f(blk,l[0],l[1],l[2],l[3],l[4])' ), 'block_dmatrix':('mview_d','vsip_mbind_d(blk,l[0],l[1],l[2],l[3],l[4])' ), 'cblock_fmatrix':('cmview_f','vsip_cmbind_f(blk,l[0],l[1],l[2],l[3],l[4])'), 'cblock_dmatrix':('cmview_d','vsip_cmbind_d(blk,l[0],l[1],l[2],l[3],l[4])'), 'block_imatrix':('mview_i','vsip_mbind_i(blk,l[0],l[1],l[2],l[3],l[4])' ), 'block_simatrix':('mview_si','vsip_mbind_si(blk,l[0],l[1],l[2],l[3],l[4])'), 'block_ucmatrix':('mview_uc','vsip_mbind_uc(blk,l[0],l[1],l[2],l[3],l[4])'), 'block_blmatrix':('mview_bl','vsip_mbind_bl(blk,l[0],l[1],l[2],l[3],l[4])')} if len(l) == 3: t=blkType+'vector' elif len(l) == 5: t=blkType+'matrix' assert t in f,'Bind has no type <:%s:>.'%t vsipBlk=eval(f[t][1]) viewType=f[t][0] return (viewType,vsipBlk) bSel={'real_f':'block_f','real_d':'block_d','imag_f':'block_f','imag_d':'block_d'} if isinstance(args[0],tuple): arg=[item for item in args[0]] else: arg = args assert len(arg) == 3 or len(arg) == 5,\ 'Argument list to block bind must be 3 (for vectors) or 5 (for matrices) integers.' if len(arg) == 3: attr=(arg[0],arg[1],arg[2]) else:# len(arg) == 5: attr=(arg[0],arg[1],arg[2],arg[3],arg[4]) bType=self.type if self.type in bSel: bType=bSel[self.type] viewType,vsipView = vsipBind(bType,self.__vsipBlock,attr) retval = self.__View(viewType,vsipView,self) retval.EW return retval @property def vector(self): """ Since data in blocks is only accessible through a view the vector method is a convenience method to return the simplest view wich indexes all data. Usage: b = Block(aBlockType,length) v = b.vector v is a unit stride compact one dimensional view reflecting all the data in the block. """ return self.bind(0,1,self.length) @classmethod def supported(cls): return {'tBlock':Block.tBlock,'viewTypes':Block.__View.supported()} @property def empty(self): """ This makes a new block object of the same type and size of the calling block object. Data in the old block object is NOT copied to the new block object. """ return self.otherBlock(self.type,self.length) @classmethod def otherBlock(cls,blk,arg): """ This method is used internal to the pyJvsip module. It is not intended to be used in user code. otherBlock creates a new block of type blk (or the proper type if blk is derived). """ #bSel is a block selector to select the proper type block if the input type is derived bSel={'imag_f':'block_f','real_f':'block_f','imag_d':'block_d','real_d':'block_d'} if isinstance(arg,tuple):#create derived block return cls(blk,arg[0],arg[1]) elif blk in bSel:#create new block starting with derived block return cls(bSel[blk],arg) else:#create new block return cls(blk,arg) @property def type(self): return self.__type @property def length(self): return self.__length def __len__(self): return self.length #View Class defined here # views are required by the specification to be associated with a block. # To enforce that in pyJvsip only block objects know how to create views; # or at least that is the goal by placing views here. As far as python is # concerned I still have much to learn. class __View(object): tView=['mview_f','mview_d','cmview_f','cmview_d', 'mview_si','mview_i','mview_uc','mview_bl', 'vview_f','vview_d','cvview_f','cvview_d', 'vview_si','vview_i','vview_uc', 'vview_mi', 'vview_vi','vview_bl'] def __init__(self,vType,view,block): self.__jvsip = JVSIP() self.__vsipView = view self.__pyBlock = block self.__type = vType self.__major ='EW' self.__parent = 0 def __del__(self): vd={'vview_f' :vsip_vdestroy_f, 'vview_d' :vsip_vdestroy_d, 'cvview_f' :vsip_cvdestroy_f, 'cvview_d' :vsip_cvdestroy_d, 'vview_i' :vsip_vdestroy_i, 'vview_si' :vsip_vdestroy_si, 'vview_uc' :vsip_vdestroy_uc, 'vview_bl' :vsip_vdestroy_bl, 'vview_vi' :vsip_vdestroy_vi, 'vview_mi' :vsip_vdestroy_mi, 'mview_f' :vsip_mdestroy_f, 'mview_d' :vsip_mdestroy_d, 'cmview_f' :vsip_cmdestroy_f, 'cmview_d' :vsip_cmdestroy_d, 'mview_i' :vsip_mdestroy_i, 'mview_si' :vsip_mdestroy_si, 'mview_uc' :vsip_mdestroy_uc, 'mview_bl' :vsip_mdestroy_bl} t=self.type vd[t](self.__vsipView) del(self.__pyBlock) del(self.__jvsip) @classmethod def supported(cls): return cls.tView @property def supported(self): self.supported() @classmethod def __newView(cls,viewType,v,b): """ Given a C VSIP view v which is associated with block b.block where b is a pyJvsip block create a new pyJvsip view encapsulating v. This method is used internally to create pyJvsip equivalents for subviews like rowview, colview, diagview, etc. """ return cls(viewType,v,b) @classmethod def __realview(cls,V): vSel={'cvview_f':'vview_f','cvview_d':'vview_d', 'cmview_f':'mview_f','cmview_d':'mview_d'} db={'cvview_f':'real_f','cvview_d':'real_d', 'cmview_f':'real_f','cmview_d':'real_d'} rv={'cmview_d': vsip_mrealview_d,'cmview_f': vsip_mrealview_f, 'cvview_d': vsip_vrealview_d,'cvview_f': vsip_vrealview_f} gb={'cvview_f':vsip_vgetblock_f,'cvview_d':vsip_vgetblock_d, 'cmview_f':vsip_mgetblock_f,'cmview_d':vsip_mgetblock_d} assert V.type in db,'View of type <:%s:> not supported for realview.'%V.type t=db[V.type] #type of derived block v=rv[V.type](V.vsip) #get real vsip view b=gb[V.type](v) #get derived (vsip) block from real (vsip) view B=V.block l=B.length newB = B.otherBlock(t,(b,l))# create new pyJvsip derived block return cls(vSel[V.type],v,newB)#create new pyJvsip real view with associated derived block @classmethod def __imagview(cls,V): vSel={'cvview_f':'vview_f','cvview_d':'vview_d', 'cmview_f':'mview_f','cmview_d':'mview_d'} db={'cvview_f':'imag_f','cvview_d':'imag_d', 'cmview_f':'imag_f','cmview_d':'imag_d'} rv={'cmview_d': vsip_mimagview_d,'cmview_f': vsip_mimagview_f, 'cvview_d': vsip_vimagview_d,'cvview_f': vsip_vimagview_f} gb={'cvview_f':vsip_vgetblock_f,'cvview_d':vsip_vgetblock_d, 'cmview_f':vsip_mgetblock_f,'cmview_d':vsip_mgetblock_d} assert V.type in db,'View of type <:%s:> not supported for imagview.'%V.type t=db[V.type] #type of derived block v=rv[V.type](V.vsip) #get imag vsip view b=gb[V.type](v) #get derived (vsip) block from imag (vsip) view B=V.block l=B.length newB = B.otherBlock(t,(b,l))# create new pyJvsip derived block return cls(vSel[V.type],v,newB)#create new pyJvsip real view with associated derived block # Elementwise add, sub, mul, div def __iadd__(self,other): # self += other add(other,self,self) return self def __add__(self,other): # new = self + other return add(other,self,self.empty) def __radd__(self,other): # new = other + self return add(other,self,self.empty) def __isub__(self,other): # -=other if 'pyJvsip' in repr(other): sub(self,other,self) else: add(-other,self,self) return self def __sub__(self,other):#self - other retval=self.empty if 'pyJvsip' in repr(other): return sub(self,other,retval) else: return add(-other,self,retval) def __rsub__(self,other): #other - self retval=self.empty return sub(other,self,retval) def __imul__(self,other):# *=other mul(other,self,self) return self def __mul__(self,other): return mul(other,self,self.empty) def __rmul__(self,other): # other * self return mul(other,self,self.empty) def __idiv__(self,other): if 'pyJvsip' in repr(other): div(self,other,self) elif isinstance(other,int) or isinstance(other,float) : div(self,other,self) elif isinstance(other,complex): mul(1.0/other,self,self) else: print('idiv divisor not recognized') return self def __div__(self,other): if isinstance(other,complex): return mul(1.0/other,self,self.empty) else: return div(self,other,self.empty) def __rdiv__(self,other): # other / self return div(other,self,self.empty) def __neg__(self): return neg(self,self) def __iter__(self): ind = 0 if 'vview' in self.type: while ind < self.length: yield self[ind] ind +=1 else: # must be a matrix while ind < self.collength: yield self.rowview(ind) ind +=1 return @property def list(self): f = {'cvview_f':'cvcopyToList_f(self.vsip)', 'cvview_d':'cvcopyToList_d(self.vsip)', 'vview_f':'vcopyToList_f(self.vsip)', 'vview_d':'vcopyToList_d(self.vsip)', 'vview_i':'vcopyToList_i(self.vsip)', 'vview_si':'vcopyToList_si(self.vsip)', 'vview_uc':'vcopyTolist_uc(self.vsip)', 'vview_vi':'vcopyToList_vi(self.vsip)', 'vview_mi':'vcopyToList_mi(self.vsip)'} fByRow = {'cmview_f':'cmcopyToListByRow_f(self.vsip)', 'mview_f':'mcopyToListByRow_f(self.vsip)', 'cmview_d':'cmcopyToListByRow_d(self.vsip)', 'mview_d':'mcopyToListByRow_d(self.vsip)', 'mview_i':'mcopyToListByRow_i(self.vsip)', 'mview_si':'mcopyToListByRow_si(self.vsip)', 'mview_uc':'mcopyToListByRow_uc(self.vsip)'} fByCol = {'cmview_f':'cmcopyToListByCol_f(self.vsip)', 'mview_f':'mcopyToListByCol_f(self.vsip)', 'cmview_d':'cmcopyToListByCol_d(self.vsip)', 'mview_d':'mcopyToListByCol_d(self.vsip)', 'mview_i':'mcopyToListByCol_i(self.vsip)', 'mview_si':'mcopyToListByCol_si(self.vsip)', 'mview_uc':'mcopyToListByCol_uc(self.vsip)'} if self.type in f: return eval(f[self.type]) elif 'COL' in self.major and self.type in fByCol: return eval(fByCol[self.type]) elif self.type in fByRow: #default by row for matrices return eval(fByRow[self.type]) else: assert False, 'Type not supported by list' def __getitem__(self,index): def vsipGet(aView,aIndex): gSel={'cvview_dscalar':'vsip_cvget_d(a,int(i))', 'cvview_fscalar':'vsip_cvget_f(a,int(i))', 'vview_dscalar':'vsip_vget_d(a,int(i))', 'vview_fscalar':'vsip_vget_f(a,int(i))', 'vview_iscalar':'int(vsip_vget_i(a,int(i)))', 'vview_viscalar':'int(vsip_vget_vi(a,int(i)))', 'vview_siscalar':'int(vsip_vget_si(a,int(i)))', 'vview_ucscalar':'int(vsip_vget_uc(a,int(i)))', 'vview_blscalar':'vsip_vget_bl(a,int(i))', 'vview_miscalar':'vsip_vget_mi(a,int(i))', 'cmview_dtuple':'vsip_cmget_d(a,i[0],i[1])', 'cmview_ftuple':'vsip_cmget_f(a,i[0],i[1])', 'mview_dtuple':'vsip_mget_d(a,i[0],i[1])', 'mview_ftuple':'vsip_mget_f(a,i[0],i[1])', 'mview_ituple':'int(vsip_mget_i(a,i[0],i[1]))', 'mview_situple':'int(vsip_mget_si(a,i[0],i[1]))', 'mview_uctuple':'vsip_mget_uc(a,i[0],i[1])', 'mview_blstuple':'vsip_mget_bl(a,i[0],i[1])', 'cmview_dscalar_mi':'vsip_cmget_d(a,i.r,i.c)', 'cmview_fscalar_mi':'vsip_cmget_f(a,i.r,i.c)', 'mview_dscalar_mi':'vsip_mget_d(a,i.r,i.c)', 'mview_fscalar_mi':'vsip_mget_f(a,i.r,i.c)', 'mview_iscalar_mi':'int(vsip_mget_i(a,i.r,i.c))', 'mview_siscalar_mi':'int(vsip_mget_si(a,i.r,i.c))', 'mview_ucscalar_mi':'vsip_mget_uc(a,i.r,i.c)', 'mview_blscalar_mi':'vsip_mget_bl(a,i.r,i.c)'} t=aView.type if 'vview' in t: assert isinstance(aIndex,int) or isinstance(aIndex,float) and aIndex >=0,\ 'In get function; index must be an integer >=0 for vector view' t += 'scalar' else: # 'mview' in t assert len(aIndex) == 2 and (isinstance(aIndex,tuple) or isinstance(aIndex,list)) or \ 'scalar_mi' in vsipGetType(i)[1],'In get function; index not recognized for matrix.' if '_mi' in vsipGetType(aIndex)[1]: t += 'scalar_mi' else: assert isinstance(aIndex[0],int) and isinstance(aIndex[1],int),\ 'In get function; indices mut be an integer >= 0 for matrix view' assert aIndex[0]>=0 and aIndex[1] >=0,'In get function; indices mut be an integer >= 0 for matrix view' t += 'tuple' assert t in gSel,'Type <:%s:> not supported for __getitem__.'%s#should not get here i=aIndex; a=aView.vsip return eval(gSel[t]) def scalarVal(val): if 'cscalar' in vsipGetType(val)[1]: c=complex(val.r,val.i) return c elif isinstance(val,int): return int(val) elif isinstance(val,float) or isinstance(val,complex): return val elif 'scalar_mi' in vsipGetType(val)[1]: return {'row_index':val.r,'col_index':val.i} else: assert False,'__getitem__ does not recognize <:'+repr(type(val))+ ':>' if 'vview' in self.type and isinstance(index,int) and index >= 0: assert index < self.length,'Index out of bounds' val=vsipGet(self,index) return scalarVal(val) elif 'mview' in self.type and isinstance(index,int) and index >=0: assert index < self.collength,'Index out of bounds' return self.rowview(index) elif 'vview' in self.type and isinstance(index,slice): return self.subview(index) elif 'mview' in self.type and (len(index) == 2) and \ isinstance(index[0],int) and isinstance(index[1],int) \ and (index[0] >=0) and (index[1] >= 0): assert index[0] < self.collength and index[1] < self.rowlength,\ 'Index out of bound' i = (index[0],index[1]) val=vsipGet(self,i) return(scalarVal(val)) elif 'mview' in self.type and (len(index) == 2) and \ isinstance(index[0],slice) and isinstance(index[1],slice): return self.subview(index[0],index[1]) elif 'mview' in self.type and (len(index) == 2) and \ isinstance(index[0],slice) and isinstance(index[1],int): return self.subview(index[0],slice(index[1],index[1]+1,1)) elif 'mview' in self.type and (len(index) == 2) and \ isinstance(index[0],int) and isinstance(index[1],slice): return self.subview(slice(index[0],index[0]+1,1),index[1]) else: assert False,'Failed to parse index arguments in __getitem__' def __setitem__(self,i,value): def vsipVPut(aView,i,aValue): pSel = {'cvview_d':vsip_cvput_d, 'cvview_f':vsip_cvput_f, 'vview_d':vsip_vput_d, 'vview_f':vsip_vput_f, 'vview_i':vsip_vput_i, 'vview_si':vsip_vput_si, 'vview_vi':vsip_vput_vi, 'vview_uc':vsip_vput_uc, 'vview_bl':vsip_vput_bl, 'vview_mi':vsip_vput_mi} t=aView.type a=aView.vsip x=vsipScalar(t,aValue) return pSel[t](a,i,x) def vsipMPut(aView,r,c,aValue): pSel = {'cmview_d':vsip_cmput_d, 'cmview_f':vsip_cmput_f, 'mview_d':vsip_mput_d, 'mview_f':vsip_mput_f, 'mview_i':vsip_mput_i, 'mview_si':vsip_mput_si, 'mview_uc':vsip_mput_uc, 'mview_bl':vsip_mput_bl} t=aView.type a=aView.vsip x=vsipScalar(t,aValue) return pSel[t](a,r,c,x) # tValue = getType(value)[1] ## assert tValue == 'scalar' or tValue == 'View' or type(value) == numpy.ndarray,'Value type note recognized for __setitem__' if 'vview' in self.type: if isinstance(i,int) : assert i >= 0 and i < self.length,'Index out of bound' vsipVPut(self,i,value) elif isinstance(i,slice) and getType(value)[1] == 'scalar': self.subview(i).fill(vsipScalar(self.type,value)) elif isinstance(i,slice): copy(value,self.subview(i)) else: assert False,'Failed to recognize index for vector view' elif 'mview' in self.type and isinstance(i,tuple) and len(i) == 2: if isinstance(i[0],slice) and isinstance(i[1],slice): if getType(value)[1] == 'scalar': self.subview(i[0],i[1]).fill(vsipScalar(self.type,value)) else: copy(value,self.subview(i[0],i[1])) elif isinstance(i[0],slice) and isinstance(i[1],int): assert i[1] >= 0 and i[1] < self.collength,'Row index out of bound' if getType(value)[1] == 'scalar': self.subview(i[0],slice(i[1],i[1]+1,1)).fill(vsipScalar(self.type,value)) else: copy(value,self.subview(i[0],slice(i[1],i[1]+1,1))) elif (isinstance(i[0],int) and isinstance(i[1],slice)): if getType(value)[1] == 'scalar': self.subview(slice(i[0],i[0]+1,1),i[1]).fill(vsipScalar(self.type,value)) else: copy(value,self.subview(slice(i[0],i[0]+1,1),i[1])) elif (isinstance(i[0],int)) \ and (isinstance(i[1],int)): assert i[0] >= 0 and i[0] < self.collength and i[1] >=0 and i[1] < self.rowlength,\ 'Index out of bound' vsipMPut(self,i[0],i[1],value) else: assert False, 'Failed to recognize index for matrix view' else: assert False, 'Failed to parse argument list for __setitem__' def __delitem__(self,key): #drop index key assert isinstance(key,int) or isinstance(key,tuple),\ 'Key must be an integer index or a tuple pair of index integers' if isinstance(key,int): i = key if 'vview' in self.type: self[i:self.length-1] = self[i+1:self.length].copy # need new copy since overlap exists self.putlength(self.length-1) else: if 'COL' in self.major: self[:,i:self.rowlength-1]=self[:,i+1:self.rowlength].copy self.putrowlength(self.rowlength-1) else: self[i:self.collength-1,:]=self[i+1:self.collength,:].copy self.putcollength(self.collength-1) else: assert 'mview' in self.type,'A tuple key does not work for a vector view' assert len(key) == 2, 'Matrix view delete i,j has exactly two integer arguments' i=key[0] j=key[1] assert isinstance(i,int) and \ isinstance(j,int) , 'Integer indices required' del self.ROW[i] del self.COL[j] return self def __len__(self): t=self.type if 'mview' in self.type: return int(self.collength) else: return int(self.length) # Support functions # scalar is a place for the implementation to store a value which can be recovered from the view # not sure we need this. Currently not used. # EW, COL, ROW, MAT are indicators of how the view is to be used @property def EW(self): self.__major = 'EW' return self @property def COL(self): self.__major = 'COL' return self @property def ROW(self): self.__major = 'ROW' return self @property def MAT(self): self.__major = 'MAT' return self @property def major(self): """ This is an attribute that is used to determine certain functionality. The major attribue does NOT necessarily agree with the smallest stride direction. """ return self.__major def compactAttrib(self,b): """Function used for introspection of view objects. Output useful for creating attributes needed for creation of new views based on existing views. usage: attr=compactAttrib(b) attr is a tuple with three entries. attr[0] is the block type of self if b is 0 (see below for b is 1). attr[1] is number of elements in view attr[2] is an attribute (tuple) suitable for entry into bind. NOTE that b is a flag either 0 or 1 used to change the depth: if b is 1 (not 0) and self.block.type is real then attr[0] will be complex if b is 1 and self.block.type is complex then attr[0] will be real if self.block.type is not in Block.complexTypes then b is treated as 0 and the actual value passed in is ignored """ tdict={'block_f':'cblock_f','block_d':'cblock_d', 'cblock_f':'block_f','cblock_d':'block_d'} cdict={'real_d':'block_d','real_f':'block_f',\ 'imag_d':'block_d','imag_f':'block_f'} t = self.block.type if t in Block.tBlock and b != 0: t=tdict[t] elif t in cdict: t=cdict[t] if self.type in Block.vectorTypes: length=self.length attr=(0,1,self.length) elif self.type in Block.matrixTypes: length=self.rowlength * self.collength vsipAttr=GetAttrib(self).vsip if vsipAttr.col_stride < vsipAttr.row_stride: attr=(0,1,vsipAttr.col_length,vsipAttr.col_length,vsipAttr.row_length) else: attr=(0,vsipAttr.row_length,vsipAttr.col_length,1,vsipAttr.row_length) else: assert False,'Type <:%s:> not supported for compactAttrib. Should not be here. Implementation Error.'%self.type return (t,length,attr) @property def empty(self): """ A way to get a new view and data space of the same size. creates a new view, on a new block, of the same type and shape as the calling view. No copy or initialization takes place, so new view is empty, so-to-speak. """ attr=self.compactAttrib(0) b = self.block.otherBlock(attr[0],attr[1]) return b.bind(attr[2]) @property def otherEmpty(self): """ A way to get a new complex view and data space of the same size and precision as a real view. creates a new complex view on a new block with the same shape and precision as the calling view. No copy or initialization takes place, so new view is empty, so-to-speak. """ attr=self.compactAttrib(1) b = self.block.otherBlock(attr[0],attr[1]) return b.bind(attr[2]) @property # returns deep (new view and new block) copy of object including data def copy(self): """For vector or matrix A then B = A.copy will create a compact view B which is a copy of A. Note compact means the view exactly fits in the Block with unit stride in the major direction. The block is new and not the same block associated with A. This is an easy way to create a new data space for out of place operations. For instance: B = A.copy.sin will leave A alone, copy its elements to new view (and block) B and then do an in-place sine operation on B. """ return copy(self,self.empty) @property def copyrm(self): """ Same as copy method except if the view is a matrix it is created with unit stride along the rows. """ if 'mview' in self.type: attr=self.compactAttrib(0) b = self.block.otherBlock(attr[0],attr[1]) cl=self.collength; rl=self.rowlength o=0; rs=1;cs=rl newView = b.bind(o,cs,cl,rs,rl) copy(self,newView) return newView else: return self.copy @property def copycm(self): """ Same as copy method except if the view is a matrix it is created with unit stride along the Columns. """ if 'mview' in self.type: attr=self.compactAttrib(0) b = self.block.otherBlock(attr[0],attr[1]) cl=self.collength; rl=self.rowlength o=0; rs=cl;cs=1 newView = b.bind(o,cs,cl,rs,rl) copy(self,newView) return newView else: return self.copy @property # A way to get a new in-place view of the object def cloneview(self): f={'vview_f':vsip_vcloneview_f, 'vview_d':vsip_vcloneview_d, 'cvview_f':vsip_cvcloneview_f, 'cvview_d':vsip_cvcloneview_d, 'cmview_d':vsip_cmcloneview_d, 'cmview_f':vsip_cmcloneview_f, 'mview_bl':vsip_mcloneview_bl, 'mview_d':vsip_mcloneview_d, 'mview_f':vsip_mcloneview_f, 'mview_i':vsip_mcloneview_i, 'mview_si':vsip_mcloneview_si, 'mview_uc':vsip_mcloneview_uc, 'vview_bl':vsip_vcloneview_bl, 'vview_i':vsip_vcloneview_i, 'vview_mi':vsip_vcloneview_mi, 'vview_si':vsip_vcloneview_si, 'vview_uc':vsip_vcloneview_uc, 'vview_vi':vsip_vcloneview_vi} assert self.type in f,'Type <:%s:> not supported for cloneview. Implementation Error. Should not be here.'%self.type v = f[self.type](self.vsip) b=self.block return self.__newView(self.type,v,b) @property def clone(self): return self.cloneview def subview(self,*vals): """ Using Slices. 1)Note pyJvsip slice does not support negatives at this time: 2)For Vector slice=slice(first element, last element+1, stride) For Matrix first slice selects rows, second slice selects columns Beginning index of slice is included. Ending index is not. This is python like. slice1=slice(first row, last row + 1, stride through column) slice2=slice(first col, last col + 1, stride through row) Using an Index: For vector v (example): vs=v.subview(slice(2,len(v),1)) is the same as vs=v.subview(2) or vs=v.subview(2,len(v)-1) or vs=v.subview(2,len(v),1) and vs=v.subview(slice(2,8,2) is the same ags vs=v.subview(2,7,2) For matrix first pair is top left corner (row,col) For matrix second pair is bottom right corner (row,col) inclusive for matrix third pair is (stride through col, stride through row) given view aView then anotherView = aView.subview(vals[0],...) where: vals is index or index, end_index or index, end_index, stride for a vector vals is row_index,col_index or row_index,col_index, end_row_index, end_col_index or row_index,col_index, end_row_index, end_col_index, colstride, rowstride for a matrix anotherView is a view on the same block and data as aView. Offset, strides and lengths are defined on aView, not the block. Note that strides are along a dimension not through the block so that to select every other element of the parent view one would use a stride of two for both row and column. (This is Not how one works when setting strides through blocks.) """ def nlength(b,e,s): #begin(start),end(stop),step(step)=>b,e,s d=int(e)-int(b) chk=d%int(s) if chk == 0: return d//int(s) else: return (d//int(s)) + 1 def vAttr(attr,vals): o=int(attr.offset); l=int(attr.length); strd=int(attr.stride); if len(vals) == 1 and isinstance(vals[0],slice): slc=vals[0] # this is (start index, stop index, step) step=slc.step if step is None: step=1 #for VSIP we need start offset into block, new length, new stride start=slc.start if start is None: start=0 no=start * strd + o #new offset ns=step * strd #new stride stride stop = slc.stop if (stop is None): stop = l if (stop > l): stop = l nl=int(nlength(start,stop,step)) #new length elif len(vals) == 1 and isinstance(vals[0],int): return vAttr(attr,(slice(vals[0],l,1),)) elif len(vals) == 2 and isinstance(vals[0],int) \ and isinstance(vals[1],int): return vAttr(attr,(slice(vals[0],vals[l]+1,1),)) elif len(vals) == 3 and isinstance(vals[0],int) \ and isinstance(vals[1],int) \ and isinstance(vals[2],int): return vAttr(attr,(slice(vals[0],vals[1]+1,vals[2]),)) else: assert False,'Failed to parse subview arguments for vector subview.' return (no,ns,nl) def mAttr(attr,vals): o=int(attr.offset) cl=int(attr.col_length); cs=int(attr.col_stride) rl=int(attr.row_length); rs=int(attr.row_stride); if len(vals) == 2 and isinstance(vals[0],slice) and isinstance(vals[1],slice): rslc=vals[1]; cslc=vals[0] cstep=cslc.step;rstep=rslc.step; if cstep is None: cstep=1 if rstep is None: rstep=1 rstart=rslc.start;cstart=cslc.start if rstart is None: rstart = 0 if cstart is None: cstart = 0 no=rstart * rs + cstart * cs + o ncs=int(cstep * cs) stop = cslc.stop if stop is None: stop = cl if (stop > cl): stop = cl ncl= int(nlength(cstart,stop,cstep)) nrs=rstep * rs stop = rslc.stop if (stop is None): stop = rl if (stop > rl): stop = rl nrl= int(nlength(rstart,stop,rstep)) elif len(vals) == 2 and isinstance(vals[0],int) and isinstance(vals[1],int): return mAttr(attr,(slice(vals[0],cl,1),slice(vals[1],rl,1))) elif len(vals) == 4 and isinstance(vals[0],int) and isinstance(vals[1],int) \ and isinstance(vals[2],int) and isinstance(vals[3],int): return mAttr(attr,(slice(vals[0],vals[2]+1,1),slice(vals[1],vals[3]+1,1))) elif len(vals) == 6 and isinstance(vals[0],int) and isinstance(vals[1],int) \ and isinstance(vals[2],int) and isinstance(vals[3],int) \ and isinstance(vals[4],int) and isinstance(vals[5],int): return mAttr(attr,(slice(vals[0],vals[2]+1,vals[4]),slice(vals[1],vals[3]+1,vals[5]))) else: assert False,'Failed to parse arguments for matrix subview.' return (no,ncs,ncl,nrs,nrl) #enter subview here attr = vsipGetAttrib(self) if self.type in Block.vectorTypes: return self.block.bind(vAttr(attr,vals)) elif self.type in Block.matrixTypes: return self.block.bind(mAttr(attr,vals)) else: #should not be able to get here assert False, 'Implementation error. Object not supported for subview' def submatrix(self,rows,cols,*vals): """ Usage for matrix m: s = m.submatrix(rows, cols) or s = m.submatrix(rows,cols,'COL') where: rows is an integer; or a view of type vector index cols is an integer; or a view of type vector index The method submatrix will create a new data space and copy the indicated submatrix values into the new matrix. 1) The new submatrix is row major by default. If the last argument is a string which contains 'COL' then the submatrix will be column major. 2) If the index entries (rows,cols) are an integer then the submatrix will be the input matrix values minus the row and column crossing at (rows,cols). 3) If rows and cols are vectors of type vector index then the submatrix will of size (rows.length, cols.length) and will consist of the entries contained in the rows and columns indicated by the indices in the index vector. """ assert 'mview' in self.type,'Method submatrix only works on views of shape matrix.' if 'pyJvsip' in repr(rows): assert 'pyJvsip' in repr(cols),'If the rows parameter is a view then the cols parameter must also be a view' assert rows.type == 'vview_vi' and cols.type == 'vview_vi','Index vector for submatrix must be of type vview_vi.' else: assert (isinstance(rows,int))\ and (isinstance(cols,int) or isinstance(cols,lont)),'Indices to submatrix must both be integers or index vectors.' if isinstance(rows,int) and isinstance(cols,int): m=self.collength-1 n=self.rowlength-1 if len(vals) > 0 and 'COL' in vals[0]: retval=Block(self.block.type,m*n).bind(0,1,m,m,n) else: retval=Block(self.block.type,m*n).bind(0,n,m,1,n) retval[0:rows,0:cols]=self[0:rows,0:cols] retval[rows:m,0:cols]=self[rows+1:m+1,0:cols] retval[0:rows,cols:n]=self[0:rows,cols+1:n+1] retval[rows:m,cols:n]=self[rows+1:m+1,cols+1:n+1] return retval else: m = rows.length n = cols.length if len(vals) > 0 and 'COL' in vals[0]: retval=Block(self.block.type,m*n).bind(0,1,m,m,n) else: retval=Block(self.block.type,m*n).bind(0,n,m,1,n) for i in range(n): gather(self.colview(cols[i]),rows,retval.colview(i)) return retval @property def attrib(self): return GetAttrib(self).attrib def putattrib(self,attrib): vsipPutAttrib(self,attrib) @property def view(self): # Deprecated. May be removed in the future return self.__vsipView @property def vsip(self): return self.__vsipView @property def compact(self): """ Bool. Determine if view is compact with minimum strided distances for referenced data size. """ if self.type in Block.vectorTypes: if self.stride == 1: return True else: return False else:# must be matrix attrib=self.attrib if attrib['colstride'] == 1 and attrib['rowstride'] == attrib['collength']: return True elif attrib['rowstride'] == 1 and attrib['colstride'] == attrib['rowlength']: return True else: return False def colview(self,j): assert 'mview' in self.type,'Column view function only works on matrices.' f={'mview_i': vsip_mcolview_i, 'mview_si': vsip_mcolview_si, 'mview_uc': vsip_mcolview_uc, 'cmview_d': vsip_cmcolview_d, 'cmview_f': vsip_cmcolview_f, 'mview_d': vsip_mcolview_d, 'mview_f': vsip_mcolview_f, 'mview_bl': vsip_mcolview_bl} viewSel={'mview_i': 'vview_i', 'mview_si': 'vview_si', 'mview_uc': 'vview_uc', 'cmview_d': 'cvview_d', 'cmview_f': 'cvview_f', 'mview_d': 'vview_d', 'mview_f': 'vview_f', 'mview_bl': 'vview_bl'} assert self.type in f,'Type <:%s:> not a valid type for col view. Implementation Error. Should not be here.'%t v=f[self.type](self.vsip,j) t=viewSel[self.type] return self.__newView(t,v,self.block) def rowview(self,i): assert 'mview' in self.type,'Column view function only works on matrices.' f={'mview_i': vsip_mrowview_i, 'mview_si': vsip_mrowview_si, 'mview_uc': vsip_mrowview_uc, 'cmview_d': vsip_cmrowview_d, 'cmview_f': vsip_cmrowview_f, 'mview_d': vsip_mrowview_d, 'mview_f': vsip_mrowview_f, 'mview_bl': vsip_mrowview_bl} viewSel={'mview_i': 'vview_i', 'mview_si': 'vview_si', 'mview_uc': 'vview_uc', 'cmview_d': 'cvview_d', 'cmview_f': 'cvview_f', 'mview_d': 'vview_d', 'mview_f': 'vview_f', 'mview_bl': 'vview_bl'} assert self.type in f,'Type <:%s:> not a valid type for row view. Implementation Error. Should not be here.'%t v=f[self.type](self.vsip,i) t=viewSel[self.type] return self.__newView(t,v,self.block) def diagview(self,i): assert 'mview' in self.type,'Diagonal view method only works on views of shape matrix' assert isinstance(i,int) ,'The index value for diagview must be an integer' f = {'mview_i': vsip_mdiagview_i, 'mview_si': vsip_mdiagview_si, 'mview_uc': vsip_mdiagview_uc, 'cmview_d': vsip_cmdiagview_d, 'cmview_f': vsip_cmdiagview_f, 'mview_d': vsip_mdiagview_d, 'mview_bl': vsip_mdiagview_bl, 'mview_f': vsip_mdiagview_f} viewSel={'mview_i': 'vview_i', 'mview_si': 'vview_si', 'mview_uc': 'vview_uc', 'cmview_d': 'cvview_d', 'cmview_f': 'cvview_f', 'mview_d': 'vview_d', 'mview_f': 'vview_f', 'mview_bl': 'vview_bl'} assert self.type in f,'Should not be here. Implementation error' v = f[self.type](self.vsip,i) t=viewSel[self.type] return self.__newView(t,v,self.block) @property def transview(self): f={'mview_bl': vsip_mtransview_bl, 'mview_i': vsip_mtransview_i, 'mview_si': vsip_mtransview_si, 'mview_uc': vsip_mtransview_uc, 'cmview_d': vsip_cmtransview_d, 'cmview_f': vsip_cmtransview_f, 'mview_d': vsip_mtransview_d, 'mview_f': vsip_mtransview_f} t=self.type assert t in f,'Type <:%s:> not a valid type for trans view.'%t return self.__newView(t,f[t](self.vsip),self.block) @property def realview(self): v=self.__realview(self) v.__parent=self return v @property def imagview(self): v = self.__imagview(self) v.__parent=self return v @property def mrowview(self): """ The method mrowview is used to convert a vector into a matrix with row length equal self.length and column length equal one. No (direct) C VSIPL equivalent """ assert 'vview' in self.type,'The mrowview method only works with a vector view input' return self.block.bind(self.offset,1,1,self.stride,self.length) @property def mcolview(self): """ The method mcolview is used to convert a vector into a matrix with column length equal self.length and row length equal one. No (direct) C VSIPL equivalent """ assert 'vview' in self.type,'The mcolview method only works with a vector view input' return self.block.bind(self.offset,self.stride,self.length,1,1) #view attributes. @property def offset(self): f={'vview_f':vsip_vgetoffset_f, 'mview_f':vsip_mgetoffset_f, 'vview_d':vsip_vgetoffset_d, 'mview_d':vsip_mgetoffset_d, 'vview_i':vsip_vgetoffset_i, 'mview_i':vsip_mgetoffset_i, 'vview_si':vsip_vgetoffset_si, 'mview_si':vsip_mgetoffset_si, 'vview_uc':vsip_vgetoffset_uc, 'mview_uc':vsip_mgetoffset_uc, 'vview_vi':vsip_vgetoffset_vi, 'cvview_f':vsip_cvgetoffset_f, 'cmview_f':vsip_cmgetoffset_f, 'cvview_d':vsip_cvgetoffset_d, 'cmview_d':vsip_cmgetoffset_d, 'vview_mi':vsip_vgetoffset_mi, 'mview_bl':vsip_mgetoffset_bl, 'vview_bl':vsip_vgetoffset_bl} assert self.type in f,'View of type %s not supported. Implementation error. Should not be here'%self.type return int(f[self.type](self.vsip)) def putoffset(self,o): f={'vview_f':vsip_vputoffset_f, 'mview_f':vsip_mputoffset_f, 'vview_d':vsip_vputoffset_d, 'mview_d':vsip_mputoffset_d, 'vview_i':vsip_vputoffset_i, 'mview_i':vsip_mputoffset_i, 'vview_si':vsip_vputoffset_si, 'mview_si':vsip_mputoffset_si, 'vview_uc':vsip_vputoffset_uc, 'mview_uc':vsip_mputoffset_uc, 'vview_vi':vsip_vputoffset_vi, 'cvview_f':vsip_cvputoffset_f, 'cmview_f':vsip_cmputoffset_f, 'cvview_d':vsip_cvputoffset_d, 'cmview_d':vsip_cmputoffset_d, 'vview_mi':vsip_vputoffset_mi, 'mview_bl':vsip_mputoffset_bl, 'vview_bl':vsip_vputoffset_bl } assert self.type in f,'View of type %s not supported. Implementation error. Should not be here'%self.type assert isinstance(o,int), 'Offsets are integers' assert o >=0,'Offsets are >=0' assert o < self.block.length,'Offset off the end of the block' f[self.type](self.vsip,int(o)) return self @property def length(self): f={'vview_f':vsip_vgetlength_f, 'vview_d':vsip_vgetlength_d, 'vview_i':vsip_vgetlength_i, 'vview_si':vsip_vgetlength_si, 'vview_uc':vsip_vgetlength_uc, 'vview_bl':vsip_vgetlength_bl, 'vview_vi':vsip_vgetlength_vi, 'cvview_f':vsip_cvgetlength_f, 'cvview_d':vsip_cvgetlength_d, 'vview_mi':vsip_vgetlength_mi } assert self.type in f,'View of type %s not a vector view'%self.type return int(f[self.type](self.vsip)) def putlength(self,l): f={'vview_f':vsip_vputlength_f, 'vview_d':vsip_vputlength_d, 'vview_i':vsip_vputlength_i, 'vview_si':vsip_vputlength_si, 'vview_uc':vsip_vputlength_uc, 'vview_bl':vsip_vputlength_bl, 'vview_vi':vsip_vputlength_vi, 'cvview_f':vsip_cvputlength_f, 'cvview_d':vsip_cvputlength_d, 'vview_mi':vsip_vputlength_mi } assert self.type in f,'Not a compatible type for putlength.' assert isinstance(l,int),'Length is a positive integer' assert l >= 1,'Length is a positive (>=1) integer' assert (l-1) * self.stride + self.offset < self.block.length, 'Length to long. Exceeds block size' f[self.type](self.vsip,l) return self @property def stride(self): f={'vview_f':vsip_vgetstride_f, 'vview_d':vsip_vgetstride_d, 'vview_i':vsip_vgetstride_i, 'vview_si':vsip_vgetstride_si, 'vview_uc':vsip_vgetstride_uc, 'vview_bl':vsip_vgetstride_bl, 'vview_vi':vsip_vgetstride_vi, 'cvview_f':vsip_cvgetstride_f, 'cvview_d':vsip_cvgetstride_d, 'vview_mi':vsip_vgetstride_mi } assert 'vview' in self.type,'Method stride only works on views of shape vector.' assert self.type in f,'No Key for stride. Implementation error. Should not be here' return int(f[self.type](self.vsip)) def putstride(self,stride): f={'vview_f':vsip_vputstride_f, 'vview_d':vsip_vputstride_d, 'vview_i':vsip_vputstride_i, 'vview_si':vsip_vputstride_si, 'vview_uc':vsip_vputstride_uc, 'vview_bl':vsip_vputstride_bl, 'vview_vi':vsip_vputstride_vi, 'cvview_f':vsip_cvputstride_f, 'cvview_d':vsip_cvputstride_d, 'vview_mi':vsip_vputstride_mi } assert 'vview' in self.type,'Method putstride only works on views of shape vector.' assert self.type in f,'No Key for putstride. Implementation error. Should not be here' assert isinstance(stride,int),'Stride is an integer' assert (int(stride) * (self.length-1) + self.offset) < self.block.length,'Stride will cause view to exceed block data space' f[self.type](self.vsip,int(stride)) return self @property def rowlength(self): assert 'mview' in self.type,'Row length only works on views of type matrix' return int(GetAttrib(self).attrib['rowlength']) def putrowlength(self,length): assert 'mview' in self.type,'Put row length only works on views of type matrix' assert length > 0 and isinstance(length,int),'Length is an integer > 0' atr=self.attrib atr['rowlength']=length vsipPutAttrib(self,atr) return self @property def collength(self): assert 'mview' in self.type,'Column length only works on views of type matrix' return int(GetAttrib(self).attrib['collength']) def putcollength(self,length): assert 'mview' in self.type,'Put column length only works on views of type matrix' assert length > 0 and isinstance(length,int),'Length is an integer > 0' atr=self.attrib atr['collength']=length vsipPutAttrib(self,atr) return self @property def rowstride(self): assert 'mview' in self.type,'Row stride only works on views of type matrix' return int(GetAttrib(self).attrib['rowstride']) def putrowstride(self,stride): assert 'mview' in self.type,'Put row stride only works on views of type matrix' assert isinstance(stride,int) ,'stride is an integer' atr=self.attrib atr['rowstride']=stride vsipPutAttrib(self,atr) return self @property def colstride(self): assert 'mview' in self.type,'Column stride only works on views of type matrix' return int(GetAttrib(self).attrib['colstride']) def putcolstride(self,stride): assert 'mview' in self.type,'Put column stride only works on views of type matrix' assert isinstance(stride,int),'stride is an integer' atr=self.attrib atr['colstride']=stride vsipPutAttrib(self,atr) return self @property def block(self): return self.__pyBlock @property def type(self): return self.__type @property def size(self): if 'vview' in self.type: return (self.length,0) else: return (self.collength,self.rowlength) # window (data taper) functions def cheby(self,ripple): t=self.type wSel={'vview_f':'cheby_f', 'vview_d':'cheby_d'} assert t in wSel,'View type <:%s:> not supported for function cheby'%self.type copy(Block(wSel[self.type],self.length,ripple).w,self) return self def kaiser(self,beta): t=self.type wSel={'vview_f':'kaiser_f', 'vview_d':'kaiser_d'} assert t in wSel,'View of type <:%s:> does not support kaiser.'%self.type copy(Block(wSel[self.type],self.length,beta).w,self) return self @property def blackman(self): t=vsipGetType(self.vsip)[1] wSel={'vview_f':'blackman_f', 'vview_d':'blackman_d'} assert t in wSel,'View of type <:%s:> does not support blackman.'%self.type copy(Block(wSel[self.type],self.length).w,self) return self @property def hanning(self): t=vsipGetType(self.vsip)[1] wSel={'vview_f':'hanning_f', 'vview_d':'hanning_d'} assert t in wSel,'View of type <:%s:> does not support hanning.'%self.type copy(Block(wSel[self.type],self.length).w,self) return self # ### ### ### Element-wise methods # Elementary math functions @property def acos(self): acos(self,self) return self @property def asin(self): asin(self,self) return self @property def atan(self): return atan(self,self) # atan2 only supported by function call @property def cos(self): cos(self,self) return self @property def cosh(self): cosh(self,self) return self @property def exp(self): exp(self,self) return self @property def exp10(self): exp10(self,self) return self @property def log(self): log(self,self) return self @property def log10(self): log10(self,self) return self @property def sin(self): sin(self,self) return self @property def sinh(self): sinh(self,self) return self @property def sqrt(self): sqrt(self,self) return self @property def tan(self): tan(self,self) return self @property def tanh(self): tanh(self,self) return self # ### Unary Operations @property def arg(self): """ Done out-of-place Input vector is of type complex Output vector of type real created by arg method and returned. """ attr=self.compactAttrib(1) out=self.block.otherBlock(attr[0],attr[1]).bind(attr[2]) return arg(self,out) @property def conj(self): """ Done In Place. For out of place use self.copy.conj. """ if self.type in ['vview_d','vview_f','mview_d','mview_f']: return self else: return conj(self,self) def jmul(self,inpt): """ Method jmul creates a view for output; regardless of input. Works for float precision. Done out-of-place Usage out=self.jmul(inpt) """ t=self.type+inpt.type f={'vview_fvview_f':'vview_f','cvview_fcvview_f':'cvview_f', 'cvview_fvview_f':'cvview_f','vview_fcvview_f':'cvview_f', 'vview_dvview_d':'vview_d','cvview_dcvview_d':'cvview_d', 'cvview_dvview_d':'cvview_d','vview_dcvview_d':'cvview_d', 'mview_fmview_f':'mview_f','cmview_fcvview_f':'cmview_f', 'cmview_fmview_f':'cmview_f','mview_fcmview_f':'cmview_f', 'mview_dmview_d':'mview_d','cmview_dcvview_d':'cmview_d', 'cmview_dmview_d':'cmview_d','mview_dcmview_d':'cmview_d'} assert t in f,'type <:%s:> not supported by jmul'%t if 'vview' in t: assert self.length == inpt.length, 'Vector lengths must be equal in jmul' out=create(f[t],self.length).fill(0.0) else: assert self.rowlength == inpt.rowlength and self.collength == inpt.collength,\ 'Matrix sizes must be the same' out=create(f[t],self.collength,self.rowlength).fill(0.0) if t in ['cvview_fcvview_f','cvview_dcvview_d','cmview_fcmview_f','cmview_dcmview_d']: return jmul(self,inpt,out) elif 'c' in inpt.type: conj(inpt,out) return mul(self,out,out) elif 'c' in self.type: return mul(inpt,self,out) else: mul(inpt,self,out) return out @property def cumsum(self): """ Done In-Place If Matrix major flag should be set for direction of cumulative sum. If a copy is done to preserve calling view place major after copy Ex a.COL.cumsum b = a.copy.COL.cumsum """ return cumsum(self,self) @property def euler(self): """ Not done In-Place Input vector of type real Method euler creates and returns a new output vector of type complex """ attr=self.compactAttrib(1) out=self.block.otherBlock(attr[0],attr[1]).bind(attr[2]) return euler(self,out) @property def mag(self): """ View property mag is an out-of-place operation Usage: y=x.mag Where: x is a view object y is a view object of type real and precision and size the same as x Note: y is created internal to the property. If x is real then y.type is the same as x.type. If x is complex then y is real. """ f = ['cmview_d', 'cmview_f', 'cvview_d', 'cvview_f', 'mview_d', 'mview_f', 'vview_d', 'vview_f', 'vview_i', 'vview_si'] assert self.type in f, 'Type <:%s:> not recognized for mag'%self.type if 'cmview' in self.type or 'cvview' in self.type: attr=self.compactAttrib(1) else: attr=self.compactAttrib(0) out=self.block.otherBlock(attr[0],attr[1]).bind(attr[2]) return mag(self,out) @property def cmagsq(self): """ View property magsq is an out-of-place operation Usage: y=x.magsq Where: x is a complex view object y is a view object of type real and precision and size the same as x Note: y is created internal to the property. """ f=['cvview_f','cvview_d','cmview_f','cmview_d'] assert self.type in f, 'Type <:%s:> not recognized for magsq'%self.type attr=self.compactAttrib(1) out=self.block.otherBlock(attr[0],attr[1]).bind(attr[2]) return cmagsq(self,out) # modulate @property def neg(self): """ Done In place Returns a convenience copy. For out of place, for view x, do y = x.copy.neg """ return neg(self,self) @property def recip(self): return recip(self,self) @property def rsqrt(self): return rsqrt(self,self) @property def sq(self): return sq(self,self) @property def sumval(self): """returns a scalar """ f={'cmview_d':vsip_cmsumval_d,'cvview_d':vsip_cvsumval_d,'cmview_f':vsip_cmsumval_f, 'cvview_f':vsip_cvsumval_f,'mview_d':vsip_msumval_d,'vview_d':vsip_vsumval_d, 'mview_f':vsip_msumval_f,'vview_f':vsip_vsumval_f,'vview_i':vsip_vsumval_i, 'vview_si':vsip_vsumval_si,'vview_uc':vsip_vsumval_uc,'mview_bl':vsip_msumval_bl, 'vview_bl':vsip_vsumval_bl} assert self.type in f, 'Type <:%s:> not recognized for sumval'%self.type if 'cmview' in self.type or 'cvview' in self.type: x=f[self.type](self.vsip) return complex(x.r,x.i) elif '_f' in self.type or '_d' in self.type: return f[self.type](self.vsip) else: return int(f[self.type](self.vsip)) @property def sumsqval(self): """ Returns a scalar equal to the sum of the squares of the view elements. """ f={'mview_d':vsip_msumsqval_d, 'vview_d':vsip_vsumsqval_d, 'mview_f':vsip_msumsqval_f, 'vview_f':vsip_vsumsqval_f} assert self.type in f,'Type <:%s:> not recognized for sumsqval'%self.type return f[self.type](self.vsip) # ### Binary # add, mull, div, sub incorporated into python built in __add__, __div__, __sub__, etc. def mmul(self,other): #vector-matrix elementwise multiply by row or col """ Input matrix is overwritten by the operation. mmul(A) expects the calling view to be of type float vector and A to be of the same precision and type float matrix. Matrix A is returned as a convenience. Note that views have a major attribute. If the calling view is set to COL then the calling vector multiplies A elementwise by COL, otherwise it is multiplied by ROW Note lengths must be conformant. If one is unsure of the state of the major attribute it should be set For instance v.ROW.mmul(A) or v.COL.mmul(A) Done in place. v.mmul(A) returns the result in A. B = v.mmul(A.copy.COL) returns the result in a new matrix. """ return vmmul(self,other,other) @property def meansqval(self): """ returns scalar value """ f={'cmview_d':vsip_cmmeansqval_d,'cvview_d':vsip_cvmeansqval_d,'cmview_f':vsip_cmmeansqval_f, 'cvview_f':vsip_cvmeansqval_f,'mview_d':vsip_mmeansqval_d,'vview_d':vsip_vmeansqval_d, 'mview_f':vsip_mmeansqval_f,'vview_f':vsip_vmeansqval_f} assert self.type in f, 'Type <:%s:> not recognized for meansqval'%self.type return f[self.type](self.vsip) @property def meanval(self): """ returns scalar value """ f={'cmview_d':vsip_cmmeanval_d,'cvview_d':vsip_cvmeanval_d,'cmview_f':vsip_cmmeanval_f, 'cvview_f':vsip_cvmeanval_f,'mview_d':vsip_mmeanval_d,'vview_d':vsip_vmeanval_d, 'mview_f':vsip_mmeanval_f,'vview_f':vsip_vmeanval_f} assert self.type in f, 'Type <:%s:> not recognized for meanval'%self.type return f[self.type](self.vsip) #logical operations @property def alltrue(self): f={'mview_bl':vsip_malltrue_bl, 'vview_bl':vsip_valltrue_bl} t=self.type if t in f: return 1 == f[t](self.vsip) else: print('Type ' + t + ' not a defined type for alltrue') @property def anytrue(self): f={'mview_bl':vsip_manytrue_bl, 'vview_bl':vsip_vanytrue_bl} t=self.type if t in f: return 1 == f[t](self.vsip) else: print('View type must be boolean for alltrue') def leq(self,other): """ Logical Equal Usage: b=x.leq(y) y may be of type x.type or a scalar. b is a boolean. if x[i] == y[i] the b[i]=1 (true) else 0 (false) if y is a scalar if x[i] == y then b[i] = 1 Note this works for a matrix also. The index changes to (i,j) """ if isinstance(other,complex) or 'cscalar' in repr(other): print('complex scalars not supported at this time for leq') return t0=getType(other) if 'scalar' in t0[1]: t = self.type+t0[1] else: t=self.type+other.type if 'mview' in self.type: m=self.collength n=self.rowlength out=create('mview_bl',m,n) else: #must be vector out=create('vview_bl',self.length) f={'mview_dmview_d':vsip_mleq_d, 'mview_fmview_f':vsip_mleq_f, 'vview_dvview_d':vsip_vleq_d, 'vview_fvview_f':vsip_vleq_f, 'vview_ivview_i':vsip_vleq_i, 'vview_sivview_si':vsip_vleq_si, 'vview_ucvview_uc':vsip_vleq_uc } fs={'vview_fscalar':vsip_svleq_f, 'vview_dscalar':vsip_svleq_d} if t in f: f[t](self.vsip,other.vsip,out.vsip) return out elif t in fs: fs[t](other,self.vsip,out.vsip) return out else: print('Argument type <:'+t+':> not recognized for leq') return def lge(self,input): """ Logical Greater Than or Equal Usage: b=x.lge(y) y may be of type x.type or a scalar. b is a boolean. if x[i] >= y[i] the b[i]=1 (true) else 0 (false) if y is a scalar if x[i] >= y then b[i] = 1 Note this works for a matrix also. The index changes to (i,j) Note this is not equivalent to a C VSIP vsip_svlge_p for the scalar case as the scalar is on the wrong side of the test. """ t0=getType(input) if 'mview' in self.type: m=self.collength n=self.rowlength out=create('mview_bl',m,n) else: #must be vector out=create('vview_bl',self.length) if 'scalar' in t0[1]: if 'mview' in self.type: other = create(self.type,1,1).fill(input) attr=self.attrib attr['offset']=0 attr['rowstride']=0; attr['colstride']=0 other.putattrib(attr) else: attr=self.attrib other = create(self.type,1).fill(input) attr['offset']=0;attr['stride']=0;other.putattrib(attr) else: other=input t=self.type+other.type f={'mview_dmview_d':vsip_mlge_d, 'mview_fmview_f':vsip_mlge_f, 'vview_dvview_d':vsip_vlge_d, 'vview_fvview_f':vsip_vlge_f, 'vview_ivview_i':vsip_vlge_i, 'vview_sivview_si':vsip_vlge_si, 'vview_ucvview_uc':vsip_vlge_uc} if t in f: f[t](self.vsip,other.vsip,out.vsip) return out else: print('Argument type <:'+t+':> not recognized for lge') return def lgt(self,input): """ Logical Greater Than Usage: b=x.lgt(y) y may be of type x.type or a scalar. b is a boolean. if x[i] > y[i] the b[i]=1 (true) else 0 (false) if y is a scalar if x[i] > y then b[i] = 1 Note this works for a matrix also. The index changes to (i,j) Note this is not equivalent to a C VSIP vsip_svlgt_p for the scalar case as the scalar is on the wrong side of the test. """ t0=getType(input) if 'mview' in self.type: m=self.collength n=self.rowlength out=create('mview_bl',m,n) else: #must be vector out=create('vview_bl',self.length) if 'scalar' in t0[1]: if 'mview' in self.type: other = create(self.type,1,1).fill(input) attr=self.attrib attr['offset']=0 attr['rowstride']=0; attr['colstride']=0 other.putattrib(attr) else: attr=self.attrib other = create(self.type,1).fill(input) attr['offset']=0;attr['stride']=0;other.putattrib(attr) else: other=input t=self.type+other.type f={'mview_dmview_d':vsip_mlgt_d, 'mview_fmview_f':vsip_mlgt_f, 'vview_dvview_d':vsip_vlgt_d, 'vview_fvview_f':vsip_vlgt_f, 'vview_ivview_i':vsip_vlgt_i, 'vview_sivview_si':vsip_vlgt_si, 'vview_ucvview_uc':vsip_vlgt_uc} if t in f: f[t](self.vsip,other.vsip,out.vsip) return out else: print('Argument type <:'+t+':> not recognized for lgt') return def lle(self,input): """ Logical less than or equal Usage: b=x.lle(y) y may be of type x.type or a scalar. b is a boolean. If x[i] <= y[i] then b[i]=1 (true) else 0 (false) If y is a scalar if x[i] <= y then b[i] = 1 Note this works for a matrix also. The index changes to (i,j) Note this is not equivalent to a C VSIP vsip_svlle_p for the scalar case as the scalar is on the wrong side of the test. """ t0=getType(input) if 'mview' in self.type: m=self.collength n=self.rowlength out=create('mview_bl',m,n) else: #must be vector out=create('vview_bl',self.length) if 'scalar' in t0[1]: if 'mview' in self.type: other = create(self.type,1,1).fill(input) attr=self.attrib attr['offset']=0 attr['rowstride']=0; attr['colstride']=0 other.putattrib(attr) else: attr=self.attrib other = create(self.type,1).fill(input) attr['offset']=0;attr['stride']=0;other.putattrib(attr) else: other=input f={'mview_dmview_d':vsip_mlle_d, 'mview_fmview_f':vsip_mlle_f, 'vview_dvview_d':vsip_vlle_d, 'vview_fvview_f':vsip_vlle_f, 'vview_ivview_i':vsip_vlle_i, 'vview_sivview_si':vsip_vlle_si, 'vview_ucvview_uc':vsip_vlle_uc} t=self.type+other.type if t in f: f[t](self.vsip,other.vsip,out.vsip) return out else: print('Argument type <:'+t+':> not recognized for lle') return def llt(self,input): """ Logical less than Usage: b=x.llt(y) y may be of type x.type or a scalar. b is a boolean. If x[i] < y[i] then b[i]=1 (true) else 0 (false) If y is a scalar if x[i] < y then b[i] = 1 Note this works for a matrix also. The index changes to (i,j) Note this is not equivalent to a C VSIP vsip_svllt_p for the scalar case as the scalar is on the wrong side of the test. """ t0=getType(input) if 'mview' in self.type: m=self.collength n=self.rowlength out=create('mview_bl',m,n) else: #must be vector out=create('vview_bl',self.length) if 'scalar' in t0[1]: if 'mview' in self.type: other = create(self.type,1,1).fill(input) attr=self.attrib attr['offset']=0 attr['rowstride']=0; attr['colstride']=0 other.putattrib(attr) else: attr=self.attrib other = create(self.type,1).fill(input) attr['offset']=0;attr['stride']=0;other.putattrib(attr) else: other=input t=self.type+other.type f={'mview_dmview_d':vsip_mllt_d, 'mview_fmview_f':vsip_mllt_f, 'vview_dvview_d':vsip_vllt_d, 'vview_fvview_f':vsip_vllt_f, 'vview_ivview_i':vsip_vllt_i, 'vview_sivview_si':vsip_vllt_si, 'vview_ucvview_uc':vsip_vllt_uc} if t in f: f[t](self.vsip,other.vsip,out.vsip) return out else: print('Argument type <:'+t+':> not recognized for llt') return def lne(self,other): """ Logical Not Equal Usage: b=x.lne(y) y may be of type x.type or a scalar. b is a boolean. if x[i] != y[i] the b[i]=1 (true) else 0 (false) if y is a scalar if x[i] != y then b[i] = 1 Note this works for a matrix also. The index changes to (i,j) """ if 'mview' in self.type: m=self.collength n=self.rowlength out=create('mview_bl',m,n) else: #must be vector out=create('vview_bl',self.length) f={'mview_dmview_d':vsip_mlne_d, 'mview_fmview_f':vsip_mlne_f, 'vview_dvview_d':vsip_vlne_d, 'vview_fvview_f':vsip_vlne_f, 'vview_ivview_i':vsip_vlne_i, 'vview_sivview_si':vsip_vlne_si, 'vview_ucvview_uc':vsip_vlne_uc} t=self.type+other.type if t in f: f[t](self.vsip,other.vsip,out.vsip) return out else: print('Argument type <:'+t+':> not recognized for lne') return # Selection Operations @property def indexbool(self): if 'mview_bl' in self.type: out = create('vview_mi',self.rowlength*self.collength) elif 'vview_bl' in self.type: out = create('vview_vi',self.length) else: print('Method indexbool is only defined for views of type mview_bl or vview_bl') return if self.anytrue: f={'mview_bl':vsip_mindexbool,'vview_bl':vsip_vindexbool} f[self.type](self.vsip,out.vsip) return out else: print('Method indexbool should only be called if there is at least one true entry') return def indxFill(self,indx,alpha): if 'mview' in self.type: lnth = self.rowlength * self.collength x=create(self.type,1,1) x[0,0]=alpha x.putrowlength(self.rowlength); x.putcollength(self.collength) x.putrowstride(0);x.putcolstride(0) else: lnth = self.length x=create(self.type,1) x[0]=alpha x.putlength(self.length) x.putstride(0) x.scatter(self,indx) return self @property def maxvalindx(self): """ This method returns the index of the first maximum value found for views of depth real. See cmaxmgsqvalindx for views of depth complex. """ f={'mview_d':'vsip_mmaxval_d(self.vsip,idx)', 'vview_d':'vsip_vmaxval_d(self.vsip,idx)', 'mview_f':'vsip_mmaxval_f(self.vsip,idx)', 'vview_f':'vsip_vmaxval_f(self.vsip,idx)', 'mview_i':'vsip_mmaxval_i(self.vsip,idx)', 'vview_i':'vsip_vmaxval_i(self.vsip,idx)', 'mview_si':'vsip_mmaxval_si(self.vsip,idx)', 'vview_si':'vsip_vmaxval_si(self.vsip,idx)', 'vview_vi':'vsip_vmaxval_vi(self.vsip.idx)'} if self.type in f: if 'mview' in self.type: idx=vsip_scalar_mi() eval(f[self.type]) return (int(idx.r),int(idx.c)) else: idx=vindexptr() eval(f[self.type]) retval=int(vindexptrToInt(idx)) vindexfree(idx) return retval else: print('Type <:'+self.type+':> not supported by maxval') return @property def maxval(self): """ This method returns the maximum value found for views of depth real. For views of depth complex see cmaxmgsqval. """ f={'mview_d':'vsip_mmaxval_d(self.vsip,None)', 'vview_d':'vsip_vmaxval_d(self.vsip,None)', 'mview_f':'vsip_mmaxval_f(self.vsip,None)', 'vview_f':'vsip_vmaxval_f(self.vsip,None)', 'mview_i':'vsip_mmaxval_i(self.vsip,None)', 'vview_i':'vsip_vmaxval_i(self.vsip,None)', 'mview_si':'vsip_mmaxval_si(self.vsip,None)', 'vview_si':'vsip_vmaxval_si(self.vsip,None)', 'vview_vi':'vsip_vmaxval_vi(self.vsip,None)'} if self.type in f: return eval(f[self.type]) else: print('Type <:'+self.type+':> not supported by maxval') return @property def maxmgvalindx(self): """ This method returns the index of the first maximum value found for views of depth real. For views of depth complex see cmaxmgsqvalindx. """ f={'mview_d':'vsip_mmaxmgval_d(self.vsip,idx)', 'vview_d':'vsip_vmaxmgval_d(self.vsip,idx)', 'mview_f':'vsip_mmaxmgval_f(self.vsip,idx)', 'vview_f':'vsip_vmaxmgval_f(self.vsip,idx)'} if self.type in f: if 'mview' in self.type: idx=vsip_scalar_mi() eval(f[self.type]) return (int(idx.r),int(idx.c)) else: idx=vindexptr() eval(f[self.type]) retval=int(vindexptrToInt(idx)) vindexfree(idx) return retval else: print('Type <:'+self.type+':> not supported by maxmgvalindx') return @property def maxmgval(self): """ This method returns the first maximum value found. """ f={'mview_d':'vsip_mmaxmgval_d(self.vsip,None)', 'vview_d':'vsip_vmaxmgval_d(self.vsip,None)', 'mview_f':'vsip_mmaxmgval_f(self.vsip,None)', 'vview_f':'vsip_vmaxmgval_f(self.vsip,None)'} if self.type in f: return eval(f[self.type]) else: print('Type <:'+self.type+':> not supported by maxmgval') return @property def cmaxmgsqvalindx(self): """ This method returns the index of the first maximum complex magnitude squared value found. For views of depth real see maxmgvalindx. """ f={'cmview_d':'vsip_mcmaxmgsqval_d(self.vsip,idx)', 'cvview_d':'vsip_vcmaxmgsqval_d(self.vsip,idx)', 'cmview_f':'vsip_mcmaxmgsqval_f(self.vsip,idx)', 'cvview_f':'vsip_vcmaxmgsqval_f(self.vsip,idx)'} if self.type in f: if 'mview' in self.type: idx=vsip_scalar_mi() eval(f[self.type]) return (int(idx.r),int(idx.c)) else: idx=vindexptr() eval(f[self.type]) retval=int(vindexptrToInt(idx)) vindexfree(idx) return retval else: print('Type <:'+self.type+':> not supported by maxmgsqvalindx') return @property def cmaxmgsqval(self): """ This method returns the maximum complex magnitude squared value found. It is only defined for views of depth complex. See also maxmgval for views of depth real. """ f={'cmview_d':'vsip_mcmaxmgsqval_d(self.vsip,None)', 'cvview_d':'vsip_vcmaxmgsqval_d(self.vsip,None)', 'cmview_f':'vsip_mcmaxmgsqval_f(self.vsip,None)', 'cvview_f':'vsip_vcmaxmgsqval_f(self.vsip,None)'} if self.type in f: return eval(f[self.type]) else: print('Type <:'+self.type+':> not supported by cmaxmgsqval') return @property def minvalindx(self): """ For views of depth real this method returns the index of the first minimum value found. For views of depth complex see cminmgsqvalindx. """ f={'mview_d':'vsip_mminval_d(self.vsip,idx)', 'vview_d':'vsip_vminval_d(self.vsip,idx)', 'mview_f':'vsip_mminval_f(self.vsip,idx)', 'vview_f':'vsip_vminval_f(self.vsip,idx)', 'mview_i':'vsip_mminval_i(self.vsip,idx)', 'vview_i':'vsip_vminval_i(self.vsip,idx)', 'mview_si':'vsip_mminval_si(self.vsip,idx)', 'vview_si':'vsip_vminval_si(self.vsip,idx)', 'vview_vi':'vsip_vminval_vi(self.vsip,idx)'} if self.type in f: if 'mview' in self.type: idx=vsip_scalar_mi() eval(f[self.type]) return (int(idx.r),int(idx.c)) else: idx=vindexptr() eval(f[self.type]) retval=int(vindexptrToInt(idx)) vindexfree(idx) return retval else: print('Type <:'+self.type+':> not supported by minval') return @property def minval(self): """ For views of depth real this method returns the minimum value found. For views of depth complex see cminmgsqval. """ f={'mview_d':'vsip_mminval_d(self.vsip,None)', 'vview_d':'vsip_vminval_d(self.vsip,None)', 'mview_f':'vsip_mminval_f(self.vsip,None)', 'vview_f':'vsip_vminval_f(self.vsip,None)', 'mview_i':'vsip_mminval_i(self.vsip,None)', 'vview_i':'vsip_vminval_i(self.vsip,None)', 'mview_si':'vsip_mminval_si(self.vsip,None)', 'vview_si':'vsip_vminval_si(self.vsip,None)', 'vview_vi':'vsip_vminval_vi(self.vsip,None)'} if self.type in f: return eval(f[self.type]) else: print('Type <:'+self.type+':> not supported by minval') return @property def minmgvalindx(self): """ For views of depth real this method returns the index of the first minimum value found. For views of depth complex see cminmgsqvalindx. """ f={'mview_d':'vsip_mminmgval_d(self.vsip,idx)', 'vview_d':'vsip_vminmgval_d(self.vsip,idx)', 'mview_f':'vsip_mminmgval_f(self.vsip,idx)', 'vview_f':'vsip_vminmgval_f(self.vsip,idx)'} if self.type in f: if 'mview' in self.type: idx=vsip_scalar_mi() eval(f[self.type]) return (int(idx.r),int(idx.c)) else: idx=vindexptr() eval(f[self.type]) retval=int(vindexptrToInt(idx)) int(vindexfree(idx)) return retval else: print('Type <:'+self.type+':> not supported by minmgvalindx') return @property def minmgval(self): """ This method returns the first minimum value found. """ f={'mview_d':'vsip_mminmgval_d(self.vsip,None)', 'vview_d':'vsip_vminmgval_d(self.vsip,None)', 'mview_f':'vsip_mminmgval_f(self.vsip,None)', 'vview_f':'vsip_vminmgval_f(self.vsip,None)'} if self.type in f: return eval(f[self.type]) else: print('Type <:'+self.type+':> not supported by minmgval') return @property def cminmgsqvalindx(self): """ This method returns the index of the first minimum complex magnitude squared value found. For depths of type real use minmgvalindx or minmvalindx. """ f={'cmview_d':'vsip_mcminmgsqval_d(self.vsip,idx)', 'cvview_d':'vsip_vcminmgsqval_d(self.vsip,idx)', 'cmview_f':'vsip_mcminmgsqval_f(self.vsip,idx)', 'cvview_f':'vsip_vcminmgsqval_f(self.vsip,idx)'} if self.type in f: if 'mview' in self.type: idx=vsip_scalar_mi() eval(f[self.type]) return (int(idx.r),int(idx.c)) else: idx=vindexptr() eval(f[self.type]) retval=int(vindexptrToInt(idx)) vindexfree(idx) return retval else: print('Type <:'+self.type+':> not supported by minmgsqvalindx') return @property def cminmgsqval(self): """ This method returns the minimum complex magnitude squared value found. For views of depth real se minmgval or minval. """ f={'cmview_d':'vsip_mcminmgsqval_d(self.vsip,None)', 'cvview_d':'vsip_vcminmgsqval_d(self.vsip,None)', 'cmview_f':'vsip_mcminmgsqval_f(self.vsip,None)', 'cvview_f':'vsip_vcminmgsqval_f(self.vsip,None)'} if self.type in f: return eval(f[self.type]) else: print('Type <:'+self.type+':> not supported by minmgsqval') return #Bitwise and Boolean Logical Operators #use bb at fron to avoid conflicts def bband(self,other): """ bitwise/boolean and """ f={'mview_i':vsip_mand_i, 'mview_si':vsip_mand_si, 'vview_bl':vsip_vand_bl, 'vview_i':vsip_vand_i, 'vview_si':vsip_vand_si, 'vview_uc':vsip_vand_uc} sptd=['mview_i','mview_si','vview_bl','vview_i','vview_si','vview_uc'] assert self.length is other.length assert self.type in other.type assert self.type in sptd out=self.empty f[self.type](self.vsip,other.vsip,out.vsip) return out def bbnot(self,other): """ bitwise/boolean and """ f={'mview_i':vsip_mnot_i, 'mview_si':vsip_mnot_si, 'vview_bl':vsip_vnot_bl, 'vview_i':vsip_vnot_i, 'vview_si':vsip_vnot_si, 'vview_uc':vsip_vnot_uc} sptd=['vview_bl','vview_i','vview_si','vview_uc'] assert self.length is other.length assert self.type in other.type assert self.type in sptd out=self.empty f[self.type](self.vsip,other.vsip,out.vsip) return out def bbor(self,other): """ bitwise/boolean and """ f={'mview_i':vsip_mor_i, 'mview_si':vsip_mor_si, 'vview_bl':vsip_vor_bl, 'vview_i':vsip_vor_i, 'vview_si':vsip_vor_si, 'vview_uc':vsip_vor_uc} sptd=['vview_bl','vview_i','vview_si','vview_uc'] assert self.length is other.length assert self.type in other.type assert self.type in sptd out=self.empty f[self.type](self.vsip,other.vsip,out.vsip) return out def bbxor(self,other): """ bitwise/boolean and """ f={'mview_i':vsip_mxor_i, 'mview_si':vsip_mxor_si, 'vview_bl':vsip_vxor_bl, 'vview_i':vsip_vxor_i, 'vview_si':vsip_vxor_si, 'vview_uc':vsip_vxor_uc} sptd=['vview_bl','vview_i','vview_si','vview_uc'] assert self.length is other.length assert self.type in other.type assert self.type in sptd out=self.empty f[self.type](self.vsip,other.vsip,out.vsip) return out # data generators def ramp(self,start,increment): f={'vview_f':vsip_vramp_f, 'vview_d':vsip_vramp_d, 'vview_i':vsip_vramp_i, 'vview_si':vsip_vramp_si, 'vview_uc':vsip_vramp_uc, 'vview_vi':vsip_vramp_vi} extended = ['cvview_f','cvview_d'] t=self.type assert t in f or t in extended,'Type <:%s:> not support for ramp' if t in f: f[t](start,increment,self.vsip) else: self.fill(0) tmp=self.realview tmp.ramp(start,increment) return self def fill(self,aScalar): # does not support _bl def nConv(n): #convert a string to a number assert type(n) == str,'Input not a string. Function nConv converts a string to a float, integer, or complex' chk='0123456789-+j.' if 'j' in n:# must be complex assert all(c in chk for c in n),'Only numbers, decimal, and letter j are allowed in complex.' return(eval(n)) elif '.' in n:# must be a float return float(n) else: #must be an int return int(n) def fillList(aView,aList): if 'mview' in aView.type: m = len(aList) assert m <= aView.collength,'Data exceeds capacity of matrix view.' for i in range(m): l=aList[i] assert type(l) == list,'For matrix list input must be list of lists' fillList(aView.rowview(i),l) else: n = len(aList) assert n <= aView.length,'Data exceeds capacity of view' for j in range(n): aView[j] = aList[j] def stringToList(aString): if ';' in aString:#must be a matrix string return [[nConv((i)) for i in item.split(',')] for item in aString.split(';')] else:#must be a vector string return [nConv(item) for item in aString.split(',')] f={'cmview_d':vsip_cmfill_d, 'cmview_f':vsip_cmfill_f, 'cvview_d':vsip_cvfill_d, 'cvview_f':vsip_cvfill_f, 'mview_d':vsip_mfill_d, 'mview_f':vsip_mfill_f, 'mview_i':vsip_mfill_i, 'mview_si':vsip_mfill_si, 'mview_uc':vsip_mfill_uc, 'vview_d':vsip_vfill_d, 'vview_f':vsip_vfill_f, 'vview_i':vsip_vfill_i, 'vview_si':vsip_vfill_si, 'vview_uc':vsip_vfill_uc, 'vview_vi':vsip_vfill_vi} assert self.type in f,'Type <:%s:> not recognized.'%self.type if type(aScalar) == str: self.fill(stringToList(aScalar)) elif type(aScalar) == list: fillList(self,aScalar) else:#must be some sort of scalar val = vsipScalar(self.type,aScalar) f[self.type](val,self.vsip) return self def randn(self,seed): gen=Rand('PRNG',seed) gen.randn(self) return self def randu(self,seed): gen=Rand('PRNG',seed) gen.randu(self) return self @property def identity(self): f=['cmview_d','cmview_f','mview_d','mview_f','mview_i','mview_si'] assert self.type in f,'View of type <:'+self.type+':> not supported by identity' self.fill(0) self.diagview(0).fill(1) return self # Manipulation # Not supported by view method # vsip_scmplx_p # vsip_srect_p # vsip_spolar_p # vsip_dswap_p # ### ### # supported by view method # vsip_dsgather_p def gather(self,indx,*vars): """ Usage: self.gather(indx,other) or self.gather(indx) This function gathers self into other governed by indx. If other is not provided the function creates one. View other is returned as a convienience """ ot={'cmview_f':'cvview_f','cmview_d':'cvview_d','mview_f':'vview_f', 'mview_d':'vview_d','cvview_f':'cvview_f','cvview_d':'cvview_d', 'vview_f':'vview_f','vview_d':'vview_d','vview_i':'vview_i', 'vview_si':'vview_si','vview_uc':'vview_uc','vview_mi':'vview_mi', 'vview_vi':'vview_vi'} assert len(vars) < 2, 'Gather only supports an index view, or an index view and an output view' if len(vars) == 1: other = vars[0] else: other = create(ot[self.type],indx.length) gather(self,indx,other) return other # vsip_simag_p @property def imag(self): """ A method to get a deep copy of the imaginary part of a complex view. """ return imag(self,self.otherEmpty) # vsip_sreal_p @property def real(self): """ A method to get a deep copy of the real part of a complex view. """ return real(self,self.otherEmpty) # vsip_dsscatter_p def scatter(self,other,indx): """ Usage: self.scatter(other,indx) This function scatters self into other governed by indx View other is returned as a convienience """ scatter(self,other,indx) return other # Basic Algorithms # These algorithms are specific to pyJvsip for convenience. No C VSIPL functions are in the C Library. def axpy(self,a,x): """ This is commonly called a saxpy (daxpy) for single (double) precision y = a * x + y or (algorithmically) y += a * x where self and x are vectors of the same type and a is a scalar. This is an in-place operation For C VSIPL this is implemented using functionality vsip_vsma_p vector-scalar-multiply-(vector)-add or linear algebra function vsip_dgems_p. """ assert isinstance(a,float) or isinstance(a,int) or isinstance(a,complex),'First paramter is a scalar for axpy' assert 'pyJvsip' in repr(x),'Second parameter is a view for axpy' assert self.type==x.type,'Views of input and output must agree in type.' assert self.size == x.size,'Views must be the same size.' if isinstance(a,complex): assert 'c' in self.type,'a complex scalar is not allowed for Views which are not complex.' if'mview' in self.type: return gems(a,x,'NTRANS',1,self) else: return ma(x,a,self,self) def gaxpy(self,A,x): """ Generalized axpy: y += Ax where y is vector in R(n), x is vector in R(m), A is matrix R(m,n); Views are float of same precision For more general case use gemp Note: Regular matrix multiply may be faster but gaxpy is an in-place operation. If instead you use y=Ax+y then Ax will create a new vector; add it to y into another new vector; and then replace the y reference with the new reference. """ tSup = ['vview_fmview_fvview_f','cmview_fcvview','mview_dvview_d','cmview_dcvview_d'] assert 'pyJvsip' in repr(A),'Matrix input must be a pyJvsip view' assert 'pyJvsip' in repr(x),'vector input must ba a pyJvsip view' assert 'mview' in A.type,'The first parameter must be a view of shape matrix.' assert 'vview' in x.type,'The second parameter must be a view of shape vector.' assert A.rowlength == x.length,'Views not of a compatible size for product.' assert A.type+x.type in tSup,'Type <:%s:> not supported for gaxpy.'%A.type+x.type assert self.type == x.type,'Calling view must be same type as input vector view' rs=A.rowstride; cs=A.colstride if rs < cs: #do by ROW t=A.rowview(0) s=A.colstride o=A.offset for i in range(A.collength): t.putoffset(s*i + o) self[i] += t.dot(x) else: #do by col t=A.colview(0) s=A.rowstride o=A.offset for i in range(A.rowlength): t.putoffset(s*i + o) self.axpy(x[i],t) return self def opu(self,x,y): """ Outer Product Update: A += x.outer(y) where: A in R(m,n); x in R(m), y in R(n) Note: Doing a regular outer product such as A = A + x.outer(y) will create a new matrix for the outer product; create a new matrix for the addition results and then return this matrix into the reference for A. Using A.opu(x,y) will do an in-place operation in A. """ assert 'mview' in self.type,'Calling view must be a matrix for opu.' assert 'pyJvsip' in repr(x) and 'pyJvsip' in repr(y),'Parameters to opu must be pyJvsip views.' assert 'vview' in x.type and 'vview' in y.type,'Input views must be vectors for opu' # we select a method with the += on the major stride. # This may not necessarily be the fastest method if calling matrix # has row length >> col length or vice versa if self.rowstride < self.colstride: #do by ROW t=self.rowview(0) s=self.colstride o=t.offset for i in range(self.collength): t.putoffset(i*s+o) t.axpy(x[i],y) else: #do by COL t=self.colview(0) s=self.rowstride o=t.offset for i in range(self.rowlength): t.putoffset(i*s+o) t.axpy(y[i],x) return self def nopu(self,x,y): """ Outer Product Update where you want a minus instead of a plus: A -= x.outer(y) where: A in R(m,n); x in R(m), y in R(n) Note: Doing a regular outer product such as A = A - x.outer(y) will create a new matrix for the outer product; create a new matrix for the addition results and then return this matrix into the reference for A. Using A.opu(x,y) will do an in-place operation in A. """ assert 'mview' in self.type,'Calling view must be a matrix for nopu.' assert 'pyJvsip' in repr(x) and 'pyJvsip' in repr(y),'Parameters to nopu must be pyJvsip views.' assert 'vview' in x.type and 'vview' in y.type,'Input views must be vectors for nopu' # we select a method with the -= on the major stride. # This may not necessarily be the fastest method if calling matrix # has row length >> col length or vice versa if self.rowstride < self.colstride: #do by ROW t=self.rowview(0) s=self.colstride o=t.offset for i in range(self.collength): t.putoffset(i*s+o) t.axpy(-x[i],y) else: #do by COL t=self.colview(0) s=self.rowstride o=t.offset for i in range(self.rowlength): t.putoffset(i*s+o) t.axpy(-y[i],x) return self def eroa(self,rFrom,rTo): """Elementary Row Operation Add (rows) For Matrix A A.eroa(i,j) will add row 'i' to row 'j' and replace row 'j' with the result """ assert 'mview' in self.type,'Elementary row operations only work with matrix views.' a1 = self.rowview(rTo) a1 += self.rowview(rFrom) return ('eroa',(rFrom,rTo)) def eros(self,r0,r1): """Elementary Row Operations Switch (rows) For Matrix A A.eros(i,j) will switch row 'i' and row'j' in-place """ assert 'mview' in self.type,'Elementary row operations only work with matrix views.' a0=self.rowview(r0) a1=self.rowview(r1) swap(a0,a1) return ('eros',(r0,r1)) def ecos(self,r0,r1): """Elementary Column Operations Switch (columns) For Matrix A A.ecos(i,j) will switch column 'i' and column 'j' in-place """ assert 'mview' in self.type,'Elementary row operations only work with matrix views.' a0=self.colview(r0) a1=self.colview(r1) swap(a0,a1) return ('ecos',(r0,r1)) def erom(self,alpha,r): """Elementary Row Operation (scalar) Multiply For Matrix A A.erom(aScalar,aRowIndex) will multiply aScalar times the row of A indexed by aRowIndex in-place """ assert 'mview' in self.type,'Elementary row operations only work with matrix views.' a=self.rowview(r) a *= alpha return('erom',(alpha,r)) @property def det(self): """ Calculate the determinant of a real matrix. Uses elementary row operations and axpy to produce an upper diagonal matrix. Done in place. The determinant is the product of the diagonal entries. Note: Done in place and the input is used up so use a copy method if the input matrix is needed. """ assert 'mview' in self.type and 'c' not in self.type, 'Determinant only calculated for real matrices of type float or double' n=self.rowlength m=self.collength assert m==n,'For determinant input matrix must be square' retval=1.0 for i in range(n): T=self[i:n,i:n] k=T.colview(0).maxmgvalindx if k != 0: retval = -retval T.eros(0,k) pvt=T[0,0] if pvt == 0.0: return 0.0 else: retval *= pvt vp=T.rowview(0) for j in range(1,T.rowlength): scl=-T[j,0]/pvt T.rowview(j).axpy(scl,vp) return retval ### plu operations are a demonstration. Should use LU class; or lu, luInv, luSolve. @property def plu(self): """ Calculate an LU decomposition with a row permutation vector for square Matrix A of size 'n' and type real, float. This operation is done out-of-place A.plu will return (a tuple) an permutation (index) vector of length n (call it p) a lower triangular matrix of size n (call it L) an upper triangular matrix of size n (call it U) such that A.permute(p) will be equal to L.prod(U) """ p=Block('block_vi',self.collength).vector.ramp(0,1) L=self.empty.identity U=self.copy supportedViews = ['mview_f','mview_d'] assert U.type in supportedViews,'Matrix must be of type mview_f or mview_d' n=U.rowlength m=U.collength assert m == n, 'Matrix must be square' for k in range(n-1): pk=U.colview(k)[k:n].maxmgvalindx if pk != 0: U.eros(k,k+pk) t=p[k] p[k]=p[k+pk] p[k+pk]=t pvt=U[k,k] assert pvt != 0.0, 'Matrix is singular' div(U[k+1:n,k],pvt,U[k+1:n,k]) uc=U.colview(k)[k+1:n];ur=U.rowview(k)[k+1:n] # to do in place use nopu else use product. U[k+1:n,k+1:n].nopu(uc,ur) # U[k+1:n,k+1:n] -= U[k+1:n,k].prod(U[k,k+1:n]) for i in range(1,n): for j in range(i): L[i,j]=U[i,j] U[i,j]=0 return (p,L,U) def lsolve(self,xy): assert 'vview' in xy.type, 'Method lsolve only works with vector argument' assert 'mview' in self.type, 'Method lsolve only defined for (upper diagonal) matrices' assert self.rowlength == self.collength and self.rowlength == xy.length,\ 'Calling view must be square with size equal to argument length' n=self.rowlength xy[0] /= self[0,0] for i in range(1,n): y0=xy[i] xy[i] = (y0 - self.rowview(i)[0:i].dot(xy[0:i]))/self[i,i] return xy def usolve(self,xy): assert 'vview' in xy.type, 'Method usolve only works with vector argument' assert 'mview' in self.type, 'Method usolve only defined for (upper diagonal) matrices' assert self.rowlength == self.collength and self.rowlength == xy.length,\ 'Calling view must be square with size equal to argument length' n=self.rowlength-1 xy[n] /= self[n,n] for i in range(n-1,-1,-1): y0=xy[i] xy[i] = (y0 - self.rowview(i)[i+1:n+1].dot(xy[i+1:n+1]))/self[i,i] return xy ### end plu operations #Matrix and Vector norms @property def norm2(self): """This method is a property which returns the two norm """ vSup=['vview_f','cvview_f','vview_d','cvview_d'] mSup=['mview_f','cmview_f','mview_d','cmview_d'] def eigB(A): #find Biggest eigenvalue small=A.normFro/1e16 vk=0; xk=A.colview(0).empty.fill(0.0) xk[0]=1 for i in range(1000): axk=A.prod(xk) n=axk.norm2 vkn=xk.jdot(axk).real chk=vkn-vk if chk < 0: chk = -chk if chk < small: return vkn else: vk = vkn xk=axk / n return vkn assert self.type in vSup or self.type in mSup, 'Type <:'+self.type+':> not supported by norm2' if self.type in vSup: return vsip_sqrt_d(self.jdot(self).real) else: if self.collength >= self.rowlength: t=self.transview M=t.prodh(t) else: M=self.prodh(self) return vsip_sqrt_d(eigB(M)) @property def normFro(self): """This method is a property which returns the Frobenius norm """ f={'vview_f': 'vsip_sqrt_d(self.sumsqval)', 'vview_d': 'vsip_sqrt_d(self.sumsqval)', 'mview_f': 'vsip_sqrt_d(self.sumsqval)', 'mview_d': 'vsip_sqrt_d(self.sumsqval)', 'cvview_f':'vsip_sqrt_d(self.realview.sumsqval + self.imagview.sumsqval)', 'cvview_d':'vsip_sqrt_d(self.realview.sumsqval + self.imagview.sumsqval)', 'cmview_f':'vsip_sqrt_d(self.realview.sumsqval + self.imagview.sumsqval)', 'cmview_d':'vsip_sqrt_d(self.realview.sumsqval + self.imagview.sumsqval)'} if self.type in f: return eval(f[self.type]) else: print('Type <:'+self.type+':> not recognized for frobenius') return @property def norm1(self): """This method is a property which returns the one norm """ vSup=['vview_f','cvview_f','vview_d','cvview_d'] mSup=['mview_f','cmview_f','mview_d','cmview_d'] if self.type in vSup: return self.mag.sumval elif self.type in mSup: mx=0 for i in range(self.rowlength): t=self.colview(i).norm1 if t > mx: mx=t return mx else: print('Type <:'+self.type+':> not supported by norm1') return @property def normInf(self): """This method is a property which returns the Infinity norm """ vSup=['vview_f','cvview_f','vview_d','cvview_d'] mSup=['mview_f','cmview_f','mview_d','cmview_d'] if self.type in vSup: return self.magval elif self.type in mSup: mx=0 for j in range(self.collength): t=self.rowview(j).norm1 if t > mx: mx=t return mx else: print('Type <:'+self.type+':> not supported by norm1') return #linear algebra def gemp(self,alpha,A,opA,B,opB,beta): """ self=alpha* opA(A)*obB(B) + beta * self op is one of 'NTRANS', 'TRANS','HERM','CONJ' alpha and beta are scalars A and B are float matrices (_d or _f) of type mview or cmview """ gemp(alpha,A,opA,B,opB,beta,self) return self def gems(self,alpha,A,opA,beta): """ self = alpha * op[opA](A) + beta*self """ gems(alpha,A,opA,beta,self) return self def outer(self,*args): """ Usage: A=b.outer(c) or A=b.outer(alpha,c) where: alpha is a scalar multiply (default one) b and c are vector views of the same type A is a matrix view created and returned by the method. """ assert len(args) > 0 and len(args) < 3,'There are at most two arguments to outer method.' if len(args) == 1: a = 1.0 other = args[0] else:# len(args) == 2: a = args[0] other = args[1] assert 'pyJvsip' in repr(other),'Expect pyJvsip view for input argument.' assert 'vview' in self.type,'Outer method only supported by views of type vector' assert self.type==other.type,'Input to outer method must be a views of type vector' cl=self.length; rl=other.length retval=self.block.otherBlock(self.block.type,rl*cl).bind(0,rl,cl,1,rl) outer(a,self,other,retval) return retval def prod(self,other): if 'vview' in self.type and 'mview' in other.type: l=other.rowlength retval = self.block.otherBlock(self.block.type,l).bind((0,1,l)) prod(self,other,retval) return retval elif 'mview' in self.type and 'mview' in other.type: n=other.rowlength m=self.collength retval = self.block.otherBlock(self.block.type,m*n).bind((0,n,m,1,n)) if m == 3 and self.rowlength == 3: prod3(self,other,retval) elif m == 4 and self.rowlength == 4: prod4(self,other,retval) else: prod(self,other,retval) return retval elif 'mview' in self.type and 'vview' in other.type: l=self.collength retval = self.block.otherBlock(self.block.type,l).bind((0,1,l)) if l == 3 and self.rowlength == 3: prod3(self,other,retval) elif l == 4 and self.rowlength == 4: prod4(self,other,retval) else: prod(self,other,retval) return retval else: assert False,'Input views <:%s:> and <:%s:> do not appear to be supported by function prod'%(self.type,other.type) def prodh(self,other): cSup=['cmview_f','cmview_d'] rSup=['mview_f','mview_d'] assert self.type == other.type,'For prodh views must be the same type' assert self.type in cSup or self.type in rSup,'Type <:%s:> not supported for prodh.'%self.type if self.type in cSup: n=other.collength m=self.collength retval = self.block.otherBlock(self.block.type,m*n).bind((0,n,m,1,n)) prodh(self,other,retval) return retval else: return self.prodt(other) def prodj(self,other): assert 'cmview' in self.type and 'cmview' in other.type,'Calling view and arument must be complex matrices.' m=self.collength n=other.rowlength retval = self.block.otherBlock(self.block.type,m*n).bind((0,n,m,1,n)) prodj(self,other,retval) return retval def prodt(self,other): assert 'mview' in self.type and 'mview' in other.type,'Calling view and argument for prodt must be matrix views.' n=other.collength m=self.collength retval = self.block.otherBlock(self.block.type,m*n).bind((0,n,m,1,n)) prodt(self,other,retval) return retval @property def trans(self): """ Done out of place. A new block and row major view are created and the transpose of the calling view is copied into it. See transview method for a transpose view on the same block. See trans function for the general case of transpose. Usage: B=A.trans """ assert 'mview' in self.type,'View must be a matrix' m=self.rowlength n=self.collength retval=self.block.otherBlock(self.block.type,m*n).bind((0,n,m,1,n)) trans(self,retval) return retval @property def herm(self): """ Done out of place. For square matrices in-place is possible using the herm function. Usage: Given matrix view A B = A.herm returns new matrix B which is hermitian of A. For an in place equivalent one can do A.transview.conj. """ assert 'mview' in self.type,'View must be a matrix' if 'cmview' in self.type: m=self.rowlength n=self.collength retval=self.block.otherBlock(self.block.type,m*n).bind((0,n,m,1,n)) herm(self,retval) return retval else:# 'mview' in self.type: return self.trans def dot(self,other): f = {'vview_f':vsip_vdot_f, 'vview_d':vsip_vdot_d, 'cvview_f':vsip_cvdot_f, 'cvview_d':vsip_cvdot_d} assert self.type in f,'Type <:%s:> not supported for dot product.'%self.type assert self.type == other.type,'Input view types must agree for dot.' retval=f[self.type](self.vsip,other.vsip) if 'cscalar' in repr(retval): return complex(retval.r,retval.i) else: return retval def jdot(self,other): assert 'pyJvsip' in repr(other),'Argument must be a pyJvsip view.' assert self.type.rpartition('_')[2] == other.type.rpartition('_')[2],\ 'Precisions of input views must agree for jdot.' f = { 'cvview_f':vsip_cvjdot_f, 'cvview_d':vsip_cvjdot_d} reTypes=['vview_f','vview_d'] imTypes=['cvview_f','cvview_d'] if 'cvview' in self.type and 'cvview' in other.type: t=self.type retval = f[t](self.vsip,other.vsip) return complex(retval.r,retval.i) elif (self.type in reTypes) and (other.type in reTypes): return self.dot(other) elif (self.type in imTypes) and (other.type in reTypes): return complex(self.realview.dot(other),self.imagview.dot(other)) elif (self.type in reTypes) and (other.type in imTypes): return complex(self.dot(other.realview),-self.dot(other.imagview)) else: assert False,'Input views not supported by jdot' def permute(self,p,*major): """ The permute method will permute a matrix by row or by column given an index vector. Usage: aView.permute(p,major) Where: aView is a matrix view of type float or double. vector views supported as if they were a column vector. p is a vector of type index (vview_vi) major is a string indicating permutatioln is by row ('ROW') or column ('COL') The permute method is done in place using the appropriate c VSIPL call to vsip_mpermute_once """ f={'cmview_f':vsip_cmpermute_once_f,\ 'cmview_d':vsip_cmpermute_once_d,\ 'mview_f':vsip_mpermute_once_f,\ 'mview_d':vsip_mpermute_once_d} assert p.type in 'vview_vi','The index vector for method permute must be of type "vview_vi".' pc=p.copy assert self.type in ['cmview_f','cmview_d','mview_f','mview_d','vview_f','vview_d'],\ 'For method permute type <:%s:> not supported'%self.type if 'vview' in self.type: self.mcolview.permute(p,'ROW') elif len(major) == 1 and major[0] == 'COL': assert p.length == self.rowlength,'In permute method index vector is not sized properly' f[self.type](self.vsip,VSIP_COL,pc.vsip,self.vsip) else: #do by ROW assert p.length == self.collength,'In permute method index vector is not sized properly' f[self.type](self.vsip,VSIP_ROW,pc.vsip,self.vsip) return self @property def permuteTranspose(self): """Return a permutation vector which is the equivalent of a transpose of the permutation matrix represented by the calling view. Done out-of-place. Input vector not modified. Input and output vectors both of type vview_vi """ if self.type != 'vview_vi': print('permuteTranspose method only works for vectors of type vview_vi') return p=self.empty for i in range(p.length): p[self[i]]=i return p def sortip(self,*vals): """ Usage: indx=self.sortip(mode,dir,fill,indx) Default: indx=self.sortip() -is the same as- indx = self.sortip('BYVALUE','ASCENDING') indx=self.sortip(mode) -is the same as- index = self.sortip(mode,'ASCENDING') Where: self is a vector mode is a string 'BYVALUE' or 'BYMAGNITUDE' dir is a string 'ASCENDING' or 'DESCENDING' fill is a bool True or False indx is an index vector the same length as self All arguments are optional but must be entered in order; for instance if dir is included then mode must be included. The bool fill indicates whether the indx vector is initialized or not. If no indx vector is included and fill is False then no indx vector is returned. If no indx vector is included and fill is True (or not included) then an indx vector is created and initialized and returned (with the sorted indices). If an indx vector is included then it is initialized (or not depending on fill), and the indices are sorted. If an index is included, indx is returned as a convenience. """ t=self.type f={'vview_f':vsip_vsortip_f,'vview_d':vsip_vsortip_d, 'vview_i':vsip_vsortip_i,'vview_vi':vsip_vsortip_vi} m={'BYVALUE':0,'BYMAGNITUDE':1,0:VSIP_SORT_BYVALUE,1:VSIP_SORT_BYMAGNITUDE} d={'DESCENDING':1,'ASCENDING':0,0:VSIP_SORT_ASCENDING,1:VSIP_SORT_DESCENDING} nvals=len(vals) assert t in f,'Type <:%s:> not supported for sortip.'%t assert nvals <5,'Maximum number of arguments for sortip is 4' if nvals > 0: mode=m[vals[0]] else: mode=m['BYVALUE'] if nvals > 1: dir=d[vals[1]] else: dir=d['ASCENDING'] fill = 1 if nvals > 2 and vals[2] == False: fill=0 if nvals == 4: assert vals[3].type == 'vview_vi','index vector for sortip must be of type vview_vi' idx = vals[3] if fill==1: idx.ramp(0,1) elif fill == 1: idx = create('vview_vi',self.length) else: idx = None if idx == None: f[t](self.vsip,mode,dir,fill,idx) else: f[t](self.vsip,mode,dir,fill,idx.vsip) return idx def sort(self,*vals): if len(vals) > 0: if len(vals) == 1: return self.sortip(vals[0]) elif len(vals) == 2: return self.sortip(vals[0],vals[1]) elif len(vals) == 3: return self.sortip(vals[0],vals[1],vals[2]) else:# len(vals) == 4 return self.sortip(vals[0],vals[1],vals[2],vals[3]) else: return self.sortip() # Signal Processing @property def fftip(self): fCreate = {'cvview_d':'ccfftip_d', 'cvview_f':'ccfftip_f', 'cmview_d':'ccfftmip_d', 'cmview_f':'ccfftmip_f'} assert self.type in fCreate,'View of type <:%s"> not supported by fftip.'%self.type if 'vview' in self.type: FFT(fCreate[self.type],self.length,1.0,-1,0,0).dft(self) elif 'COL' in self.major: FFT(fCreate[self.type],self.collength,self.rowlength,1.0,-1,VSIP_COL,0,0).dft(self) else: FFT(fCreate[self.type],self.collength,self.rowlength,1.0,-1,VSIP_ROW,0,0).dft(self) return self @property def ifftip(self): fCreate = {'cvview_d':'ccfftip_d', 'cvview_f':'ccfftip_f', 'cmview_d':'ccfftmip_d', 'cmview_f':'ccfftmip_f'} assert self.type in fCreate,'View of type <:%s"> not supported by ifftip.'%self.type if 'vview' in self.type: FFT(fCreate[self.type],self.length,1.0,1,0,0).dft(self) elif 'COL' in self.major: FFT(fCreate[self.type],self.collength,self.rowlength,1.0,1,VSIP_COL,0,0).dft(self) else: FFT(fCreate[self.type],self.collength,self.rowlength,1.0,1,VSIP_ROW,0,0).dft(self) return self @property def fftop(self): """ The method fftop (FFT Out Of Place) is a property on real and float vectors and matrices. For matrices use the major attribute of the view to set the direction of the FFT. fftop will create and return view of the proper type for the output. If the input is real then fftop assumes the complex portion is zero. """ selV={'vview_f':'cvview_f','vview_d':'cvview_d'} selM={'mview_f':'cmview_f','mview_d':'cmview_d'} if self.type in selV: y=create(selV[self.type],self.length).fill(0.0) copy(self,y.realview) return y.fftip elif self.type in selM: y=create(selM[self.type],self.collength,self.rowlength).fill(0.0) copy(self,y.realview) if 'COL' in self.major: return y.COL.fftip else: return y.ROW.fftip else: f = {'cvview_d':'ccfftop_d', 'cvview_f':'ccfftop_f', 'cmview_d':'ccfftmop_d', 'cmview_f':'ccfftmop_f'} assert self.type in f, 'Type <:%s:> not supported by method fftop'%self.type retval = self.empty if 'vview' in self.type: FFT(f[self.type],self.length,1.0,-1,0,0).dft(self,retval) elif 'COL' in self.major: FFT(f[self.type],self.collength,self.rowlength,1.0,-1,VSIP_COL,0,0).dft(self,retval) else: FFT(f[self.type],self.collength,self.rowlength,1.0,-1,VSIP_ROW,0,0).dft(self,retval) return retval @property def ifftop(self): """ The method ifftop (Inverse FFT Out Of Place) is a property on real and float vectors and matrices. For matrices use the major attribute of the view to set the direction of the FFT. fftop will create and return view of the proper type for the output. If the input is real then ifftop assumes the complex portion is zero. """ selV={'vview_f':'cvview_f','vview_d':'cvview_d'} selM={'mview_f':'cmview_f','mview_d':'cmview_d'} if self.type in selV: y=create(selV[self.type],self.length).fill(0.0) copy(self,y.realview) return y.ifftip elif self.type in selM: y=create(selM[self.type],self.collength,self.rowlength).fill(0.0) copy(self,y.realview) if 'COL' in self.major: return y.COL.ifftip else: return y.ROW.ifftip else: f = {'cvview_d':'ccfftop_d', 'cvview_f':'ccfftop_f', 'cmview_d':'ccfftmop_d', 'cmview_f':'ccfftmop_f'} assert self.type in f, 'Type <:%s:> not supported by method ifftop'%self.type retval = self.empty if 'vview' in self.type: FFT(f[self.type],self.length,1.0,1,0,0).dft(self,retval) elif 'COL' in self.major: FFT(f[self.type],self.collength,self.rowlength,1.0,1,VSIP_COL,0,0).dft(self,retval) else: FFT(f[self.type],self.collength,self.rowlength,1.0,1,VSIP_ROW,0,0).dft(self,retval) return retval @property def rcfft(self): fCreate = {'vview_d':'rcfftop_d', 'vview_f':'rcfftop_f', 'mview_d':'rcfftmop_d', 'mview_f':'rcfftmop_f'} t={'vview_f':'cblock_f','vview_d':'cblock_d', 'mview_f':'cblock_f','mview_d':'cblock_d'} assert self.type in fCreate,'Type <:%s:> is not supported for rcfft'%self.type if 'vview' in self.type: length = self.length assert not length & 1,'rcfft only supported for even length along fft direction ' n=int(length/2)+1 retval=Block(t[self.type],n).bind(0,1,n) FFT(fCreate[self.type],length,1.0,1,0).dft(self,retval) elif 'COL' in self.major: length = self.collength assert not length & 1,'rcfft only supported for even length along fft direction ' m = int(length/2 + 1) n = self.rowlength retval = Block(t[self.type],n * m).bind(0,1,m,m,n) FFT(fCreate[self.type],length,n,1.0,VSIP_COL,1,0).dft(self,retval) else: length = self.rowlength assert not length & 1,'rcfft only supported for even length along fft direction ' m=int(self.collength) n=int(length/2 + 1) retval = Block(t[self.type],m*n).bind(0,n,m,1,n) FFT(fCreate[self.type],m,length,1.0,VSIP_ROW,1,0).dft(self,retval) return retval @property def crfft(self): fCreate = {'cvview_d':'crfftop_d', 'cvview_f':'crfftop_f', 'cmview_d':'crfftmop_d', 'cmview_f':'crfftmop_f'} t={'cvview_f':'block_f','cvview_d':'block_d', 'cmview_f':'block_f','cmview_d':'block_d'} assert self.type in fCreate,'Type <:%s:> is not supported for rcfft'%self.type if 'vview' in self.type: n = int( 2 * (self.length-1)) retval=Block(t[self.type],n).bind(0,1,n) FFT(fCreate[self.type],n,1.0,1,0).dft(self,retval) elif 'COL' in self.major: m = int( 2 * (self.collength-1)) n = self.rowlength retval = Block(t[self.type],n * m).bind(0,1,m,m,n) FFT(fCreate[self.type],m,n,1.0,VSIP_COL,1,0).dft(self,retval) else: m=self.collength n= int(2 * (self.rowlength -1)) retval = Block(t[self.type],m*n).bind(0,n,m,1,n) FFT(fCreate[self.type],m,n,1.0,VSIP_ROW,1,0).dft(self,retval) return retval def firflt(self,x,*args): assert 'pyJvsip' in repr(x), 'The kernel must be a pyJvsip view' fSel={'vview_fvview_f':'fir_f','vview_fcvview_f':'rcfir_f','cvview_fcvview_f':'cfir_f', 'vview_dvview_d':'fir_d','vview_dcvview_d':'rcfir_d','cvview_dcvview_d':'cfir_d'} sel=self.type+x.type assert sel in fSel,'type <:%s:> not supported for fir method'%sel t=fSel[sel] saveState='NO' sym='NONE' N=x.length if len(args) > 0: assert isinstance(args[0],int),'Decimation argument must be an integer' D=int(args[0]) assert D <= self.length,'Decimation argument must be <= the length of the kernel' else: D=1 args = (self,sym,N,D,saveState) firObj = FIR(t,*args) y=create(x.type,int(N/D)+1) firObj.flt(x,y) y.putlength(firObj.lengthOut) return y @property def freqswap(self): freqswap(self) return self # # General Square Solver @property def lu(self): """ Create LU Object and Decomposition of calling view. Calling view must be square and float return lu object """ assert self.type in LU.tSel, "LU for %s not supported"%self.type assert self.rowlength == self.collength,"LU only supports square matrices" return LU(LU.tSel[self.type],self.rowlength).lud(self) @property def luInv(self): """ The method luInv creates a new matrix and uses the LU decomposition place the inverse of the calling matrix into it. Note that LU decomposition overwrites the input matrix so if "A" is the input matrix then Y=A.luInv will overwrite A. To keep A use copy as in Y=A.copy.luInv. """ assert self.type in LU.tSel, 'Type <:'+ self.type + ':> not supported for luInv' assert self.rowlength == self.collength, 'Method luInv only works for square matrices' retval=self.empty.identity LU(LU.tSel[self.type],self.rowlength).lud(self).solve(0,retval) return retval def luSolve(self,XB): """ Usage: X = A.luSolve(X) A is a matrix of type float or double; real or complex. On input X is a vector or matrix of the same precision as A luSolve overwrites input data with output data. To keep the input use Y = A.luSolve(X.copy) LU will overwrite the Calling matrix. To keep everything use Y = A.copy.luSolve(X.copy) """ assert self.type in LU.tSel, 'Type <:'+ self.type + ':> not supported for luSolve' assert self.rowlength == self.collength, 'Method luSolve only works for square matrices' if 'vview' in XB.type: X=XB.block.bind(XB.offset,XB.stride,XB.length,1,1) else: X = XB assert X.type == self.type, 'Calling view and input/output view must be the same type and precision' assert self.collength == X.collength, 'Input/Output view not sized properly for calling view' obj=LU(LU.tSel[self.type],self.rowlength).lud(self) assert obj.singular == False,'The calling matrix is singular' obj.solve('NTRANS',X) return XB # #QR Decomposition; Over-Determined Linear System Solver @property def qr(self): """ Usage: qr = view.qr where view is of type float; real or complex Return QR object and decomposition for calling view. Input view is used by QR object is so use a copy if original is needed. This returns a QR object for a Full Q. (qSave => VSIP_QRD_SAVEQ) NOTE for vector views: If the input view is a vector then the vector is converted to a matrix matrix. Vectors are treated as a column here. """ if self.type in ['vview_f','vview_d','cvview_f','cvview_d']: A=self.block.bind(self.offset,self.stride,self.length,1,1) elif self.type in ['mview_f','mview_d','cmview_f','cmview_d']: A = self else: print('Type <:' +self.type+ '<: not supported for QR') return assert A.collength >= A.rowlength,"QR requires column length less than row length" retval=QR(QR.tSel[self.type],A.collength,A.rowlength,VSIP_QRD_SAVEQ) retval.qrd(A) return retval @property def qrd(self): """ Usage: Q,R=view.qrd where view is of type float; real or complex For this function self is not overwritten Q.prod(R) should return (a matrix) equivalent to the input """ assert self.type in ['vview_d','vview_f','mview_d','mview_f', \ 'cvview_d','cvview_f','cmview_d','cmview_f'],\ 'Type <:'+self.type+':> not supported by view qrd method' if self.type in ['vview_f','vview_d','cvview_f','cvview_d']: A=self.block.bind(self.offset,self.stride,self.length,0,1).copy else: A = self.copy m = A.collength;n=A.rowlength; Q = Block(Block.blkSel[self.type],m*m).bind(0,1,m,m,m).identity qr = A.copy.qr qr.prodQ('NTRANS','RSIDE',Q) if 'cmview' in A.type: qr.prodQ('HERM','LSIDE',A) else: qr.prodQ('TRANS','LSIDE',A) return(Q,A) @property def qrInv(self): assert self.type in QR.tSel, 'Type <:'+ self.type + ':> not supported for qrInv' assert self.rowlength == self.collength, 'Method qrInv only works for square matrices' qr=self.qr Qt=qr.prodQ('TRANS','LSIDE',self.empty.identity) return qr.solveR('NTRANS',1.,Qt) #SVD Decomposition @property def sv(self): """ For a matrix view 'A' of type float or double, real or complex, s = A.sv will return a vector of singular values for matrix A Note Matrix A is overwritten by the decomposition. To retain A use s = A.copy.sv """ svtSel={'mview_d':'sv_d','mview_f':'sv_f','cmview_d':'csv_d','cmview_f':'csv_f'} vtSel={'mview_d':'vview_d','mview_f':'vview_f','cmview_d':'vview_d','cmview_f':'vview_f'} n=self.rowlength m=self.collength svObj=SV(svtSel[self.type],m,n,'NOS','NOS') if n < m: s=create(vtSel[self.type],n) else: s=create(vtSel[self.type],m) return svObj.svd(self,s) @property def svd(self): """ This method is a full svd decompostion. For SVD decomposition where A = U s V^H For matrix A: D=A.svd Matrix A is overwritten by the SVD. To retain A use D = A.copy.svd returns a tuple into D. D[0] will be matrix U, D[1] will be (real) vector s of singular values, and D[2] will be matrix V Note that this method returns the full U and V matrix including any NULL space. """ svtSel={'mview_d':'sv_d','mview_f':'sv_f','cmview_d':'csv_d','cmview_f':'csv_f'} vtSel={'mview_d':'vview_d','mview_f':'vview_f','cmview_d':'vview_d','cmview_f':'vview_f'} n=self.rowlength m=self.collength svObj=SV(svtSel[self.type],m,n,'FULL','FULL') if n < m: s=create(vtSel[self.type],n) else: s=create(vtSel[self.type],m) svObj.svd(self,s) U=create(self.type,m,m) V=create(self.type,n,n) svObj.matV(0,n,V) svObj.matU(0,m,U) return (U,s,V) @property def svdP(self): """ This method returns the partial svd decomposition. For SVD decomposition where A = U s V^H For matrix A: D=A.svd Matrix A is overwritten by the SVD. To retain A use D = A.copy.svd returns a tuple into D. D[0] will be matrix U, D[1] will be (real) vector s of singular values, and D[2] will be matrix V Note that this method returns the partial U and V matrix without the NULL space. """ svtSel={'mview_d':'sv_d','mview_f':'sv_f','cmview_d':'csv_d','cmview_f':'csv_f'} vtSel={'mview_d':'vview_d','mview_f':'vview_f','cmview_d':'vview_d','cmview_f':'vview_f'} n=self.rowlength m=self.collength svObj=SV(svtSel[self.type],m,n,'PART','PART') if n < m: s=create(vtSel[self.type],n) rl=n else: s=create(vtSel[self.type],m) rl=m svObj.svd(self,s) U=create(self.type,m,rl) V=create(self.type,n,rl) svObj.matV(0,rl,V) svObj.matU(0,rl,U) return (U,s,V) @property def svdU(self): """ For SVD decomposition where A = U s V^H For matrix A: D=A.svd Matrix A is overwritten by the SVD. To retain A use D = A.copy.svd returns a tuple into D. D[0] will be matrix U, D[1] will be (real) vector s of singular values This method returns the Full matrix U. """ svtSel={'mview_d':'sv_d','mview_f':'sv_f','cmview_d':'csv_d','cmview_f':'csv_f'} vtSel={'mview_d':'vview_d','mview_f':'vview_f','cmview_d':'vview_d','cmview_f':'vview_f'} n=self.rowlength m=self.collength svObj=SV(svtSel[self.type],m,n,'FULL','NOS') if n < m: s=create(vtSel[self.type],n) else: s=create(vtSel[self.type],m) svObj.svd(self,s) U=create(self.type,m,m) svObj.matu(0,m,U) return (U,s) @property def svdV(self): """ For SVD decomposition where A = U s V^H For matrix A: D=A.svd Matrix A is overwritten by the SVD. To retain A use D = A.copy.svd returns a tuple into D. D[0] will be (real) vector s of singular values, and D[1] will be matrix V Matrix V is the Full V matrix. """ svtSel={'mview_d':'sv_d','mview_f':'sv_f','cmview_d':'csv_d','cmview_f':'csv_f'} vtSel={'mview_d':'vview_d','mview_f':'vview_f','cmview_d':'vview_d','cmview_f':'vview_f'} n=self.rowlength m=self.collength svObj=SV(svtSel[self.type],m,n,'NOS','FULL') if n < m: s=create(vtSel[self.type],n) else: s=create(vtSel[self.type],m) svObj.svd(self,s) V=create(self.type,n,n) svObj.matv(0,n,V) return (s,V) @property def svdInv(self): m=self.collength; assert m==self.rowlength,'Matrix inverse only works for square matrices.' svObj=SV(SV.tSel[self.type],m,m,'FULL','FULL') s = svObj.svd(self) assert s[m-1] > 0.0,'Matrix is singular' s.recip; return svObj.prodV('NTRANS','LSIDE',s.COL.mmul(svObj.prodU('TRANS','LSIDE',self.empty.identity))) #utility functions def mstring(self,fmt): """ This method returns a string suitable for printing the values as a vector or matrix. usage: mstring(<vsip matrix/vector>, fmt) fmt is a string corresponding to a simple fmt statement. For instance '%6.5f' prints as 6 characters wide with 5 decimal digits. Note format converts this statement to '% 6.5f' or '%+6.5f' so keep the input simple. """ assert isinstance(fmt,str), 'Format must be a string' def _fmt1(c): if c != '%': return c else: return '% ' def _fmt2(c): if c != '%': return c else: return '%+' def _fmtfunc(fmt1,fmt2,y): if type(y) is complex: s = fmt1 % y.real s += fmt2 % y.imag s += "i" return s else: return fmt1 % y tm=['mview_d','mview_f','cmview_d','cmview_f','mview_i','mview_uc', 'mview_si','mview_bl'] tv=['vview_d','vview_f','cvview_d','cvview_f','vview_i','vview_uc', 'vview_si','vview_bl','vview_vi','vview_mi'] t=self.type tfmt=[_fmt1(c) for c in fmt] fmt1 = "".join(tfmt) tfmt=[_fmt2(c) for c in fmt] fmt2 = "".join(tfmt) if t in tm: cl=self.collength rl=self.rowlength s=str() for i in range(cl): M=[] for j in range(rl): M.append(_fmtfunc(fmt1,fmt2,self[i,j])) if i == 0 and cl==1: s += "["+" ".join(M) + "]\n" elif i== 0: s += "["+" ".join(M) + ";\n" elif i < cl-1: s += " "+" ".join(M) + ";\n" else: s += " "+" ".join(M) + "]\n" return s elif t in tv: l=self.length V=[_fmtfunc(fmt1,fmt2,self[i]) for i in range(l)] return "[" + " ".join(V) + "]\n" else: print('Object not VSIP vector or matrix') def mprint(self,fmt): assert isinstance(fmt,str), 'Format for mprint is a string' print(self.mstring(fmt)) def View(blk,*args): assert 'pyJvsip.Block' in repr(blk),'First parameter to View must be a block' return blk.bind(args) class Rand(object): """ Usage randObj=Rand(aType,aSeed) where aType is one of 'PRNG' or 'NPRNG' and aSeed is an integer number 'PRNG' signifies the portable VSIP version and 'NPRNG' signifies the non-portable version. randObj.randn(a) randObj.randu(a) fills view object a with the VSIPL normal or uniform (respectivly) random data. """ tRand = ['PRNG','NPRNG'] supported = ['vview_f','vview_d','cvview_f','cvview_d','mview_f','mview_d','cmview_f','cmview_d'] def __init__(self,t,seed): self.__jvsip = JVSIP() self.__type = t self.__seed = seed f={'PRNG':'vsip_randcreate(seed,1,1,0)', 'NPRNG':'vsip_randcreate(seed,1,1,1)'} if t in f: self.__rng=eval(f[t]) else: print("type must be either 'PRNG' or 'NPRNG'") def __del__(self): vsip_randdestroy(self.__rng) del(self.__jvsip) @property def type(self): return self.__type; @property def seed(self): return(self.__seed) @property def nextu(self): return vsip_randu_d(self.__rng) @property def nextn(self): return vsip_randn_d(self.__rng) @property def rng(self): return self.__rng def randn(self,a): assert 'pyJvsip' in repr(a),'Normal random method only works on pyJvsip views of precision float or double' t=a.type f = {'cvview_d':vsip_cvrandn_d, 'cvview_f':vsip_cvrandn_f, 'vview_d':vsip_vrandn_d, 'vview_f':vsip_vrandn_f, 'cmview_d':vsip_cmrandn_d, 'cmview_f':vsip_cmrandn_f, 'mview_d':vsip_mrandn_d, 'mview_f':vsip_mrandn_f} assert t in f,'Type <:%s:> not a supported type for method randn.'%t f[t](self.rng,a.vsip) return a def randu(self,a): assert 'pyJvsip' in repr(a),'Uniform random method only works on pyJvsip views of precision float or double' t=a.type f = {'cvview_d':vsip_cvrandu_d, 'cvview_f':vsip_cvrandu_f, 'vview_d':vsip_vrandu_d, 'vview_f':vsip_vrandu_f, 'cmview_d':vsip_cmrandu_d, 'cmview_f':vsip_cmrandu_f, 'mview_d':vsip_mrandu_d, 'mview_f':vsip_mrandu_f} assert t in f,'Type <:%s:> not a supported type for method randu.'%t f[t](self.rng,a.vsip) return a # Signal Processing Classes # Not Implemented # vsip_fft_setwindow_f # vsip_dfft2dx_create_f # vsip_ccfft2dx_f # vsip_crfft2dop_f # vsip_rcfft2dop_f # vsip_conv2d_create_f # vsip_conv2d_destroy_f # vsip_conv2d_getattr_f # vsip_convolve2d_f # vsip_dcorr2d_create_f # vsip_dcorr2d_destroy_f # vsip_dcorr2d_getattr_f # vsip_dcorrelate2d_f class FFT(object): """ Usage: fftObj=FFT(t,*arg) where t is one of ['ccfftip_f', 'ccfftop_f', 'rcfftop_f', 'crfftop_f', 'ccfftip_d', 'ccfftop_d', 'rcfftop_d', 'crfftop_d', 'ccfftmip_f', 'ccfftmop_f', 'rcfftmop_f', 'crfftmop_f', 'ccfftmip_d', 'ccfftmop_d', 'rcfftmop_d', 'crfftmop_d'] arg is an argument list corresponding to one of the VSIPL arguments list for the associated type value. Example: If VSIPL enumerated types are available as part of the pyJvsip import. """ tFft = ['ccfftip_f', 'ccfftop_f', 'rcfftop_f', 'crfftop_f', 'ccfftip_d', \ 'ccfftop_d', 'rcfftop_d', 'crfftop_d', 'ccfftmip_f', 'ccfftmop_f', \ 'rcfftmop_f', 'crfftmop_f', 'ccfftmip_d', 'ccfftmop_d', 'rcfftmop_d', 'crfftmop_d'] fftViewDict = {'ccfftip_d':'cvview_d', 'ccfftip_f':'cvview_f', 'ccfftop_d':'cvview_dcvview_d', 'ccfftop_f':'cvview_fcvview_f', 'rcfftop_d':'vview_dcvview_d', 'rcfftop_f':'vview_fcvview_f', 'crfftop_d':'cvview_dvview_d', 'crfftop_f':'cvview_dvview_f', 'ccfftmip_d':'cmview_d', 'ccfftmip_f':'cmview_f', 'ccfftmop_d':'cmview_dcmview_d', 'ccfftmop_f':'cmview_fcmview_f', 'crfftmop_d':'cmview_dmview_d', 'crfftmop_f':'cmview_fmview_f', 'rcfftmop_d':'mview_dcmview_d', 'rcfftmop_f':'mview_fcmview_f'} #given fft type what type of views works fftCreateDict={'ccfftip_f':'vsip_ccfftip_create_f(l[0],l[1],l[2],l[3],l[4])', 'ccfftop_f':'vsip_ccfftop_create_f(l[0],l[1],l[2],l[3],l[4])', 'rcfftop_f':'vsip_rcfftop_create_f(l[0],l[1],l[2],l[3])', 'crfftop_f':'vsip_crfftop_create_f(l[0],l[1],l[2],l[3])', 'ccfftip_d':'vsip_ccfftip_create_d(l[0],l[1],l[2],l[3],l[4])', 'ccfftop_d':'vsip_ccfftop_create_d(l[0],l[1],l[2],l[3],l[4])', 'rcfftop_d':'vsip_rcfftop_create_d(l[0],l[1],l[2],l[3])', 'crfftop_d':'vsip_crfftop_create_d(l[0],l[1],l[2],l[3])', 'ccfftmip_f':'vsip_ccfftmip_create_f(l[0],l[1],l[2],l[3],l[4],l[5],l[6])', 'ccfftmop_f':'vsip_ccfftmop_create_f(l[0],l[1],l[2],l[3],l[4],l[5],l[6])', 'rcfftmop_f':'vsip_rcfftmop_create_f(l[0],l[1],l[2],l[3],l[4],l[5])', 'crfftmop_f':'vsip_crfftmop_create_f(l[0],l[1],l[2],l[3],l[4],l[5])', 'ccfftmip_d':'vsip_ccfftmip_create_d(l[0],l[1],l[2],l[3],l[4],l[5],l[6])', 'ccfftmop_d':'vsip_ccfftmop_create_d(l[0],l[1],l[2],l[3],l[4],l[5],l[6])', 'rcfftmop_d':'vsip_rcfftmop_create_d(l[0],l[1],l[2],l[3],l[4],l[5])', 'crfftmop_d':'vsip_crfftmop_create_d(l[0],l[1],l[2],l[3],l[4],l[5])'} fftDestroyDict={'ccfftip_f':vsip_fft_destroy_f, 'ccfftop_f':vsip_fft_destroy_f, 'rcfftop_f':vsip_fft_destroy_f, 'crfftop_f':vsip_fft_destroy_f, 'ccfftip_d':vsip_fft_destroy_d, 'ccfftop_d':vsip_fft_destroy_d, 'rcfftop_d':vsip_fft_destroy_d, 'crfftop_d':vsip_fft_destroy_d, 'ccfftmip_f':vsip_fftm_destroy_f, 'ccfftmop_f':vsip_fftm_destroy_f, 'rcfftmop_f':vsip_fftm_destroy_f, 'crfftmop_f':vsip_fftm_destroy_f, 'ccfftmip_d':vsip_fftm_destroy_d, 'ccfftmop_d':vsip_fftm_destroy_d, 'rcfftmop_d':vsip_fftm_destroy_d, 'crfftmop_d':vsip_fftm_destroy_d} fftFuncDict={'cvview_d':'vsip_ccfftip_d(self.vsip,inpt.vsip)', 'cvview_f':'vsip_ccfftip_f(self.vsip,inpt.vsip)', 'cvview_dcvview_d':'vsip_ccfftop_d(self.vsip,inpt.vsip,outpt.vsip)', 'cvview_fcvview_f':'vsip_ccfftop_f(self.vsip,inpt.vsip,outpt.vsip)', 'vview_dcvview_d':'vsip_rcfftop_d(self.vsip,inpt.vsip,outpt.vsip)', 'vview_fcvview_f':'vsip_rcfftop_f(self.vsip,inpt.vsip,outpt.vsip)', 'cvview_dvview_d':'vsip_crfftop_d(self.vsip,inpt.vsip,outpt.vsip)', 'cvview_fvview_f':'vsip_crfftop_f(self.vsip,inpt.vsip,outpt.vsip)', 'cmview_d':'vsip_ccfftmip_d(self.vsip,inpt.vsip)', 'cmview_f':'vsip_ccfftmip_f(self.vsip,inpt.vsip)', 'cmview_dcmview_d':'vsip_ccfftmop_d(self.vsip,inpt.vsip,outpt.vsip)', 'cmview_fcmview_f':'vsip_ccfftmop_f(self.vsip,inpt.vsip,outpt.vsip)', 'mview_dcmview_d':'vsip_rcfftmop_d(self.vsip,inpt.vsip,outpt.vsip)', 'mview_fcmview_f':'vsip_rcfftmop_f(self.vsip,inpt.vsip,outpt.vsip)', 'cmview_dmview_d':'vsip_crfftmop_d(self.vsip,inpt.vsip,outpt.vsip)', 'cmview_fmview_f':'vsip_crfftmop_f(self.vsip,inpt.vsip,outpt.vsip)'} def __init__(self,t,*args): if t in FFT.fftCreateDict: self.__jvsip = JVSIP() self.__arg = args self.__type = t if len(args) == 1 and isinstance(args[0],tuple): l = args[0] else: l = args self.__fft = eval(FFT.fftCreateDict[t]) else: print("Type <:%s:> not a recognized type for FFT",t) def __del__(self): FFT.fftDestroyDict[self.type](self.__fft) del (self.__jvsip) def dft(self,*vars): """This method requires one view for in-place dft calculation or two views for out-of-place. The dft type may be retrieved using the type property of the FFT object. See the VSIPL specification for various view requirements which depend on the FFT method being used. Some error checking is done but it is not all inclusive. """ n = len(vars) assert n ==1 or n == 2,'One or two parameters to dft method are needed depending on type' if n == 1: #in-place inpt=vars[0];outpt=vars[0] t=inpt.type else: # out-of-place inpt=vars[0];outpt=vars[1] t=inpt.type+outpt.type assert 'pyJvsip' in repr(inpt) and 'pyJvsip' in repr(outpt),'Input parameters to dft method must be pyJvsip views.' assert t in FFT.fftFuncDict,'Type <:%s:> not recognized for dft method.'%t eval(FFT.fftFuncDict[t]) return outpt @property def vsip(self): return self.__fft @property def type(self): return self.__type @property def arg(self): return self.__arg # Convolution/Correlation Classes # vsip_dconv1d_create_f # vsip_dconv1d_destroy_f # vsip_dconv1d_getattr_f # vsip_dconvolve1d_f #VSIP_NONSYM = 0, VSIP_SYM_EVEN_LEN_ODD = 1, VSIP_SYM_EVEN_LEN_EVEN = 2 class CONV(object): """ See VSIPL specification for more information on convolution. """ tConv=['conv1d_f','conv1d_d'] tSel={'vview_f':'conv1d_f','vview_d':'conv1d_d'} supported=['vview_f','vview_d'] supportRegion = {0:VSIP_SUPPORT_FULL,1:VSIP_SUPPORT_SAME,2:VSIP_SUPPORT_MIN, 'FULL':VSIP_SUPPORT_FULL,'SAME':VSIP_SUPPORT_SAME,'MIN':VSIP_SUPPORT_MIN} symmetry = {0:VSIP_NONSYM,1:VSIP_SYM_EVEN_LEN_ODD, 2:VSIP_SYM_EVEN_LEN_EVEN, 'NON':VSIP_NONSYM,'ODD':VSIP_SYM_EVEN_LEN_ODD,'EVEN':VSIP_SYM_EVEN_LEN_EVEN} algHint={0:VSIP_ALG_TIME, 1:VSIP_ALG_SPACE, 2:VSIP_ALG_NOISE, 'TIME':VSIP_ALG_TIME,'SPACE':VSIP_ALG_SPACE,'NOISE':VSIP_ALG_NOISE} supportStrings={0:'FULL',1:'SAME',2:'MIN'} symmStrings={0:'NON',1:'ODD',2:'EVEN'} algStrings={0:'TIME',1:'SPACE',2:'NOISE'} def __init__(self,t,h,symm,dtaLength,dec,sup,ntimes,hint): f={'conv1d_d':vsip_conv1d_create_d,'conv1d_f':vsip_conv1d_create_f} assert isinstance(t,str),'Type argument must be a string for function conv' assert t in f, 'Type <:'+t+':> not recognized by function conv' assert hint in CONV.algHint, 'Argument hint not recognized by function conv' assert sup in CONV.supportRegion, 'Argument for support region not recognized by function conv' assert isinstance(dec,int) and isinstance(dtaLength,int) and isinstance(ntimes,int),\ 'Arguments decimation and data size must be integers, and ntimes is an integer' assert dec > 0, 'Decimation must be an integer greater than zero ' assert 'pyJvsip' in repr(h), 'The kernel must be a pyJvsip view' assert h.type in CONV.tSel and t == CONV.tSel[h.type],\ 'Kernel type <:' + h.type + ':> not recognized for convolution.' assert symm in CONV.symmetry, 'Symmetry flag not recognized' mySym=CONV.symmStrings[CONV.symmetry[symm]] # calculate kernel length if mySym == 'NON': M=h.length elif mySym == 'EVEN': M=h.length * 2 else: M=h.length * 2 - 1 assert M <= dtaLength, 'The kernel length is to long for the data length' self.__jvsip = JVSIP() self.__type = t self.__conv = f[t](h.vsip,CONV.symmetry[symm],dtaLength,dec,CONV.supportRegion[sup],ntimes,CONV.algHint[hint]) self.__kernel_len = int(M) self.__dtaLength = int(dtaLength) self.__decimation = int(dec) if CONV.supportRegion[sup]==VSIP_SUPPORT_FULL: self.__outLen = (self.__dtaLength + self.__kernel_len - 2) // self.__decimation + 1 elif CONV.supportRegion[sup]==VSIP_SUPPORT_SAME: self.__outLen = (self.__dtaLength -1 ) // self.__decimation + 1 else: # must be MIN self.__outLen = (self.__dtaLength - 1) // self.__decimation - (self.__kernel_len - 1) // self.__decimation + 1 self.__symm = CONV.symmetry[symm] self.__support = CONV.supportStrings[CONV.supportRegion[sup]] def __del__(self): f={'conv1d_d':vsip_conv1d_destroy_d,'conv1d_f':vsip_conv1d_destroy_f} f[self.type](self.vsip) del(self.__jvsip) @property def vsip(self): return self.__conv @property def type(self): return self.__type @property def kernel_len(self): return self.__kernel_len @property def symm(self): return CONV.symmStrings[self.__symm] @property def support(self): return self.__support @property def data_len(self): return self.__dtaLength @property def out_len(self): return self.__outLen @property def decimation(self): return self.__decimation def convolve(self,x,y): f={'conv1d_dvview_dvview_d':vsip_convolve1d_d, 'conv1d_fvview_fvview_f':vsip_convolve1d_f} assert 'pyJvsip' in repr(x) and 'pyJvsip' in repr(y),'Arguments to convolve must be pyJvsip views' t=self.type+x.type+y.type assert t in f,'Type <:' + t + ':> not recognized by convolve method' assert y.length == self.out_len, 'Output vector length not equal to calculated output length' f[t](self.vsip,x.vsip,y.vsip) return y # vsip_dcorr1d_create_f # vsip_dcorr1d_destroy_f # vsip_dcorr1d_getattr_f # vsip_dcorrelate1d_f class CORR(object): """ See VSIPL specification for more information on correlation. """ tCorr=['corr1d_f','corr1d_d','ccorr1d_f','ccorr1d_d'] corrSel={'mview_f':'corr1d_f','mview_d':'corr1d_d','cmview_f':'ccorr1d_f','cmview_d':'ccorr1d_d'} supported=['cmview_d','cmview_f','mview_d','mview_f'] supReg = {0:VSIP_SUPPORT_FULL,1:VSIP_SUPPORT_SAME,2:VSIP_SUPPORT_MIN, 'FULL':VSIP_SUPPORT_FULL,'SAME':VSIP_SUPPORT_SAME,'MIN':VSIP_SUPPORT_MIN} supportStrings={0:'FULL',1:'SAME',2:'MIN'} algHint={0:VSIP_ALG_TIME, 1:VSIP_ALG_SPACE, 2:VSIP_ALG_NOISE, 'TIME':VSIP_ALG_TIME,'SPACE':VSIP_ALG_SPACE,'NOISE':VSIP_ALG_NOISE} def __init__(self,t,repSize,dtaSize,region,ntimes,hint): f={'ccorr1d_d':vsip_ccorr1d_create_d,'ccorr1d_f':vsip_ccorr1d_create_f, 'corr1d_d':vsip_corr1d_create_d,'corr1d_f':vsip_corr1d_create_f} assert isinstance(t,str),'Type argument must be a string for function corr' assert t in f, 'Type <:'+t+':> not recognized by function corr' assert hint in CORR.algHint, 'Argument hint not recognized by function corr' assert region in CORR.supReg, 'Argument for support region not recognized by function corr' assert isinstance(repSize,int) and isinstance(dtaSize,int) and isinstance(ntimes,int),\ 'Arguments two, three and five must be integers' assert repSize > 0 and repSize <= dtaSize, \ 'The replica vector length must be > 0 and <= to the length of the data vector' self.__jvsip = JVSIP() self.__type = t self.__corr = f[t](repSize,dtaSize,CORR.supReg[region],ntimes,CORR.algHint[hint]) self.__repLength = repSize self.__dtaLength = dtaSize if CORR.supReg[region]==VSIP_SUPPORT_FULL: self.__lagLength = dtaSize + repSize - 1 elif CORR.supReg[region]==VSIP_SUPPORT_MIN: self.__lagLength = dtaSize - repSize + 1 else: self.__lagLength = dtaSize self.__support = CORR.supportStrings[CORR.supReg[region]] def __del__(self): f={'ccor1d_d':vsip_ccorr1d_destroy_f, 'ccor1d_f':vsip_ccorr1d_destroy_f, 'corr1d_d': vsip_corr1d_destroy_d, 'corr1d_f': vsip_corr1d_destroy_f} f[self.type](self.vsip) del(self.__jvsip) @property def type(self): return self.__type @property def vsip(self): return self.__corr @property def support(self): """ Support attribute """ return self.__support @property def lag_len(self): return self.__lagLength @property def ref_len(self): """ Reference vector length attribute """ return self.__repLength @property def data_len(self): """ Data Length attribute """ return self.__dtaLength def correlate(self,bias,ref,x,y): """ See VSIP specification document for more Information. Usage: correlate(bias, ref, x, y) Where: bias 'BIASED' or 'UNBIASED' to select correlation normalization. ref reference vector x input view y output view """ biasSelect={0:VSIP_BIASED,1:VSIP_UNBIASED, 'BIASED':VSIP_BIASED, 'UNBIASED':VSIP_UNBIASED} f={'ccorr1d_dcvview_dcvview_dcvview_d':vsip_ccorrelate1d_d, 'ccorr1d_fcvview_fcvview_fcvview_f':vsip_ccorrelate1d_f, 'corr1d_dvview_dvview_dvview_d':vsip_correlate1d_d, 'corr1d_fvview_fvview_fvview_f':vsip_correlate1d_f} assert 'pyJvsip' in repr(a) and 'pyJvsip' in repr(b)\ and 'pyJvsip' in repr(c),\ 'The last three arguments of method correlate must be pyJvsip views' t = self.type+ref.type+x.type+y.type assert t in f,'Type<:'+t+' not recognized for correlate object' assert bias in biasSelect(bias), \ 'Bias key not recogonized for correlate method' assert ref.length == self.ref_len, \ 'Reference vector length not in correlate object' assert x.length == self.data_len, \ 'data vector length not in correlate object' f[t](self.vsip,biasSelect[bias],ref.vsip,x.vsip,y.vsip) return y # filter Class class FIR(object): tFir=['fir_f','fir_d','cfir_f','cfir_d','rcfir_f','rcfir_d'] def __init__(self,t,*args): """ Usage: firObj = FIR(t,*args) args is a tuple containing the argument list for the C VSIPL create call args = (filt, symm, N, D, state, ntimes, algHint) t is a type string; one of: 'rcfir_f','cfir_f','fir_f','rcfir_d','cfir_d','fir_d' filt is a vector view of filter coefficients sym may ba a string or VSIP flag 'NONE' or VSIP_NONSYM 'ODD' or VSIP_SYM_EVEN_LEN_ODD 'EVEN' or VSIP_SYM_EVEN_LEN_EVEN N is the length of the input data expected D is the decimation state (save state) may be a string or VSIP flag 'NO' or VSIP_STATE_NO_SAVE or 'YES' or VSIP_STATE_SAVE Default to 'NO' if argument left off. ntimes is a hint indicating how often the fir will be used. 0 indicates a lot of times ntimes may be left off and defaults to zero. JVSIP only supports only supports the interface. Internaly ntimes is not supported. algHint defaults to 0 VSIP_ALG_TIME VSIP_ALG_SPACE VSIP_ALG_NOISE JVSIP only supports the interface for algHint. Internally algHint is not supported. """ filtSptd = {'fir_f':'vview_f', 'fir_d':'vview_d', 'cfir_f':'cvview_f', 'cfir_d':'cvview_d', 'rcfir_f':'vview_f', 'rcfir_d':'vview_d'} firCreate = {'fir_f':vsip_fir_create_f, 'fir_d':vsip_fir_create_d, 'cfir_f':vsip_cfir_create_f, 'cfir_d':vsip_cfir_create_d, 'rcfir_f':vsip_rcfir_create_f, 'rcfir_d':vsip_rcfir_create_d} symType={VSIP_NONSYM:VSIP_NONSYM, VSIP_SYM_EVEN_LEN_ODD:VSIP_SYM_EVEN_LEN_ODD, VSIP_SYM_EVEN_LEN_EVEN:VSIP_SYM_EVEN_LEN_EVEN, 'NONE':0,'ODD':1,'EVEN':2} stateType={VSIP_STATE_NO_SAVE:VSIP_STATE_NO_SAVE, VSIP_STATE_SAVE: VSIP_STATE_SAVE,'NO':1,'YES':2} assert len(args) > 3, 'args must include (filt, symm, N, D).' assert len(args) < 8, 'Argument list has too many elemnets' assert args[0].type == filtSptd[t],\ 'Filter Coefficients of type <:%s:> in wrong for filter of type <:%s:>'%(filt.type,t) assert t in firCreate, 'Filter type not recognized' state= VSIP_STATE_NO_SAVE if len(args) > 4: assert args[4] in stateType,'State flag not recognized' state = stateType[args[4]] algHint=VSIP_ALG_TIME ntimes=0 filt=args[0].vsip sym=symType[args[1]] N=args[2] D=args[3] assert args[0].length <= N,'Data length must be >= kernel length' assert D <= args[0].length,'Decimation must be <= kernel length' assert sym in symType,'Sym flag not recognized' self.__jvsip = JVSIP() self.__type = t self.__fir = firCreate[t](filt,sym,N,D,state,ntimes,algHint) self.__length = N self.__decimation=D self.__state = state self.__outLength=0 def __del__(self): firDestroy = {'fir_f':vsip_fir_destroy_f, 'fir_d':vsip_fir_destroy_d, 'cfir_f':vsip_cfir_destroy_f, 'cfir_d':vsip_cfir_destroy_d, 'rcfir_f':vsip_rcfir_destroy_f, 'rcfir_d':vsip_rcfir_destroy_d} firDestroy[self.type](self.vsip) del(self.__jvsip) def flt(self,x,y): """ Usage: fir = FIR(...) fir.flt(x,y) x is input view of data to be filtered y is output view of filtered data """ filtSptd = {'fir_f':'vview_f','fir_d':'vview_d',\ 'cfir_f':'cvview_f','cfir_d':'cvview_d',\ 'rcfir_f':'cvview_f','rcfir_d':'cvview_d'} firflt = {'fir_f':vsip_firflt_f,'fir_d':vsip_firflt_d,\ 'cfir_f':vsip_cfirflt_f,'cfir_d':vsip_cfirflt_d,\ 'rcfir_f':vsip_rcfirflt_f,'rcfir_d':vsip_rcfirflt_d} assert x.type == y.type, 'Input and output views must be the same type.' assert filtSptd[self.type] == x.type,'Filter type does not support input views' self.__outLength = firflt[self.type](self.vsip,x.vsip,y.vsip) return y @property def reset(self): """ Property. Resets the state of the FIR object. (as it had not been called yet). """ fir_reset = {'fir_f':vsip_fir_reset_f,'fir_d':vsip_fir_reset_d, 'cfir_f':vsip_cfir_reset_f,'cfir_d':vsip_cfir_reset_d, 'rcfir_f':vsip_rcfir_reset_f,'rcfir_d':vsip_rcfir_reset_d} if self.state: fir_reset[self.type](self.vsip) return self @property def state(self): """ Property. Returns a bool True if the FIR object saves state and False if it does not save state. """ if self.__state == 'YES': return True else: return False @property def type(self): """ Property. Returns a string reflecting the type of FIR object. """ return self.__type @property def vsip(self): """ Property. Returns the C VSIPL FIR instance. """ return self.__fir @property def length(self): """ Property. Returns the length of the expected input data view. """ return self.__length @property def decimation(self): """ Property. Returns the decimation factor for the filter. """ return self.__decimation @property def lengthOut(self): """ Property. Returns number of data values in output view from last filter operation. """ return self.__outLength # Linear Algebra Classes # vsip_dlud_p # vsip_dlud_create_p # vsip_dlud_destroy_p # vsip_dlud_getattr_p # vsip_dlusol_p class LU(object): tLu=['lu_f','lu_d','clu_f','clu_d'] tSel={'mview_f':'lu_f','mview_d':'lu_d','cmview_f':'clu_f','cmview_d':'clu_d', 'lu_f':'lu_f','lu_d':'lu_d','clu_f':'clu_f','clu_d':'clu_d'} supported=['cmview_d','cmview_f','mview_d','mview_f'] def __init__(self,t,luSize): luCreate={'clu_f':vsip_clud_create_f, 'clu_d':vsip_clud_create_d, 'lu_f':vsip_lud_create_f, 'lu_d':vsip_lud_create_d} assert t in LU.tSel,'Type not recognized for LU' assert luSize > 0,'Size must be greater than 0' assert isinstance(luSize,int),'LU size must be an integer' self.__jvsip = JVSIP() self.__type = LU.tSel[t] self.__size = luSize self.__m = {'matrix':0} self.__singular=1 self.__lu = luCreate[self.__type](luSize) def __del__(self): f={'lu_d':vsip_lud_destroy_d,'lu_f':vsip_lud_destroy_f, 'clu_d':vsip_clud_destroy_d,'clu_f':vsip_clud_destroy_f} f[self.type](self.__lu) del(self.__jvsip) @property def type(self): return self.__type @property def size(self): return self.__size @property def singular(self): if self.__singular == 0: return False else: return True @property def vsip(self): return self.__lu def lud(self,m): """ Usage: luObj.lud(A) A is a square matrix of type real or complex float or double decompose method for LU object atta """ tMatrix={'cmview_d':'clu_d','cmview_f':'clu_f','mview_d':'lu_d','mview_f':'lu_f'} luDecompose={'lu_f':vsip_lud_f, 'lu_d':vsip_lud_d, 'clu_f':vsip_clud_f, 'clu_d':vsip_clud_d} assert 'pyJvsip' in repr(m),'Input must be a pyJvsip view in LU Decompose' assert m.rowlength == m.collength,'Matrix must be square for LU' assert m.type in LU.supported, 'Matrix not supported by LU' assert self.size == m.rowlength,\ 'LU object of size %d but matrix of size %d'%(self.size,m.rowlength) self.__singular=luDecompose[self.type](self.vsip,m.vsip) self.__m['matrix'] = m return self def solve(self,opIn,inOut): """ sv.solve(opA,XB) opA should be a string equal to 'NTRANS', 'TRANS', or 'HERM' or opA should be a C VSIPL Flag XB is a matrix. Solve is done in place. For pyJvsip if a vector is passed in for XB it will work as a matrix with a single column. I have tried to make this generic but it is probably possible to pass in arguments which will cause a failure when calling the underlying VSIPL functions. """ op = {'NTRANS':VSIP_MAT_NTRANS,'TRANS':VSIP_MAT_TRANS,'HERM':VSIP_MAT_HERM} if 'vview' in inOut.type: XB=inOut.block.bind(inOut.offset,inOut.stride,inOut.length,1,1) else: XB=inOut luSol={'lu_d':vsip_lusol_d,'lu_f':vsip_lusol_f,\ 'clu_d':vsip_clusol_d,'clu_f':vsip_clusol_f} assert (type(opIn) is str) or (type(opIn) is int), "LU solve: Matrix Operator must be string or int." if type(opIn) is str: assert ('TRANS' in opIn) or ('HERM' in opIn), "LU solve: Flag type %s not recognized."%opIn if 'NTRANS' in opIn: opM=op['NTRANS'] elif 'HERM' in opIn: if 'clu' in self.type: opM=opn['HERM'] else: opM=np['TRANS'] else: opM=op['TRANS'] else: assert (opIn >= 0) and (opIn < 3), "LU solve: Flag %d not recognized"%opIn opM = opIn if 'clu' not in self.type and opM == 2: opM = 1 if (XB.type in LU.supported) and (XB.collength == self.size): if self.__m['matrix'] == 0: print('LU object has no matrix associated with it') return else: luSol[self.type](self.vsip,opM,XB.vsip) return inOut else: print('Input matrix must be conformant with lu') return # vsip_dchold_p # vsip_dchold_create_p # vsip_dchold_destroy_p # vsip_dchold_getattr_p # vsip_dcholsol_p class CHOL(object): """ Cholesky Decomposition """ tChol=['chol_f','chol_d','cchol_f','cchol_d'] tSel={'mview_f':'chol_f','mview_d':'chol_d','cmview_f':'cchol_f','cmview_d':'cchol_d', 'chol_f':'chol_f','chol_d':'chol_d','cchol_f':'cchol_f','cchol_d':'cchol_d' } uplowSel={0:VSIP_TR_LOW,1:VSIP_TR_UPP,'UPP':VSIP_TR_UPP,'LOW':VSIP_TR_LOW} supported=['cmview_d','cmview_f','mview_d','mview_f'] def __init__(self,t,uplow,cholSize): """ See C VSIP specification for more info. Usage: chol=CHOL(t,upOrLow,N) Where: t is the cholesky type ('cchol_f','cchol_d','chol_f','chol_d' upOrLow is a string 'UPP' to indicate the upper triangular portion of the matrix is to be used or 'LOW' if the lower triangular portion. N is the size of the square matrix. """ cholCreate={'cchol_f':vsip_cchold_create_f, 'cchol_d':vsip_cchold_create_d, 'chol_f':vsip_chold_create_f, 'chol_d':vsip_chold_create_d} assert t in CHOL.tSel,'CHOL type not recognized' self.__jvsip = JVSIP() self.__type = CHOL.tSel[t] self.__size = cholSize self.__m = {'matrix':0} assert self.__type in cholCreate and cholSize > 0 and isinstance(cholSize,int), \ 'CHOL create error. Check type, and size. Size must be an int greater than 0.' assert uplow in CHOL.uplowSel,'Flag for upper or lower matrix not recognized' self.__chol = cholCreate[self.__type](CHOL.uplowSel[uplow],cholSize) def __del__(self): cholDestroy={'cchol_f':vsip_cchold_destroy_f, 'cchol_d':vsip_cchold_destroy_d, 'chol_f':vsip_chold_destroy_f, 'chol_d':vsip_chold_destroy_d} cholDestroy[self.__type](self.__chol) del(self.__jvsip) @property def type(self): return self.__type @property def size(self): return self.__size @property def vsip(self): return self.__chol def lud(self,m): """ Decompose method for CHOL object Usage for cholesky object cholObj: cholObj.chold(A) Where: A is a square matrix of type real or complex float or double """ tMatrix={'cmview_d':'cchol_d','cmview_f':'cchol_f', 'mview_d':'chol_d','mview_f':'chol_f'} cholDecompose={'chol_f':vsip_chold_f, 'chol_d':vsip_chold_d, 'cchol_f':vsip_cchold_f, 'cchol_d':vsip_cchold_d} assert 'pyJvsip' in repr(m), \ 'Input for CHOL decompose method must be a pyJvsip view' assert tMatrix[m.type] == self.type, 'Type <:'+m.type+':> not supported by CHOL object' assert m.rowlength == m.collength and m.rowlength == self.size,\ 'For chold object (decomposition) matrix must be square and of size '+repr(self.size) cholDecompose[self.type](self.vsip,m.vsip) self.__m['matrix'] = m return self def solve(self,inOut): """ Usage for cholesky object chold: chold.solve(XB) XB is a matrix. Solve is done in place. For pyJvsip if a vector is passed in for XB it will work as a matrix with a single column. I have tried to make this generic but it is probably possible to pass in arguments which will cause a failure when calling the underlying VSIPL functions. """ cholSol={'chol_d':vsip_cholsol_d,'chol_f':vsip_cholsol_f,\ 'cchol_d':vsip_ccholsol_d,'cchol_f':vsip_ccholsol_f} tMatrix={'cmview_d':'cchol_d','cmview_f':'cchol_f', 'mview_d':'chol_d','mview_f':'chol_f'} assert 'pyJvsip' in repr(inOut), \ 'Input for CHOL decompose method must be a pyJvsip view' if 'vview' in inOut.type: a=inOut.block.bind(inOut.offset,inOut.stride,inOut.length,1,1) else: a=inOut assert a.collength == self.size,'Size error in CHOL solve' assert a.type in tMatrix, 'Type <:'+inOut.type+':> not supported by CHOL solve' assert tMatrix[a.type] == self.type, 'Cholesky object does not match input view' assert self.__m['matrix'] != 0, 'Cholesky object not associated with a matrix' cholSol[self.type](a.vsip) return inOut #QR class QR(object): """ qSave is VSIP_QRD_NOSAVEQ => 0 (No Q) VSIP_QRD_SAVEQ => 1 (Full Q) VSIP_QRD_SAQVEQ1 =>2 (skinny Q) qOp VSIP_MAT_NTRANS => 0, VSIP_MAT_TRANS => 1, VSIP_MAT_HERM => 2, qSide VSIP_MAT_LSIDE => 0, VSIP_MAT_RSIDE => 1 qProb VSIP_COV => 0, VSIP_LLS => 1 """ tQr=['qr_f','qr_d','cqr_f','cqr_d'] tSel={'mview_f':'qr_f','mview_d':'qr_d','cmview_f':'cqr_f','cmview_d':'cqr_d', 'qr_f':'qr_f','qr_d':'qr_d','cqr_f':'cqr_f','cqr_d':'cqr_d'} supported=['cmview_d','cmview_f','mview_d','mview_f'] qSave=['NOSAVEQ','SAVEQ','SAVEQ1', VSIP_QRD_NOSAVEQ, VSIP_QRD_SAVEQ, VSIP_QRD_SAVEQ1] selQsave = {'NOSAVEQ':0,'SAVEQ':1,'SAVEQ1':2, 0:VSIP_QRD_NOSAVEQ, 1:VSIP_QRD_SAVEQ, 2:VSIP_QRD_SAVEQ1} qSide = {'LSIDE':VSIP_MAT_LSIDE,'RSIDE':VSIP_MAT_RSIDE,0:VSIP_MAT_LSIDE,1:VSIP_MAT_RSIDE} qOp = {'NTRANS':VSIP_MAT_NTRANS,'TRANS':VSIP_MAT_TRANS,'HERM':VSIP_MAT_HERM, 0:VSIP_MAT_NTRANS,1:VSIP_MAT_TRANS,2:VSIP_MAT_HERM} qProb={'COV':VSIP_COV,'LLS':VSIP_LLS,0:VSIP_COV,1:VSIP_LLS} probSel={0:'COV',1:'LLS'} def __init__(self,t,m,n,qSave): qrCreate={'cqr_f':vsip_cqrd_create_f, 'cqr_d':vsip_cqrd_create_d, 'qr_f':vsip_qrd_create_f, 'qr_d':vsip_qrd_create_d} assert t in QR.tSel, 'Type <:%s:> not recognized for QR'%repr(t) assert type(m) is int and type(n) is int,"Row and column sizes must be integers" assert m >= n and n > 0, "For QR lengths are greater than zero and column length is >= row length" assert qSave in QR.selQsave, 'Flag for save Q is %s. Flag not recognized for QR'%repr(qSave) self.__jvsip = JVSIP() self.__type = QR.tSel[t] self.__qSave = QR.selQsave[qSave] self.__collength = m self.__rowlength = n self.__m = {'matrix':0} self.__qr = qrCreate[self.__type](m,n,QR.selQsave[qSave]) def __del__(self): f={'qr_d':vsip_qrd_destroy_d, 'qr_f':vsip_qrd_destroy_f, 'cqr_d':vsip_cqrd_destroy_d,'cqr_f':vsip_cqrd_destroy_f} f[self.type](self.__qr) del(self.__jvsip) @property def type(self): return self.__type @property def size(self): return {'ColumnLength':self.__collength,'RowLength':self.__rowlength} @property def args(self): return (self.__collength,self.__rowlength,self.__qSave) @property def sizeQ(self): attr=self.args m=attr[0];n=attr[1];op=attr[2] if op == 0: return (0,0) elif op == 1: return(m,m) else: return(m,n) @property def vsip(self): return self.__qr def qrd(self,m): tMatrix={'cmview_d':'cqr_d','cmview_f':'cqr_f','mview_d':'qr_d','mview_f':'qr_f'} qrDecompose={'qr_f':vsip_qrd_f, 'qr_d':vsip_qrd_d, 'cqr_f':vsip_cqrd_f, 'cqr_d':vsip_cqrd_d} assert 'pyJvsip' in repr(m),'Input to decompose must be a pyJvsip view' assert m.type in tMatrix,'Type <:%s:> not supported for QR'%m.type assert self.type == tMatrix[m.type],\ 'View of type <:%s:> not compliant with QR object of type <:%s:>'%(m.type,self.type) assert self.__collength==m.collength and self.__rowlength==m.rowlength, \ 'Matrix to decompose and QR object are not the same size.' qrDecompose[self.type](self.vsip,m.vsip) self.__m['matrix'] = m return self def prodQ(self,op,side,X): qrProd={'qr_d':vsip_qrdprodq_d,'qr_f':vsip_qrdprodq_f, \ 'cqr_d':vsip_cqrdprodq_d,'cqr_f':vsip_cqrdprodq_f} assert 'pyJvsip' in repr(self.__m['matrix']), 'No matrix associated with QR object.' assert side in QR.qSide,\ "Flag for Q side not recognized; should be 'LSIDE' or 'RSIDE'" assert op in QR.qOp,\ "Flag for Q option not recognized; should be 'NTRANS', 'TRANS' or 'HERM' " assert self.args[2] != 0,'QR object told not to save Q. No matrix product available' assert 'pyJvsip' in repr(X),'The last argument to prodQ must be a pyJvsip view.' assert X.type in QR.tSel,'The input view to prodQ is not supported by QR object' assert QR.tSel[X.type] == self.type,\ 'The input view to prodQ not the type the QR object was created for' m,n=self.sizeQ XM=X.collength if QR.qSide[side] == VSIP_MAT_LSIDE: if QR.qOp[op] == VSIP_MAT_TRANS or QR.qOp[op] == VSIP_MAT_HERM: assert m == XM, 'Matrix product size error in prodQ' else: #must be NTRANS assert n == XM,'Matrix product Size Error in prodQ' else: #must be RSIDE if QR.qOp[op] == VSIP_MAT_TRANS or QR.qOp[op] == VSIP_MAT_HERM: assert n == XM,'Matrix product Size Error in prodQ' else: #must be NTRANS assert m == XM, 'Matrix product Size Error in prodQ' qrProd[self.type](self.vsip,QR.qOp[op],QR.qSide[side],X.vsip) return X def solveR(self,op,alpha,XB): qrSol={'qr_d':vsip_qrdsolr_d,'qr_f':vsip_qrdsolr_f,\ 'cqr_d':vsip_cqrdsolr_d,'cqr_f':vsip_cqrdsolr_f} assert 'pyJvsip' in repr(self.__m['matrix']), 'No matrix associated with QR object.' assert isinstance(alpha,int) or isinstance(alpha,float) or isinstance(alpha,complex),\ 'Second argument must be a number compatible with input/output view' assert op in QR.qOp,'Flag for matrix operation not found.' assert 'pyJvsip' in repr(XB),'Last argument must be a pyJvsip View' assert XB.type in QR.tSel if 'cmview_d' in XB.type: sclr=vsip_cmplx_d(alpha.real,alpha,imag) elif 'cmview_f' in XB.type: sclr= vsip_cmplx_f(alpha.real,alpha.imag) else: sclr=alpha assert self.__rowlength == XB.rowlength,'Size error for solveR.' assert self.type == QR.tSel[XB.type], 'The input view does not comply with QR object type' qrSol[self.type](self.vsip,QR.qOp[op],sclr,XB.vsip) return XB def solve(self,prob,XB): qrSol={'qr_d':vsip_qrsol_d,'qr_f':vsip_qrsol_f,\ 'cqr_d':vsip_cqrsol_d,'cqr_f':vsip_cqrsol_f} assert 'pyJvsip' in repr(self.__m['matrix']),'No matrix associated with QR object' assert prob in QR.qProb,"QR problem type should be 'COV' or 'LLS'. " assert 'pyJvsip' in repr(XB),'The second argument to solve must be a pyJvsip view' assert XB.type in QR.tSel,'The second argument is not supported by QR' assert QR.tSel[XB.type] == self.type,\ 'The QR object of type <:%s:> was not defined for an input/output view of type <:%s:>'%(self.type,XB.type) if 'COV' == QR.probSel[QR.qProb[prob]]: assert XB.collength == self.__rowlength, 'Size error for solve covariance problem' else: # must be LLS assert XB.collength == self.__collength, 'Size error for solve least square problem' qrSol[self.type](self.vsip,QR.qProb[prob],XB.vsip) return XB #Singular Value class SV(object): """ Usage: svObj=SV(type, colLength,rowLength,opU,opV) Where: type is a string; one of 'sv_f', 'sv_d', 'csv_f', csf_d' colLength and rowLength are the sizes of the expected matrix, opU and opV are strings; one of 'NOS', 'FULL', 'PART' indicating what part of the U and S matrices are to be retained. Note you may also use the string coresponding to the target matrix for type. For instance if only singular values of matrix A are required then you could do sv=SV(A.type,A.collength,A.rowlength,'NOS','NOS') """ tSv=['sv_f','sv_d','csv_f','csv_d'] supported=['mview_d','cmview_d','mview_f','cmview_f'] svSel={'sv_f':'mview_f','sv_d':'mview_d','csv_f':'cmview_f','csv_d':'cmview_d'} svvSel={'sv_f':'vview_f','sv_d':'vview_d','csv_f':'vview_f','csv_d':'vview_d'} tSel={'sv_f':'sv_f','mview_f':'sv_f','sv_d':'sv_d','mview_d':'sv_d', 'csv_f':'csv_f','cmview_f':'csv_f','csv_d':'csv_d','cmview_d':'csv_d'} saveSel={'NOS':VSIP_SVD_UVNOS,'FULL':VSIP_SVD_UVFULL,'PART':VSIP_SVD_UVPART, 0:VSIP_SVD_UVNOS, 1:VSIP_SVD_UVFULL, 2:VSIP_SVD_UVPART} sideSel = {'LSIDE':VSIP_MAT_LSIDE,'RSIDE':VSIP_MAT_RSIDE, 0:VSIP_MAT_LSIDE, 1:VSIP_MAT_RSIDE} matopSel = {'NTRANS':VSIP_MAT_NTRANS,'TRANS':VSIP_MAT_TRANS,'HERM':VSIP_MAT_HERM, 0:VSIP_MAT_NTRANS, 1:VSIP_MAT_TRANS, 2:VSIP_MAT_HERM} def __init__(self,t,*args): # m,n,opU,opV or (m,n),opU,opV svCreate={'sv_f':vsip_svd_create_f, 'sv_d':vsip_svd_create_d, 'csv_f':vsip_csvd_create_f, 'csv_d':vsip_csvd_create_d} assert t in SV.tSel,'Type <:%s:> not recognized for SV'%repr(t) assert len(args) == 3 or len(args) == 4,'Argument list not a proper length' if len(args) == 3: assert isinstance(args[0],tuple),'Second argument should be m,n or tuple (m,n)' m=args[0][0];n=args[0][1] opU=args[1];opV=args[2] else: m=args[0];n=args[1]; opU=args[2];opV=args[3] assert isinstance(m,int) and isinstance(n,int),'Length arguments must be integers for SV' assert opU in SV.saveSel and opV in SV.saveSel, 'Singular Value flags not recognized' self.__jvsip = JVSIP() self.__type = SV.tSel[t] self.opU=SV.saveSel[opU] self.opV=SV.saveSel[opV] self.m=m self.n=n self.__sizeU=(m,m) self.__sizeV=(n,n) if self.opU == VSIP_SVD_UVPART and m > n: self.__sizeU = (m,n) if self.opV == VSIP_SVD_UVPART and n > m: self.__sizeV = (n,m) if self.opU == VSIP_SVD_UVNOS: self.__sizeU = (0,0) if self.opV == VSIP_SVD_UVNOS: self.__sizeV = (0,0) self.__sv=svCreate[self.__type](m,n,SV.saveSel[opU],SV.saveSel[opV]) self.View=0.0 self.__s=0.0 def __del__(self): svDestroy={'sv_f':vsip_svd_destroy_f, 'sv_d':vsip_svd_destroy_d, 'csv_f':vsip_csvd_destroy_f, 'csv_d':vsip_csvd_destroy_d} svDestroy[self.type](self.vsip) del(self.__jvsip) @property def s(self): assert self.__s != 0.0,'No matrix decompostion assciated with SV object' return self.__s.copy @property def size(self): return(self.m,self.n) @property def sizeU(self): return self.__sizeU @property def sizeV(self): return self.__sizeV @property def type(self): """ SV property returning type string. """ return self.__type @property def vsip(self): """ SV property returning VSIPL svd object. Must retain reference to containing SV object to use. """ return self.__sv def svd(self,other,*sarg): """ Usage: given matrix view A of type real or complex, float or double and real vector view s of equivalent precision to A (float or double) and s of length min(A.collength, A.rowlength) and SV Object sv then sv.svd(A,s) will calculate the singular values of A and place them in s. Note that the matrix A is overwritten by the singular value calculation. To keep A use sv.svd(A.copy,s). Note a vector s is returned as a convenience. Note if vector s is not supplied method will create s. """ svdD={'sv_f':vsip_svd_f, 'sv_d':vsip_svd_d, 'csv_f':vsip_csvd_f, 'csv_d':vsip_csvd_d} self.View=other assert 'pyJvsip' in repr(other),'Input must be a pyJvsip view object.' if len(sarg) < 1: m,n=other.size if m > n: m = n s=create(SV.svvSel[self.type],m) else: s = sarg[0] assert 'pyJvsip' in repr(s),'Input must be a pyJvsip view object.' if SV.svSel[self.type] in other.type and SV.svvSel[self.type] in s.type: svdD[self.type](self.vsip,other.vsip,s.vsip) self.__s = s.copy return s else: print('svd does not understand argument list\n') return def matV(self,*args): """ Return V matrix from SV computation. Assume svObj is the SV object Usage: V=svObj.matV(low,high,V) Where: low is the first column index of V to include. high is the last column index of V to include. V is included as an argument and returned as a convenience (in pyJvsip). As a convenience in pyJvsip V=svObj.matV() will create and return a saved V. V=svObj.matV(low,high) will create and return a suitable V. """ assert len(args) == 0 or len(args) == 2 or len(args) == 3,'Argument list error.' svMatV={'sv_f':vsip_svdmatv_f, 'sv_d':vsip_svdmatv_d, 'csv_f':vsip_csvdmatv_f, 'csv_d':vsip_csvdmatv_d} if SV.saveSel['NOS'] == self.opV: return elif len(args) < 1: other = create(SV.svSel[self.type],self.sizeV) m,n=self.sizeV return self.matV(0,n-1,other) elif len(args) == 2: other = create(SV.svSel[self.type],self.sizeV) return self.matV(args[0],args[1],other) else: low=args[0];high=args[1];other=args[2] assert self.View != 0.0,'No matrix decomposition has taken place' assert isinstance(low,int) and isinstance(high,int),'Column indices must be integers' assert 'pyJvsip' in repr(other),'Output must be pyJvsip view' assert other.type == SV.svSel[self.type],'SV object of type <:%s:> not compatible with output view of type <:%s:>'%(self.type,other.type) svMatV[self.type](self.vsip,low,high,other.vsip) return other def matU(self,*args): """ Return U matrix from SU computation. Assume svObj is the SV object Usage: U=svObj.matU(low,high,U) Where: low is the first column index of U to include. high is the last column index of U to include. U is included as an argument and returned as a convenience (in pyJvsip). As a convenience in pyJvsip. U=svObj.matU() will create and return the saved U. U=svObj.matU(low,high) will create and return a suitable U. """ svMatU={'sv_f':vsip_svdmatu_f, 'sv_d':vsip_svdmatu_d, 'csv_f':vsip_csvdmatu_f, 'csv_d':vsip_csvdmatu_d} assert len(args) == 0 or len(args) == 2 or len(args) == 3,'Argument list error.' if SV.saveSel['NOS'] == self.opU: return elif len(args) < 1: other = create(SV.svSel[self.type],self.sizeU) m,n=self.sizeU return self.matU(0,n-1,other) elif len(args) == 2: other = create(SV.svSel[self.type],self.sizeU) return self.matU(args[0],args[1],other) else: low=args[0];high=args[1];other=args[2] assert self.View != 0.0,'No matrix decomposition has taken place' assert isinstance(low,int) and isinstance(high,int),'Column indices must be integers' assert 'pyJvsip' in repr(other),'Output must be pyJvsip view' assert other.type == SV.svSel[self.type],'SV object of type <:%s:> not compatible with output view of type <:%s:>'%(self.type,other.type) svMatU[self.type](self.vsip,low,high,other.vsip) return other def prodV(self,opMat,opSide,inout): assert 'pyJvsip' in repr(inout), 'The Input/Output argument must be a pyJvsip view' assert SV.svSel[self.type] == inout.type, 'SV object of type %s not compatible with view of type %s'%(self.type,inout.type) assert opMat in SV.matopSel,'Matrix operator flag not recognized' assert opSide in SV.sideSel,'Side operator flag not recognized' assert SV.saveSel['NOS'] != self.opV,'SV object created with no V matrix saved' assert self.View != 0.0,'No matrix decomposition has taken place' f={'sv_f':vsip_svdprodv_f,'sv_d':vsip_svdprodv_d,'csv_f':vsip_csvdprodv_f,'csv_d':vsip_csvdprodv_d} m,n=sizeOut(self.sizeV,inout.size,opMat,opSide) out=inout.cloneview; out.putrowlength(n); out.putcollength(m); f[self.type](self.vsip,SV.matopSel[opMat],SV.sideSel[opSide],inout.vsip) return out def prodU(self,opMat,opSide,inout): assert 'pyJvsip' in repr(inout), 'The Input/Output argument must be a pyJvsip view' assert SV.svSel[self.type] == inout.type, 'SV object of type %s not compatible with view of type %s'%(self.type,inout.type) assert opMat in SV.matopSel,'Matrix operator flag not recognized' assert opSide in SV.sideSel,'Side operator flag not recognized' assert SV.saveSel['NOS'] != self.opU,'SV object created with no U matrix saved' assert self.View != 0.0,'No matrix decomposition has taken place' m,n=sizeOut(self.sizeU,inout.size,opMat,opSide) out=inout.cloneview; out.putrowlength(n); out.putcollength(m); f={'sv_f':vsip_svdprodu_f,'sv_d':vsip_svdprodu_d,'csv_f':vsip_csvdprodu_f,'csv_d':vsip_csvdprodu_d} f[self.type](self.vsip,SV.matopSel[opMat],SV.sideSel[opSide],inout.vsip) return out class Spline(object): """ Cubic Spline """ Sel={'mview_d':'spline_d','mview_f':'spline_f','vview_d':'spline_d','vview_f':'spline_f',\ 'spline_d':'spline_d','spline_f':'spline_f'} def __init__(self,t,nMax): assert isinstance(nMax,int),'Spline length argument must be an integer' f={'spline_f':vsip_spline_create_f,'spline_d':vsip_spline_create_d} assert t in Spline.Sel,'Type <:%s:> not recognized for spline'%t self.__jvsip=JVSIP() self.__type=Spline.Sel[t] self.__spline=f[self.__type](nMax) self.size=nMax def __del__(self): f={'spline_f':vsip_spline_destroy_f,'spline_d':vsip_spline_destroy_d} f[self.type](self.vsip) del(self.__jvsip) def interpolate(self,*args): n=len(args) f={'vview_f':'vsip_vinterp_spline_f(x0.vsip,y0.vsip,self.vsip,x.vsip,y.vsip)',\ 'vview_d':'vsip_vinterp_spline_d(x0.vsip,y0.vsip,self.vsip,x.vsip,y.vsip)',\ 'mview_f':'vsip_minterp_spline_f(x0.vsip,y0.vsip,self.vsip,dim,x.vsip,y.vsip)',\ 'mview_d':'vsip_minterp_spline_d(x0.vsip,y0.vsip,self.vsip,dim,x.vsip,y.vsip)'} major={'ROW':VSIP_ROW,'COL':VSIP_COL,0:VSIP_ROW,1:VSIP_COL} assert len(args) >= 4 and len(args) < 6,'Argument length should be 4 or 5' x0=args[0];y0=args[1]; x=args[n-2]; y=args[n-1] assert 'pyJvsip' in repr(x0) and 'pyJvsip' in repr(y0) and \ 'pyJvsip' in repr(x) and 'pyJvsip' in repr(y),\ 'first two and last two arguments to spline method must be views' if 'mview' in y0.type: if n == 5: assert args[2] in major,'Major flag not recognized for spline method.' dim=major[args[2]] else: assert x0.major in major,'Major flag not recognized for spline method.' dim=major[x0.major] if dim==0: assert x0.length == y0.collength,'Input data views not compliant.' assert x.length == y.collength,'Output data views not compliant.' else: assert x0.length == y0.rowlength,'Input data views not compliant.' assert x.length == y.rowlength,'Output data views not compliant.' else: assert x0.length == y0.length,'Input data views not compliant.' assert y.length == x.length, 'Output data views not compliant.' eval(f[y0.type]) @property def type(self): return self.__type @property def vsip(self): return self.__spline @property def maxlength(self): return self.size class Permute(object): from pyJvsip import JVSIP fcreateSel={'mview_d':vsip_mpermute_create_d,'mview_f':vsip_mpermute_create_f} fdestroySel={'mview_d':vsip_permute_destroy,'mview_f':vsip_permute_destroy} fpermuteSel={'mview_d':vsip_mpermute_d,'mview_f':vsip_mpermute_f} major={'ROW':VSIP_ROW,'COL':VSIP_COL,0:VSIP_ROW,1:VSIP_COL} def __init__(self,t,m,n,major): assert t in Permute.fcreateSel, 'Permute class only supports matrices of type float and depth real' assert major in Permute.major, "Major argument is 0 (VSIP_ROW),1 (VSIP_COL), or 'ROW', 'COL'" self.__jvsip=JVSIP() self.__vsip=Permute.fcreateSel[t](m,n,Permute.major[major]) self.__m=m self.__n=n self.__t=t def __del__(self): vsip_permute_destroy(self.vsip) del(self.__jvsip) @property def size(self): return(self.__m,self.__n) @property def type(self): return self.__t @property def vsip(self): return self.__vsip def permuteInit(self,p): vsip_permute_init(self.vsip,p.vsip) def permute(self,input,output): assert self.type == input.type,'Permute object not created for input type' assert input.type == output.type,'input and output types must agree' assert input.size == self.size,'permute object must be the same size as the input' assert input.size==output.size,'input and output views must be the same size' Permute.fpermuteSel[input.type](input.vsip,self.vsip,output.vsip) def ramp(t,start,inc,length): return create(t,length).ramp(start,inc) def create(atype,*vals): """ usage: anObject=create(aType,...) where: aType corresponds to a valid type for the object being created and ... are a variable argument list associated with each supported create type The create function has default values for most creates. For instance the matrix create will be row major by default, and no memory hints are used since the jvsip distribution does not support (underneath the covers) the vsip_memory_hint. QR creates are by default for the full Q, SV creates are by default for the full matrix. """ blockTypes = Block.tBlock windowTypes=Block.windowTypes vectorTypes=['cvview_f','cvview_d','vview_f','vview_d','vview_i','vview_si','vview_uc',\ 'vview_vi','vview_mi','vview_bl'] fVector = {'vview_f':'block_f','vview_d':'block_d','cvview_f':'cblock_f', \ 'cvview_d':'cblock_d','vview_i':'block_i','vview_si':'block_si', \ 'vview_uc':'block_uc','vview_bl':'block_bl','vview_vi':'block_vi', \ 'vview_mi':'block_mi'} matrixTypes=['cmview_f','cmview_d','mview_f','mview_d','mview_i','mview_si','mview_uc', \ 'mview_bl'] fMatrix = {'mview_f':'block_f','mview_d':'block_d','cmview_f':'cblock_f',\ 'cmview_d':'cblock_d','mview_i':'block_i','mview_si':'block_si',\ 'mview_uc':'block_uc','mview_bl':'block_bl'} fftTypes = FFT.tFft mfftTypes = ['ccfftmip_f', 'ccfftmop_f', 'rcfftmop_f', 'crfftmop_f', \ 'ccfftmip_d', 'ccfftmop_d', 'rcfftmop_d', 'crfftmop_d'] vfftTypes=['ccfftip_f', 'ccfftop_f', 'rcfftop_f', 'crfftop_f', \ 'ccfftip_d', 'ccfftop_d', 'rcfftop_d', 'crfftop_d'] luTypes = LU.tLu svTypes = SV.tSv qrTypes = QR.tQr cholTypes=CHOL.tChol convTypes=CONV.tConv corrTypes=CORR.tCorr randType = Rand.tRand majorType=['ROW','COL',VSIP_ROW,VSIP_COL] mat_uploFlag=['UPP','LOW',VSIP_TR_LOW,VSIP_TR_UPP] assert isinstance(atype,str),'Types used in the create function must be a string' if atype in blockTypes: assert len(vals) == 1, 'Create for %s has a single length argument'%atype assert isinstance(vals[0],int), 'Length for %s must be an integer'%atype return Block(atype,vals[0]) elif atype in windowTypes: if 'hanning' in atype or 'blackman' in atype: assert len(vals) == 1, 'Create for %s has a single length argument'%atype return Block(atype,vals[0]).w else: assert len(vals) == 2, 'Create for %s has a single length argument and one parameter'%atype return Block(atype,vals[0],vals[1]).w elif atype in vectorTypes: assert len(vals) == 1, 'Create for %s has a single length argument'%atype if isinstance(vals[0],tuple): l=vals[0][0] else: l=vals[0] assert isinstance(l,int) , 'Length for %s must be an integer'%atype return create(fVector[atype],l).bind(0,1,l) elif atype in matrixTypes: offset=0 if isinstance(vals[0],tuple): assert len(vals[0]) == 2,'Size for %s must have two integer entries.'%atype cl,rl=vals[0] assert (isinstance(cl,int) and isinstance(rl,int)) , 'Lengths for %s must be integers.'%atype row_stride=1;col_stride=rl if len(vals) == 2: assert vals[1] in majorType, 'Flag %s not recognized as a vsip_major type'%repr(vals[1]) if vals[1] == VSIP_COL or vals[1] == 'COL': row_stride=cl;col_stride=1 else: assert len(vals) > 1 and len(vals) < 4, \ 'Create for %s has two length arguments and an optional major argument.'%atype assert (isinstance(vals[0],int) and isinstance(vals[1],int)) , 'Lengths for %s must be integers.'%atype cl=vals[0];rl= vals[1] row_stride=1;col_stride=rl if len(vals) == 3: assert vals[2] in majorType, 'Flag %s not recognized as a vsip_major type'%repr(vals[2]) if vals[2] == VSIP_COL or vals[2] == 'COL': row_stride=cl;col_stride=1 l=rl * cl return create(fMatrix[atype],l).bind(offset,col_stride,cl,row_stride,rl) elif atype in fftTypes: nVals = len(vals) hint = 0 # set to VSIP_ALG_TIME ntimes = 0 # set to use a lot assert (atype in vfftTypes and nVals > 0) or (atype in mfftTypes and nVals > 1), \ """ Usage requires a single length for vectors or the column and row length for matrices. For vectors (matrices) the second (third) argument is a scalar indicating a scale (defaults to 1.0). The argument list is searched for the string "INV" and if found the object is built for an inverse FFT. The default is a Forward FFT If a multiple FFT is specified the argument list is searched for a string of "COL". If found the fft is done for each column. The default is by row. """ if 'INV' in vals: dir = 1 #VSIP_FFT_INV else: dir = -1 #VSIP_FFT_FWD if atype in mfftTypes: major = 0 # default fft by row assert (isinstance(vals[0],int) and isinstance(vals[1],int)), \ 'Length arguments for %s must be integers'%atype M = vals[0]; N = vals[1] if nVals > 2 and (isinstance(vals[2,int]) or isinstance(vals[2],float)): scaleFactor = float(vals[2]) else: scaleFactor = 1.0 if 'COL' in vals: major = 1 # 'VSIP_COL' else: assert isinstance(vals[0],int) ,\ 'Length argument for %s must be an integer'%atype N = vals[0] if nVals > 1 and (isinstance(vals[1],int) or isinstance(vals[1],float)): scaleFactor = float(vals[1]) else: scaleFactor = 1.0 if ('ccfftip' in atype) or ('ccfftop' in atype): arg = (N,scaleFactor,dir,ntimes,hint)#5 elif ('crfftop' in atype) or ('rcfftop' in atype): arg = (N,scaleFactor,ntimes,hint)#4 elif ('ccfftmip' in atype) or ('ccfftmop' in atype): arg = (M,N,scaleFactor,dir,major,ntimes,hint)#7 elif ('crfftmop' in atype) or ('rcfftmop' in atype): arg = (M,N,scaleFactor,major,ntimes,hint)#6 else: print('<:%s:> not recognized'%atype) #should not be able to get here return if len(arg) == 7: return FFT(atype,arg[0],arg[1],arg[2],arg[3],arg[4],arg[5],arg[6]) elif len(arg) == 6: return FFT(atype,arg[0],arg[1],arg[2],arg[3],arg[4],arg[5]) elif len(arg) == 5: return FFT(atype,arg[0],arg[1],arg[2],arg[3],arg[4]) elif len(arg) == 4: return FFT(atype,arg[0],arg[1],arg[2],arg[3]) elif atype in randType: assert len(vals) == 2, 'Type <:%s:> takes a type argument and an intger seed'%atype assert isinstance(vals[1],int), 'Argument two for random number generator is an integer' return Rand(atype,vals[1]) elif atype in luTypes: assert len(vals) == 1, 'Type <:%s:> takes a type argument and an intger length'%atype assert isinstance(vals[0],int), 'Argument two for LU is an integer' return LU(atype,vals[0]) elif atype in qrTypes: assert len(vals) > 1, \ 'Too few arguments. Type <::%s:> takes a type, two length arguments, and an optional Q save argument'%atype assert len(vals) < 4, \ 'Too many arguments. Type <::%s:> takes a type, two length arguments, and an optional Q save argument'%atype op='SAVEQ' #default if len(vals) == 3: assert vals[2] in QR.selQsave, 'Flag %s not recognized for QR create'%repr(vals[2]) op=vals[2] return QR(atype,vals[0],vals[1],op) elif atype in svTypes: assert len(vals) > 1,\ 'Too few arguments. Type <::%s:> takes a type, two length arguments, and two optional vsip_svd_uv save argumenta'%atype assert len(vals) < 5, \ 'Too many arguments. Type <::%s:> takes a type, two length arguments, and an optional Q save argument'%atype opVsave='FULL';opUsave='FULL' if len(vals) == 3: assert vals[2] in SV.saveSel,'Save argument not recognized for singular value' opVsave=SV.saveSel[vals[2]] opUsave=opVsave if len(vals) == 4: assert vals[2] in SV.saveSel and vals[3] in SV.saveSel,'Save Arguments not recognized for singular value' opVsave=SV.saveSel[vals[3]] opUsave=SV.saveSel[vals[2]] return SV(atype,vals[0],vals[1],opUsave,opVsave) elif atype in cholTypes: assert len(vals) < 3, 'Cholesky create takes either a vsip_mat_uplo flag and a length, or just a length' assert len(vals) > 0, 'Cholesky must have at least one integer size value' if len(vals) == 2: assert vals[0] in mat_uploFlag, "Second argument to create for type %s is 'UPP' or 'LOW' "%atype assert isinstance[vals[1],int], 'Third argument to create for type %s is an integer size'%atype matFlag=vals[0] sz=vals[1] else: matFlag='UPP' assert isinstance[vals[0],int], \ 'Argument to create for type %s is an integer size. If not included default vsip_mat_uplo is "UPP" '%atype sz=vals[0] return CHOL(atype,matFlag,sz) elif atype in convTypes: """ Usage Cases Convolution: create(atype,h,dtaLength) => symm = 'NON', dec=1, support='FULL',ntimes=0,hint='TIME' create(atype,h,dtaLength, dec) => symm = 'NON', support='FULL',ntimes=0,hint='TIME' create(atype,h,symm, dtaLength, dec) => support='FULL',ntimes=0,hint='TIME' create(atype,h,symm, dtaLength, dec, support) => ntimes=0,hint='TIME' """ ntimes=0; hint='TIME'; symm='NON'; dec=1; support='FULL' nvals=len(vals) msg = 'For create convolution the number of arguments after type is five or less.' msg += '\nNote ntimes hint is always 0 and the alg hint is always "TIME" for this function.' msg += 'These are default values and not part of the argument list' msg1 = 'The first argument after the type must be a vector view conformant with the convolution type\n' msg1+= 'The second argument after the data type must be an integer length.' assert nvals > 1, 'As a minimum convolution create requires a filter view and a data length' h=vals[0] if nvals < 4: dtaSize = vals[1] else: dtaSize = vals[2] symm = vals[1] assert symm in symmetry,'Symmetry flag not recognized for create of %s'%atype assert nvals < 6, msg assert 'pyJvsip' in repr(h) and isinstance(dtaSize,int) and h.type in CONV.tSel, msg1 assert atype == CONV.tSel[h.type],'Type %s not conformant with %s.'%(h.type,atype) if nvals > 3: dec = vals[3] assert isinstance(dec,int),'Decimation value for create of %s must be an integer'%atype if nvals > 4: sup = vals[4] assert sup in supportRegion, 'Support region flag not recognized for create of %s'%atype return CONV(atype,h,symm,dtaLength,dec,sup,ntimes,hint) elif atype in corrTypes: """ Usage: If region is 'FULL' use corr=create(atype,repSize,dtaSize) or: corr=create(atype,repSize,dtaSize,region) where region is one of 'FULL', 'SAVE', or 'MIN' ntimes and hint always default to 0 and 'TIME' respectively. """ ntimes=0; hint='TIME'; region='FULL' region = 'FULL' nvals = len(vals) assert nvals > 1, 'As a minimum create of %s requires a reference vector length and a data vector length'%atype assert nvals < 4, \ 'Too many argumentsfor create of %s; has at most a type, two lengths, and a support region flag'%atype repSize = vals[0];dtaSize=vals[1] if nvals > 2: region = vals[2] assert region in supportRegion, 'Support region flag not recognized for create of %s'%atype assert isinstance(repSize,int), 'Reference vector length must be an for create of %s'%atype assert isinstance(dtaSize,int), 'Data vector length must be an integer for create of %s'%atype return CORR(atype,repSize,dtaSize,region,ntimes,hint) else: print('Input type <:%s:> not recognzied for create'%atype) def svdCompose(d,indx): """ Usage: import pyJvsip as pv # get pyJvsip matrix A from some process d=A.svd # create an index vector (indx) of singular values of interest. C=svdCompose(d,indx) Returns a matrix reconstituted from selected singular values. Note: d above is a tuble. See svd method info. Note: the indices in indx should be less than the length of d[1] Note: you can create a new tuple, say g=(d[0],s,d[2]) if you want to create a new matrix but not use the original singular values. Note: C=svdCompose(d,create('vview_vi',d[1].length).ramp(0,1)) will return (an estimate of) the original matrix A. """ assert 'vview_vi' in getType(indx)[2] assert type(d) is tuple assert 'mview' in getType(d[0])[2] assert 'vview' in getType(d[1])[2] assert 'mview' in getType(d[2])[2] r=create(d[0].type,d[0].collength,d[2].collength).fill(0.0) for i in range(indx.length): j=indx[i] r += d[0].colview(j).outer(d[1][j],d[2].colview(j)) return r def listToJv(t,a): """ Usage: listToJv(t,a) will attempt to create a pyJvsip view of type t and copy the list <a> into it. Lists are very general. It is easy to create a list that listToJv can not handle. Lists must agree with the data type t. Currently only vectors of type float and double are supported. """ assert t in ['vview_d','vview_f','cvview_d','cvview_d','vview_vi'], 'Requested type not supported' assert isinstance(a,list),'Input must be a list' n=len(a) v=create(t,n) if 'cvview_d' in t: for i in range(n): s=a[i] v[i]=vsip_cmplx_d(s.real,s.imag) elif 'cvview_f' in t: for i in range(n): s=a[i] v[i]=vsip_cmplx_f(s.real,s.imag) else: for i in range(n): v[i] = a[i] return v def sizeOut(s1,s2,opMat,opSide): """ Return size of output matrix after matrix product Usage: m,n=sizeOut(s1,s2,opMat,opSide) where: s1 is size of prime matrix. s2 is size of other matrix size of output matrix after matrix product is (m,n) opMat indicates if prime matrix is transposed or not before matrix product. opSide indicates location of prime matrix as Left or Right """ if opSide==VSIP_MAT_LSIDE or opSide=='LSIDE': if opMat == VSIP_MAT_NTRANS or opMat == 'NTRANS': assert s1[1] == s2[0],'Matrices are not compliant for matrix product.' m = s1[0];n = s2[1] else: #must be TRANS or HERM assert s1[0] == s2[0],'Matrices are not compliant for matrix product.' m = s1[1];n = s2[1] else: #must be RSIDE if opMat == VSIP_MAT_NTRANS or opMat == 'NTRANS': assert s1[0] == s2[1],'Matrices are not compliant for matrix product.' m = s2[0]; n = s1[1] else: #must be TRANS or HERM assert s1[1] == s2[1],'Matrices are not compliant for matrix product.' m = s2[0]; n = s1[0] return(m,n) def sizeIn(s,opMat,opSide): """ Return size of input matrix for matrix product Usage: m,n=sizeOut(s,opMat,opSide) where: s is size of prime matrix. size of input matrix is (m,n) opMat indicates if prime matrix is transposed or not before matrix product. opSide indicates location of prime matrix as Left or Right Note m or n will be free. This is indicated be a zero for that entry. """ if opSide==VSIP_MAT_LSIDE or opSide=='LSIDE': if opMat == VSIP_MAT_NTRANS or opMat == 'NTRANS': m = s[1]; n=0; else: #must be TRANS or HERM m = s[0]; n=0; else: #must be RSIDE if opMat == VSIP_MAT_NTRANS or opMat == 'NTRANS': m = 0; n = s[0] else: #must be TRANS or HERM m = 0; n = s[1] return(m,n) def reshape(x,cl,rl): """Return matrix view of vector; column major. In Place Operation. """ assert 'vview' in x.type,'input view must be a vector for reshape' assert cl*rl==x.length, 'size of input data must agree with size of output data' return x.block.bind(x.offset,x.stride,cl,x.stride*cl,rl) def flattenByCol(A): """ Turn matrix into vector by column. Out of place operation """ B=A.copycm return B.block.bind(0,1,A.rowlength*A.collength) def flattenByRow(A): """ Turn matrix into vector by row. Out of place operation """ B=A.copyrm return B.block.bind(0,1,A.rowlength*A.collength) <file_sep>#include<vsip.h> #include"svd.h" static void cmprint_d(vsip_cmview_d *A){ vsip_length n=vsip_cmgetrowlength_d(A); vsip_length m=vsip_cmgetcollength_d(A); vsip_index i,j; printf("["); for(i=0; i<m; i++){ for(j=0; j<n; j++){ vsip_cscalar_d a=vsip_cmget_d(A,i,j); printf("%.5f%+.5fi ",a.r,a.i); if(j < n - 1) printf(","); } printf(";\n") ; } printf("]\n"); } static void vprint_d(vsip_vview_d *v){ vsip_index i; printf("["); for(i=0; i<vsip_vgetlength_d(v); i++) printf("%+.5f ",vsip_vget_d(v,i)); printf("]\n"); } static vsip_scalar_d cmnormFro_d(vsip_cmview_d *v){ vsip_mview_d* re=vsip_mrealview_d(v); vsip_mview_d* im=vsip_mimagview_d(v); return vsip_sqrt_d(vsip_msumsqval_d(re)+vsip_msumsqval_d(im)); vsip_mdestroy_d(re);vsip_mdestroy_d(im); } static vsip_scalar_d ccheckBack_d(vsip_cmview_d* A,vsip_cmview_d* L, vsip_vview_d* d, vsip_cmview_d* R){ vsip_scalar_d c; vsip_cmview_d *VH=vsip_cmcreate_d(vsip_cmgetcollength_d(R),vsip_cmgetrowlength_d(R),VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *Ac=vsip_cmcreate_d(vsip_cmgetcollength_d(A),vsip_cmgetrowlength_d(A),VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_d *L0=vsip_cmsubview_d(L,0,0,vsip_cmgetcollength_d(L),vsip_vgetlength_d(d)); vsip_cmcopy_d_d(R,VH); vsip_rvcmmul_d(d,VH,VSIP_COL,VH); vsip_cmprod_d(L0,VH,Ac); vsip_cmsub_d(A,Ac,Ac); c = cmnormFro_d(Ac); vsip_cmalldestroy_d(VH);vsip_cmalldestroy_d(Ac);vsip_cmdestroy_d(L0); return c; } int main(int argc, char* argv[]){ int init=vsip_init((void*)0); if(init) exit(0); csvdObj_d s; vsip_cmview_d *A = vsip_cmcreate_d(8,6,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *Ar=vsip_mrealview_d(A); vsip_mview_d *Ai=vsip_mimagview_d(A); vsip_vview_d *ar = vsip_vbind_d(vsip_mgetblock_d(Ar),0,1,48); vsip_vview_d *ai = vsip_vbind_d(vsip_mgetblock_d(Ai),0,1,48); vsip_randstate *rnd=vsip_randcreate(5,1,1,VSIP_PRNG); vsip_vrandn_d(rnd,ar); vsip_vrandn_d(rnd,ai); cmprint_d(A); printf("\n"); s=csvd_d(A); cmprint_d(s.L); printf("\n"); vprint_d(s.d); printf("\n"); cmprint_d(s.R); printf("Check value %f\n",ccheckBack_d(A,s.L,s.d,s.R)); vsip_cmalldestroy_d(s.L); vsip_cmalldestroy_d(s.R); vsip_valldestroy_d(s.d); vsip_mdestroy_d(Ar);vsip_mdestroy_d(Ai); vsip_vdestroy_d(ar); vsip_vdestroy_d(ai); vsip_cmalldestroy_d(A); vsip_randdestroy(rnd); vsip_finalize((void*)0); return 1; } <file_sep>#include"pyVsip.h" PyObject *cvcopyToList_f(vsip_cvview_f *v){ PyObject *cval; vsip_length N = vsip_cvgetlength_f(v); PyObject *retval = PyList_New(N); vsip_index i; for(i=0; i<N; i++){ vsip_cscalar_f x = vsip_cvget_f(v,i); double re = (double)x.r; double im = (double)x.i; cval = PyComplex_FromDoubles(re,im); PyList_SetItem(retval,i,cval); } return retval; } PyObject *cvcopyToList_d(vsip_cvview_d *v){ PyObject *cval; vsip_length N = vsip_cvgetlength_d(v); PyObject *retval = PyList_New(N); vsip_index i; for(i=0; i<N; i++){ vsip_cscalar_d x = vsip_cvget_d(v,i); double re = (double)x.r; double im = (double)x.i; cval = PyComplex_FromDoubles(re,im); PyList_SetItem(retval,i,cval); } return retval; } PyObject *vcopyToList_f(vsip_vview_f *v){ vsip_length N = vsip_vgetlength_f(v); PyObject *retval = PyList_New(N); vsip_index i; for(i=0; i<N; i++){ double x = (double)vsip_vget_f(v,i); PyList_SetItem(retval,i,PyFloat_FromDouble(x)); } return retval; } PyObject *vcopyToList_d(vsip_vview_d *v){ vsip_length N = vsip_vgetlength_d(v); PyObject *retval = PyList_New(N); vsip_index i; for(i=0; i<N; i++){ double x = (double)vsip_vget_d(v,i); PyList_SetItem(retval,i,PyFloat_FromDouble(x)); } return retval; } PyObject *vcopyToList_i(vsip_vview_i *v){ vsip_length N = vsip_vgetlength_i(v); PyObject *retval = PyList_New(N); PyObject *aval; vsip_index i; for(i=0; i<N; i++){ int x = (int)vsip_vget_i(v,i); aval=Py_BuildValue("i",x); PyList_SetItem(retval,i,aval); } return retval; } PyObject *vcopyToList_si(vsip_vview_si *v){ vsip_length N = vsip_vgetlength_si(v); PyObject *retval = PyList_New(N); PyObject *aval; vsip_index i; for(i=0; i<N; i++){ long int x = (long int)vsip_vget_si(v,i); aval=Py_BuildValue("i",x); PyList_SetItem(retval,i,aval); } return retval; } PyObject *vcopyToList_vi(vsip_vview_vi *v){ vsip_length N = vsip_vgetlength_vi(v); PyObject *retval = PyList_New(N); PyObject *aval; vsip_index i; for(i=0; i<N; i++){ long int x = (long int)vsip_vget_vi(v,i); aval=Py_BuildValue("l",x); PyList_SetItem(retval,i,aval); } return retval; } PyObject *vcopyToList_uc(vsip_vview_uc *v){ vsip_length N = vsip_vgetlength_uc(v); PyObject *retval = PyList_New(N); PyObject *aval; vsip_index i; for(i=0; i<N; i++){ int x = (int)vsip_vget_uc(v,i); aval=Py_BuildValue("i",x); PyList_SetItem(retval,i,aval); } return retval; } PyObject *vcopyToList_mi(vsip_vview_mi *v){ PyObject *miVal; vsip_length N = vsip_vgetlength_mi(v); PyObject *retval = PyList_New(N); vsip_index i; for(i=0; i<N; i++){ vsip_scalar_mi x = vsip_vget_mi(v,i); miVal = Py_BuildValue("(ii)",x.r,x.c); PyList_SetItem(retval,i,miVal); } return retval; } /* matrix copy by row */ PyObject *cmcopyToListByRow_f(vsip_cmview_f *v){ PyObject *cval; vsip_length M = vsip_cmgetcollength_f(v); vsip_length N = vsip_cmgetrowlength_f(v); PyObject *retval = PyList_New(M); vsip_index i,j; for(i=0; i<M; i++){ PyObject *row = PyList_New(N); for(j=0; j<N; j++){ vsip_cscalar_f x = vsip_cmget_f(v,i,j); double re = (double)x.r; double im = (double)x.i; cval = PyComplex_FromDoubles(re,im); PyList_SetItem(row,j,cval); } PyList_SetItem(retval,i,row); } return retval; } PyObject *mcopyToListByRow_f(vsip_mview_f *v){ vsip_length M = vsip_mgetcollength_f(v); vsip_length N = vsip_mgetrowlength_f(v); PyObject *retval = PyList_New(M); vsip_index i,j; for(i=0; i<M; i++){ PyObject *row = PyList_New(N); for(j=0; j<N; j++){ double x = (double)vsip_mget_f(v,i,j); PyList_SetItem(row,j,PyFloat_FromDouble(x)); } PyList_SetItem(retval,i,row); } return retval; } PyObject *cmcopyToListByRow_d(vsip_cmview_d *v){ PyObject *cval; vsip_length M = vsip_cmgetcollength_d(v); vsip_length N = vsip_cmgetrowlength_d(v); PyObject *retval = PyList_New(M); vsip_index i,j; for(i=0; i<M; i++){ PyObject *row = PyList_New(N); for(j=0; j<N; j++){ vsip_cscalar_d x = vsip_cmget_d(v,i,j); double re = (double)x.r; double im = (double)x.i; cval = PyComplex_FromDoubles(re,im); PyList_SetItem(row,j,cval); } PyList_SetItem(retval,i,row); } return retval; } PyObject *mcopyToListByRow_d(vsip_mview_d *v){ vsip_length M = vsip_mgetcollength_d(v); vsip_length N = vsip_mgetrowlength_d(v); PyObject *retval = PyList_New(M); vsip_index i,j; for(i=0; i<M; i++){ PyObject *row = PyList_New(N); for(j=0; j<N; j++){ double x = (double)vsip_mget_d(v,i,j); PyList_SetItem(row,j,PyFloat_FromDouble(x)); } PyList_SetItem(retval,i,row); } return retval; } PyObject *mcopyToListByRow_i(vsip_mview_i *v){ vsip_length M = vsip_mgetcollength_i(v); vsip_length N = vsip_mgetrowlength_i(v); PyObject *retval = PyList_New(M); PyObject *aval; vsip_index i,j; for(i=0; i<M; i++){ PyObject *row = PyList_New(N); for(j=0; j<N; j++){ int x = ( int)vsip_mget_i(v,i,j); aval=Py_BuildValue("i",x); PyList_SetItem(row,j,aval); } PyList_SetItem(retval,i,row); } return retval; } PyObject *mcopyToListByRow_si(vsip_mview_si *v){ vsip_length M = vsip_mgetcollength_si(v); vsip_length N = vsip_mgetrowlength_si(v); PyObject *retval = PyList_New(M); PyObject *aval; vsip_index i,j; for(i=0; i<M; i++){ PyObject *row = PyList_New(N); for(j=0; j<N; j++){ int x = ( int)vsip_mget_si(v,i,j); aval=Py_BuildValue("i",x); PyList_SetItem(row,j,aval); } PyList_SetItem(retval,i,row); } return retval; } PyObject *mcopyToListByRow_uc(vsip_mview_uc *v){ vsip_length M = vsip_mgetcollength_uc(v); vsip_length N = vsip_mgetrowlength_uc(v); PyObject *retval = PyList_New(M); PyObject *aval; vsip_index i,j; for(i=0; i<M; i++){ PyObject *row = PyList_New(N); for(j=0; j<N; j++){ int x = ( int)vsip_mget_uc(v,i,j); aval=Py_BuildValue("i",x); PyList_SetItem(row,j,aval); } PyList_SetItem(retval,i,row); } return retval; } /* matrix copy by col */ PyObject *cmcopyToListByCol_f(vsip_cmview_f *v){ PyObject *cval; vsip_length M = vsip_cmgetcollength_f(v); vsip_length N = vsip_cmgetrowlength_f(v); PyObject *retval = PyList_New(M); vsip_index i,j; for(j=0; j<N; j++){ PyObject *col = PyList_New(M); for(i=0; i<M; i++){ vsip_cscalar_f x = vsip_cmget_f(v,i,j); double re = (double)x.r; double im = (double)x.i; cval = PyComplex_FromDoubles(re,im); PyList_SetItem(col,i,cval); } PyList_SetItem(retval,j,col); } return retval; } PyObject *mcopyToListByCol_f(vsip_mview_f *v){ vsip_length M = vsip_mgetcollength_f(v); vsip_length N = vsip_mgetrowlength_f(v); PyObject *retval = PyList_New(M); vsip_index i,j; for(j=0; j<N; j++){ PyObject *col = PyList_New(M); for(i=0; i<M; i++){ double x = (double)vsip_mget_f(v,i,j); PyList_SetItem(col,i,PyFloat_FromDouble(x)); } PyList_SetItem(retval,j,col); } return retval; } PyObject *cmcopyToListByCol_d(vsip_cmview_d *v){ PyObject *cval; vsip_length M = vsip_cmgetcollength_d(v); vsip_length N = vsip_cmgetrowlength_d(v); PyObject *retval = PyList_New(M); vsip_index i,j; for(j=0; j<N; j++){ PyObject *col = PyList_New(M); for(i=0; i<M; i++){ vsip_cscalar_d x = vsip_cmget_d(v,i,j); double re = (double)x.r; double im = (double)x.i; cval = PyComplex_FromDoubles(re,im); PyList_SetItem(col,i,cval); } PyList_SetItem(retval,j,col); } return retval; } PyObject *mcopyToListByCol_d(vsip_mview_d *v){ vsip_length M = vsip_mgetcollength_d(v); vsip_length N = vsip_mgetrowlength_d(v); PyObject *retval = PyList_New(M); vsip_index i,j; for(j=0; j<N; j++){ PyObject *col = PyList_New(M); for(i=0; i<M; i++){ double x = (double)vsip_mget_d(v,i,j); PyList_SetItem(col,i,PyFloat_FromDouble(x)); } PyList_SetItem(retval,j,col); } return retval; } PyObject *mcopyToListByCol_i(vsip_mview_i *v){ vsip_length M = vsip_mgetcollength_i(v); vsip_length N = vsip_mgetrowlength_i(v); PyObject *retval = PyList_New(M); PyObject *aval; vsip_index i,j; for(j=0; j<N; j++){ PyObject *col = PyList_New(M); for(i=0; i<M; i++){ int x = (int)vsip_mget_i(v,i,j); aval=Py_BuildValue("i",x); PyList_SetItem(col,i,aval); } PyList_SetItem(retval,j,col); } return retval; } PyObject *mcopyToListByCol_si(vsip_mview_si *v){ vsip_length M = vsip_mgetcollength_si(v); vsip_length N = vsip_mgetrowlength_si(v); PyObject *retval = PyList_New(M); PyObject *aval; vsip_index i,j; for(j=0; j<N; j++){ PyObject *col = PyList_New(M); for(i=0; i<M; i++){ int x = ( int)vsip_mget_si(v,i,j); aval=Py_BuildValue("i",x); PyList_SetItem(col,i,aval); } PyList_SetItem(retval,j,col); } return retval; } PyObject *mcopyToListByCol_uc(vsip_mview_uc *v){ vsip_length M = vsip_mgetcollength_uc(v); vsip_length N = vsip_mgetrowlength_uc(v); PyObject *retval = PyList_New(M); PyObject *aval; vsip_index i,j; for(j=0; j<N; j++){ PyObject *col = PyList_New(M); for(i=0; i<M; i++){ int x = ( int)vsip_mget_uc(v,i,j); aval=Py_BuildValue("i",x); PyList_SetItem(col,i,aval); } PyList_SetItem(retval,j,col); } return retval; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmrecip_f.h,v 2.0 2003/02/22 15:23:21 judd Exp $ */ #include"VU_cmprintm_f.include" static void cmrecip_f(void){ printf("\n*******\nTEST cmrecip_f\n\n"); { vsip_scalar_f data_r[] = {M_PI/8.0, M_PI/4.0, M_PI/3.0, M_PI/1.5, 1.25 * M_PI, 1.75 * M_PI}; vsip_scalar_f data_i[] = {1, 2, -1, -2, 3, 4}; vsip_scalar_f ans_r[] = {0.3402, 0.1701, 0.4995, 0.2497, 0.1608, 0.1189}; vsip_scalar_f ans_i[] = { -0.8664, -0.4332, 0.4770, 0.2385, -0.1228, -0.0865}; vsip_cblock_f *block = vsip_cblockbind_f(data_r,data_i,6,VSIP_MEM_NONE); vsip_cblock_f *ans_block = vsip_cblockbind_f(ans_r,ans_i,6,VSIP_MEM_NONE); vsip_cmview_f *a = vsip_cmbind_f(block,0,2,3,1,2); vsip_cmview_f *ansm = vsip_cmbind_f(ans_block,0,2,3,1,2); vsip_cmview_f *b = vsip_cmcreate_f(3,2,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *chk = vsip_cmcreate_f(3,2,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *chk_r = vsip_mcreate_f(3,2,VSIP_COL,VSIP_MEM_NONE); vsip_cblockadmit_f(block,VSIP_TRUE); vsip_cblockadmit_f(ans_block,VSIP_TRUE); printf("test out of place, compact, user \"a\", vsipl \"b\"\n"); vsip_cmrecip_f(a,b); printf("cmrecip_f(a,b)\n matrix a\n");VU_cmprintm_f("8.6",a); printf("matrix b\n");VU_cmprintm_f("8.6",b); printf("answer\n");VU_cmprintm_f("8.4",ansm); vsip_cmsub_f(b,ansm,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); printf("check cmrecip_f in place\n"); vsip_cmrecip_f(a,a); vsip_cmsub_f(a,ansm,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a); vsip_cmalldestroy_f(b); vsip_mdestroy_f(chk_r); vsip_cmalldestroy_f(chk); vsip_cmalldestroy_f(ansm); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D881 */ #ifndef _vsip_cfirattributes_f_h #define _vsip_cfirattributes_f_h 1 #include"VI.h" struct vsip_cfirattributes_f{ vsip_cvview_f *h; vsip_cvview_f *s; vsip_length N; vsip_length M; vsip_length p; vsip_length D; int ntimes; vsip_symmetry symm; vsip_alg_hint hint; vsip_obj_state state; }; #endif /* _vsip_cfirattributes_f_h */ <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_tviewattributes_d.h,v 2.0 2003/02/22 15:48:15 judd Exp $ */ #ifndef _vsip_tviewattributes_d_h #define _vsip_tviewattributes_d_h 1 #include"vsip.h" #include"VI.h" #include"vsip_blockattributes_d.h" struct vsip_tviewattributes_d { vsip_block_d* block; /* memory data block object */ vsip_offset offset; vsip_stride x_stride; vsip_stride y_stride; vsip_stride z_stride; vsip_length x_length; vsip_length y_length; vsip_length z_length; int markings; /* valid|destoyed tview object */ }; #endif /* _vsip_tviewattributes_d_h */ <file_sep>from vsip import * def __isSizeCompatible(a,b): if 'mview' in a.type and 'mview' in b.type: if (a.rowlength == b.rowlength) and (a.collength == b.collength): return True elif 'vview' in a.type and 'vview' in b.type: if a.length == b.length: return True else: return False def __isView(a): return 'pyJvsip' in repr(a) def add(a,b,c): """ The add function includes view+view adds and scalar+view adds. """ f={'vview_dvview_dvview_d':vsip_vadd_d,'vview_fvview_fvview_f':vsip_vadd_f, 'vview_ivview_ivview_i':vsip_vadd_i,'vview_sivview_sivview_si':vsip_vadd_si, 'vview_ucvview_ucvview_uc':vsip_vadd_uc,'mview_dmview_dmview_d':vsip_madd_d, 'mview_fmview_fmview_f':vsip_madd_f,'mview_imview_imview_i':vsip_madd_i, 'mview_simview_simview_si':vsip_madd_si,'mview_dcmview_dcmview_d':vsip_rcmadd_d, 'mview_fcmview_fcmview_f':vsip_rcmadd_f,'vview_vivview_vivview_vi':vsip_vadd_vi, 'cvview_dcvview_dcvview_d':vsip_cvadd_d,'cvview_fcvview_fcvview_f':vsip_cvadd_f, 'cmview_dcmview_dcmview_d':vsip_cmadd_d,'cmview_fcmview_fcmview_f':vsip_cmadd_f, 'vview_dcvview_dcvview_d':vsip_rcvadd_d,'vview_fcvview_fcvview_f':vsip_rcvadd_f, 'scalarmview_dmview_d':vsip_smadd_d, 'scalarmview_fmview_f':vsip_smadd_f, 'scalarvview_dvview_d':vsip_svadd_d, 'scalarvview_fvview_f':vsip_svadd_f, 'scalarvview_ivview_i':vsip_svadd_i, 'scalarcmview_dcmview_d':vsip_rscmadd_d, 'scalarcmview_fcmview_f':vsip_rscmadd_f, 'scalarcvview_dcvview_d':vsip_rscvadd_d, 'scalarcvview_fcvview_f':vsip_rscvadd_f, 'scalarivview_sivview_si':vsip_svadd_si, 'scalarcvview_ucvview_uc':vsip_svadd_uc, 'scalarvview_vivview_vi':vsip_svadd_vi, 'cscalarcmview_dcmview_d':vsip_csmadd_d, 'cscalarcmview_fcmview_f':vsip_csmadd_f, 'cscalarcvview_dcvview_d':vsip_csvadd_d, 'cscalarcvview_fcvview_f':vsip_csvadd_f} assert __isView(b),'Argument two must be a pyJvsip view object in add' assert __isView(c),'Argument three must be a pyJvsip view object in add' assert __isSizeCompatible(b,c),'Size error in add function' if isinstance(a,int) or isinstance(a,float): t='scalar'+b.type+c.type elif isinstance(a,complex): t='cscalar'+b.type+c.type else: assert __isView(a),'Argument one must be a scalar or a pyJvsip view object in add' t=a.type+b.type+c.type assert t in f, 'Type <:'+t+':> not recognized for add' if 'cscalar' in t: if 'view_d' in t: f[t](vsip_cmplx_d(a.real,a.imag),b.vsip,c.vsip) else: f[t](vsip_cmplx_f(a.real,a.imag),b.vsip,c.vsip) elif 'scalar' in t: f[t](a,b.vsip,c.vsip) else: f[t](a.vsip,b.vsip,c.vsip) return c def div(a,b,c): """ The div function includes view/view, scalar/view, and view/(real scalar) . """ err1='Argument one and argument three must have the same size if argument one is not a scalar in div' err2='Argument two and argument three must have the same size if argument two is not a scalar in div' f={'cmview_dcmview_dcmview_d':vsip_cmdiv_d, 'cmview_fcmview_fcmview_f':vsip_cmdiv_f, 'cmview_dscalarcmview_d':vsip_cmrsdiv_d, 'cmview_fscalarcmview_f':vsip_cmrsdiv_f, 'cmview_dmview_dcmview_d':vsip_crmdiv_d, 'cmview_fmview_fcmview_f':vsip_crmdiv_f, 'cvview_dvview_dcvview_d':vsip_crvdiv_d, 'cvview_fvview_fcvview_f':vsip_crvdiv_f, 'cvview_dcvview_dcvview_d':vsip_cvdiv_d, 'cvview_fcvview_fcvview_f':vsip_cvdiv_f, 'mview_dmview_dmview_d':vsip_mdiv_d, 'mview_fmview_fmview_f':vsip_mdiv_f, 'mview_dscalarmview_d':vsip_msdiv_d, 'mview_fscalarmview_f':vsip_msdiv_f, 'mview_dcmview_dcmview_d':vsip_rcmdiv_d, 'mview_fcmview_fcmview_f':vsip_rcmdiv_f, 'vview_dcvview_dcvview_d':vsip_rcvdiv_d, 'vview_fcvview_fcvview_f':vsip_rcvdiv_f, 'vview_dvview_dvview_d':vsip_vdiv_d, 'vview_fvview_fvview_f':vsip_vdiv_f, 'vview_dscalarvview_d':vsip_vsdiv_d, 'vview_fscalarvview_f':vsip_vsdiv_f, 'cvview_dscalarcvview_d':vsip_cvrsdiv_d, 'cvview_fscalarcvview_f':vsip_cvrsdiv_f, 'scalarcmview_dcmview_d':vsip_rscmdiv_d, 'scalarcmview_fcmview_f':vsip_rscmdiv_f, 'scalarcvview_dcvview_d':vsip_rscvdiv_d, 'scalarcvview_fcvview_f':vsip_rscvdiv_f, 'scalarmview_dmview_d':vsip_smdiv_d, 'scalarmview_fmview_f':vsip_smdiv_f, 'scalarvview_dvview_d':vsip_svdiv_d, 'scalarvview_fvview_f':vsip_svdiv_f, 'cscalarcmview_dcmview_d':vsip_csmdiv_d, 'cscalarcmview_fcmview_f':vsip_csmdiv_f, 'cscalarcvview_dcvview_d':vsip_csvdiv_d, 'cscalarcvview_fcvview_f':vsip_csvdiv_f} assert 'pyJvsip' in repr(c),'Argument 3 is not a pyJvsip view in div' t3=c.type if isinstance(a,int) or isinstance(a,float): t1='scalar' elif isinstance(a,complex): t1='cscalar' else: assert 'pyJvsip' in repr(a),'Argument one must be a scalar or a pyJvsip view object in div' assert __isSizeCompatible(a,c), err1 t1=a.type if isinstance(b,int) or isinstance(b,float): t2='scalar' else: assert 'pyJvsip' in repr(b),'Argument two must be a real scalar or a pyJvsip view object in div' assert __isSizeCompatible(b,c), err2 t2=b.type t=t1+t2+t3 assert t in f,'Type <:'+t+':> not recognized for div' if 'cscalar' in t1: if 'vview_d' in t3: f[t](vsip_cmplx_d(a.real,a.imag),b.vsip,c.vsip) else: f[t](vsip_cmplx_f(a.real,a.imag),b.vsip,c.vsip) elif 'scalar' in t1: f[t](a,b.vsip,c.vsip) elif 'scalar' in t2: f[t](a.vsip,b,c.vsip) else: f[t](a.vsip,b.vsip,c.vsip) return c def mul(a,b,c): """ The mul function includes view+view muls and scalar+view muls. """ f={'cmview_dcmview_dcmview_d':vsip_cmmul_d, 'cmview_fcmview_fcmview_f':vsip_cmmul_f, 'cscalarcmview_dcmview_d':vsip_csmmul_d, 'cscalarcmview_fcmview_f':vsip_csmmul_f, 'cscalarcvview_dcvview_d':vsip_csvmul_d, 'cscalarcvview_fcvview_f':vsip_csvmul_f, 'cvview_dcvview_dcvview_d':vsip_cvmul_d, 'cvview_fcvview_fcvview_f':vsip_cvmul_f, 'mview_dmview_dmview_d':vsip_mmul_d, 'mview_fmview_fmview_f':vsip_mmul_f, 'mview_dcmview_dcmview_d':vsip_rcmmul_d, 'mview_fcmview_fcmview_f':vsip_rcmmul_f, 'vview_dcvview_dcvview_d':vsip_rcvmul_d, 'vview_fcvview_fcvview_f':vsip_rcvmul_f, 'scalarcmview_dcmview_d':vsip_rscmmul_d, 'scalarcmview_fcmview_f':vsip_rscmmul_f, 'scalarcvview_dcvview_d':vsip_rscvmul_d, 'scalarcvview_fcvview_f':vsip_rscvmul_f, 'scalarmview_dmview_d':vsip_smmul_d, 'scalarmview_fmview_f':vsip_smmul_f, 'scalarvview_dvview_d':vsip_svmul_d, 'scalarvview_fvview_f':vsip_svmul_f, 'scalarvview_ivview_i':vsip_svmul_i, 'scalarvview_sivview_si':vsip_svmul_si, 'scalarvview_ucvview_uc':vsip_svmul_uc, 'vview_dvview_dvview_d':vsip_vmul_d, 'vview_fvview_fvview_f':vsip_vmul_f, 'vview_ivview_ivview_i':vsip_vmul_i, 'vview_sivview_sivview_si':vsip_vmul_si, 'vview_ucvview_ucvview_uc':vsip_vmul_uc} assert 'pyJvsip' in repr(b),'Argument two must be a pyJvsip view object in mul' assert 'pyJvsip' in repr(c),'Argument three must be a pyJvsip view object in mul' assert __isSizeCompatible(b,c),'Size error in mul function' if isinstance(a,int) or isinstance(a,float): t='scalar'+b.type+c.type elif isinstance(a,complex): t='cscalar'+b.type+c.type else: assert 'pyJvsip' in repr(a),'Argument one must be a scalar or a pyJvsip view object in mul' t=a.type+b.type+c.type assert t in f, 'Type <:'+t+':> not recognized for mul' if 'cscalar' in t: if 'view_d' in t: f[t](vsip_cmplx_d(a.real,a.imag),b.vsip,c.vsip) else: f[t](vsip_cmplx_f(a.real,a.imag),b.vsip,c.vsip) elif 'scalar' in t: f[t](a,b.vsip,c.vsip) else: f[t](a.vsip,b.vsip,c.vsip) return c def jmul(a,b,c): f={'cmview_dcmview_dcmview_d':vsip_cmjmul_d,'cmview_fcmview_fcmview_f':vsip_cmjmul_f, 'cvview_dcvview_dcvview_d':vsip_cvjmul_d,'cvview_fcvview_fcvview_f':vsip_cvjmul_f} assert __isView(a),'Argument two must be a pyJvsip view object in jmul' assert __isView(b),'Argument two must be a pyJvsip view object in jmul' assert __isView(c),'Argument two must be a pyJvsip view object in jmul' t=a.type+b.type+c.type assert t in f, 'Type <:'+t+':> not recognized for jmul' assert __isSizeCompatible(a,c), 'Argument one and argument three must be the same size in jmul' assert __isSizeCompatible(b,c), 'Argument two and argument three must be the same size in jmul' f[t](a.vsip,b.vsip,c.vsip) return c def vmmul(a,b,c): """ For Vector Matrix multiply along Rows or Along columns in C VSIPL uses a vsip_major argument. For pyJvsip if the first arguments major attribute is 'COL' then this is done element-wise along the columns; otherwise it is done element-wise along the rows. It is easier to set the major attribute than to check it. Usage mmul(a.COL,b,c) is equivalent to vsip_vmmul_f(a,b,VSIP_COL,c) mmul(a.ROW,b,c) is equivalent to vsip_vmmul_f(a,b,VSIP_ROW,c) """ err1='The vector length of argument 1 for by column must equal the column length of argument 2' err2='The vector length of argument 1 for by row must equal the row length of argument 2' f={'cvview_dcmview_dcmview_d':vsip_cvmmul_d, 'cvview_fcmview_fcmview_f':vsip_cvmmul_f, 'vview_dmview_dmview_d':vsip_vmmul_d, 'vview_fmview_fmview_f':vsip_vmmul_f, 'vview_dcmview_dcmview_d':vsip_rvcmmul_d, 'vview_fcmview_fcmview_f':vsip_rvcmmul_f} assert 'pyJvsip' in repr(a),'Argument one must be a pyJvsip view object in mmul' assert 'pyJvsip' in repr(b),'Argument two must be a pyJvsip view object in mmul' assert 'pyJvsip' in repr(c),'Argument three must be a pyJvsip view object in mmul' t=a.type+b.type+c.type assert t in f, 'Type <:'+t+':> not recognized for mmul' assert __isSizeCompatible(b,c), 'Argument two and argument three must be the same size in mmul' if 'COL' in a.major: assert a.length == b.collength, err1 f[t](a.vsip,b.vsip,VSIP_COL,c.vsip) else: assert a.length == b.rowlength, err2 f[t](a.vsip,b.vsip,VSIP_ROW,c.vsip) return c def sub(a,b,c): """ sub(a,b,c) means c=arg1-arg2; arg1 may be a scalar or a view It is the responsibility of the user to ensure data is properly sized when using scalars. For instance subtracting a short int vector from a large integer value and placing the results in a short int vector will result in overflows and unpredictable results. """ f={ 'cmview_dcmview_dcmview_d':vsip_cmsub_d, 'cmview_fcmview_fcmview_f':vsip_cmsub_f, 'cmview_dmview_dcmview_d':vsip_crmsub_d, 'cmview_fmview_fcmview_f':vsip_crmsub_f, 'cvview_dvview_dcvview_d':vsip_crvsub_d, 'cvview_fvview_fcvview_f':vsip_crvsub_f, 'cscalarcmview_dcmview_d':vsip_csmsub_d, 'cscalarcmview_fcmview_f':vsip_csmsub_f, 'cscalarcvview_dcvview_d':vsip_csvsub_d, 'cscalarcvview_fcvview_f':vsip_csvsub_f, 'cvview_dcvview_dcvview_d':vsip_cvsub_d, 'cvview_fcvview_fcvview_f':vsip_cvsub_f, 'mview_dmview_dmview_d':vsip_msub_d, 'mview_fmview_fmview_f':vsip_msub_f, 'mview_imview_imview_i':vsip_msub_i, 'mview_simview_simview_si':vsip_msub_si, 'mview_dcmview_dcmview_d':vsip_rcmsub_d, 'mview_fcmview_fcmview_f':vsip_rcmsub_f, 'vview_dcvview_dcvview_d':vsip_rcvsub_d, 'vview_fcvview_fcvview_f':vsip_rcvsub_f, 'scalarcmview_dcmview_d':vsip_rscmsub_d, 'scalarcmview_fcmview_f':vsip_rscmsub_f, 'scalarcvview_dcvview_d':vsip_rscvsub_d, 'scalarcvview_fcvview_f':vsip_rscvsub_f, 'scalarmview_dmview_d':vsip_smsub_d, 'scalarmview_fmview_f':vsip_smsub_f, 'scalarmview_imview_i':vsip_smsub_i, 'scalarmview_simview_si':vsip_smsub_si, 'scalarmview_simview_si':vsip_smsub_si, 'scalarvview_dvview_d':vsip_svsub_d, 'scalarvview_fvview_f':vsip_svsub_f, 'scalarvview_ivview_i':vsip_svsub_i, 'scalarvview_sivview_si':vsip_svsub_si, 'scalarvview_ucvview_uc':vsip_svsub_uc, 'scalarvview_vivview_vi':vsip_svsub_vi, 'vview_dvview_dvview_d':vsip_vsub_d, 'vview_fvview_fvview_f':vsip_vsub_f, 'vview_ivview_ivview_i':vsip_vsub_i, 'vview_sivview_sivview_si':vsip_vsub_si, 'vview_ucvview_ucvview_uc':vsip_vsub_uc} assert 'pyJvsip' in repr(b),'Argument two must be a pyJvsip view object in sub' assert 'pyJvsip' in repr(c),'Argument three must be a pyJvsip view object in sub' assert __isSizeCompatible(b,c),'Size error in sub function' if isinstance(a,int) or isinstance(a,float): t='scalar'+b.type+c.type elif isinstance(a,complex): t='cscalar'+b.type+c.type else: assert 'pyJvsip' in repr(a),'Argument one must be a scalar or a pyJvsip view object in sub' t=a.type+b.type+c.type assert t in f, 'Type <:'+t+':> not recognized for add' if 'cscalar' in t: if 'view_d' in t: f[t](vsip_cmplx_d(a.real,a.imag),b.vsip,c.vsip) else: f[t](vsip_cmplx_f(a.real,a.imag),b.vsip,c.vsip) elif 'scalar' in t: f[t](a,b.vsip,c.vsip) else: f[t](a.vsip,b.vsip,c.vsip) return c def expoavg(a,b,c): """ Usage: expoavg(a,b,c) Where: a is a real, float, scalar b is a vector view of type float, real or complex c is a vector view of the same type as b See VSIPL manual for additional information """ f={'scalarcmview_dcmview_d':vsip_cmexpoavg_d, 'scalarcmview_fcmview_f':vsip_cmexpoavg_f, 'scalarcvview_dcvview_d':vsip_cvexpoavg_d, 'scalarcvview_fcvview_f':vsip_cvexpoavg_f, 'scalarmview_dmview_d':vsip_mexpoavg_d, 'scalarmview_fmview_f':vsip_mexpoavg_f, 'scalarvview_dvview_d':vsip_vexpoavg_d, 'scalarvview_fvview_f':vsip_vexpoavg_f} assert isinstance(a,int) or isinstance(a,float),'Argument one of expoavg is a scalar float' assert 'pyJvsip' in repr(b) and 'vview' in b.type,'Argument two of expoavg should b a vector view' assert 'pyJvsip' in repr(c),'Argument three must be a pyJvsip view in expoavg' assert __isSizeCompatible(b,c),'Arguments two and three must be the same size in expoavg' assert c.type == b.type, 'Arguments two and three must be views of the same type' t='scalar'+b.type+c.type assert t in f,'Type <:'+t+':> not recognized for expoavg' f[t](a,b.vsip,c.vsip) return c def hypot(a,b,c): """ See VSIP specification for information on hypot. """ t0='pyJvsip' err1='Arguments must be a pyJvsip view' err2='Arguments are not of the same size' f={'mview_dmview_dmview_d':vsip_mhypot_d, 'mview_fmview_fmview_f':vsip_mhypot_f, 'vview_dvview_dvview_d':vsip_vhypot_d, 'vview_fvview_fvview_f':vsip_vhypot_f} assert t0 in repr(a) and t0 in repr(b) and t0 in repr(c),err1 assert __isSizeCompatible(a,c) and __isSizeCompatible(b,c),err2 t=a.type+b.type+c.type assert t in f,'Type <:'+t+':> not recognized for hypot' f[t](a.vsip,b.vsip,c.vsip) return c <file_sep>// // extensionMatrix.swift // SJVsip // // Created by <NAME> on 11/4/17. // Copyright © 2017 JVSIP. All rights reserved. // import Foundation import vsip extension Matrix { public static func + (left: Matrix, right: Matrix) -> Matrix { let retval = left.empty add(left, right, resultsIn: retval) return retval } public static func - (left: Matrix, right: Matrix) -> Matrix { let retval = left.empty sub(left, subtract: right, resultsIn: retval) return retval } public var normFro: Double { get { return (SJvsip.normFro(view: self).reald) } } public var qr: (Matrix, Matrix){ let qrd = QRD(type: self.type, columnLength: self.columnLength, rowLength: self.rowLength, qopt: VSIP_QRD_SAVEQ) let Q = Matrix(columnLength: qrd.columnLength, rowLength: qrd.columnLength, type: self.type, major: VSIP_ROW) let R = Matrix(columnLength: qrd.columnLength, rowLength: qrd.rowLength, type: self.type, major: VSIP_ROW) let aCopy = self.newCopy Q.fill(Scalar(0.0)) R.fill(Scalar(0.0)) Q.diagview.fill(Scalar(1.0)) let _ = qrd.decompose(aCopy) qrd.prodq(matrixOperator: VSIP_MAT_NTRANS, matrixSide: VSIP_MAT_LSIDE, matrix: Q) let Qt = Q.transview prod(Qt, times: self, resultsIn: R) return (Q,R) } public var sv: Vector { let svd = Svd(type: self.type, columnLength: self.columnLength, rowLength: self.rowLength, saveU: VSIP_SVD_UVNOS, saveV: VSIP_SVD_UVNOS) let acopy = self.newCopy return svd.decompose(acopy) } public var svd: (Matrix, Vector, Matrix) { let svd = Svd(type: self.type, columnLength: self.columnLength, rowLength: self.rowLength, saveU: VSIP_SVD_UVFULL, saveV: VSIP_SVD_UVFULL) let acopy = self.newCopy let s = svd.decompose(acopy) let U = svd.matU! let V = svd.matV! return (U,s,V) } public var svdPart: (Matrix, Vector, Matrix) { let svd = Svd(type: self.type, columnLength: self.columnLength, rowLength: self.rowLength, saveU: VSIP_SVD_UVFULL, saveV: VSIP_SVD_UVFULL) let acopy = self.newCopy let s = svd.decompose(acopy) let U = svd.matU! let V = svd.matV! if self.rowLength > self.columnLength { V.rowLength = s.length return (U,s,V.newCopy) } else { U.rowLength = s.length return (U.newCopy,s,V) } } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* new version done August 2000 */ /* $Id: */ #include"vsip.h" #include"vsip_mviewattributes_f.h" void (vsip_mprod3_f)( const vsip_mview_f* a, const vsip_mview_f* b, const vsip_mview_f* r) { /* st_r-> row stride, st_c=>col stride */ vsip_index j; vsip_stride a_st_r = a->row_stride * a->block->rstride, a_st_c = a->col_stride * a->block->rstride, b_st_r = b->row_stride * b->block->rstride, b_st_c = b->col_stride * b->block->rstride, r_st_r = r->row_stride * r->block->rstride, r_st_c = r->col_stride * r->block->rstride; vsip_length r_r_l = r->row_length; /* j_size */ vsip_scalar_f *ap = (a->block->array) + a->offset * a->block->rstride, *bp = (b->block->array) + b->offset * b->block->rstride, *rp = (r->block->array) + r->offset * r->block->rstride; vsip_scalar_f *ap0 = ap; vsip_scalar_f *b0p = bp; vsip_scalar_f *b1p = b0p + b_st_c; vsip_scalar_f *b2p = b1p + b_st_c; vsip_scalar_f *r0p = rp; vsip_scalar_f *r1p = r0p + r_st_c; vsip_scalar_f *r2p = r1p + r_st_c; register vsip_scalar_f a00,a01,a02; register vsip_scalar_f a10,a11,a12; register vsip_scalar_f a20,a21,a22; { vsip_stride chk_c = (a_st_c > 0) ? a_st_c : -a_st_c; vsip_stride chk_r = (a_st_r > 0) ? a_st_r : -a_st_r; if(chk_c < chk_r){ a00 = *ap0; ap0+=a_st_c; a10 = *ap0; ap0+=a_st_c; a20 = *ap0; ap0 = ap + a_st_r; a01 = *ap0; ap0+=a_st_c; a11 = *ap0; ap0+=a_st_c; a21 = *ap0; ap0 = ap + 2 * a_st_r; a02 = *ap0; ap0+=a_st_c; a12 = *ap0; ap0+=a_st_c; a22 = *ap0; } else { a00 = *ap0; ap0+=a_st_r; a01 = *ap0; ap0+=a_st_r; a02 = *ap0; ap0 = ap + a_st_c; a10 = *ap0; ap0+=a_st_r; a11 = *ap0; ap0+=a_st_r; a12 = *ap0; ap0 = ap + 2 * a_st_c; a20 = *ap0; ap0+=a_st_r; a21 = *ap0; ap0+=a_st_r; a22 = *ap0; } } for( j=0; j<r_r_l; j++){ register vsip_scalar_f b0 = *b0p, b1 = *b1p, b2 = *b2p; *r0p = a00 * b0 + a01 * b1 + a02 * b2; *r1p = a10 * b0 + a11 * b1 + a12 * b2; *r2p = a20 * b0 + a21 * b1 + a22 * b2; b0p += b_st_r; b1p += b_st_r; b2p += b_st_r; r0p += r_st_r; r1p += r_st_r; r2p += r_st_r; } } <file_sep>#include"vsipScalarFunctions.h" vsip_scalar_d vsip_acos_d(vsip_scalar_d a){ return (vsip_scalar_d) acos(a); } vsip_scalar_f vsip_acos_f(vsip_scalar_f a){ return (vsip_scalar_f) acos(a); } vsip_scalar_d vsip_asin_d(vsip_scalar_d a){ return (vsip_scalar_d) asin(a); } vsip_scalar_f vsip_asin_f(vsip_scalar_f a){ return (vsip_scalar_f) asin(a); } vsip_scalar_d vsip_atan_d(vsip_scalar_d a){ return (vsip_scalar_d) atan(a); } vsip_scalar_f vsip_atan_f(vsip_scalar_f a){ return (vsip_scalar_f) atan(a); } vsip_scalar_d vsip_cos_d(vsip_scalar_d a){ return (vsip_scalar_d)cos(a); } vsip_scalar_f vsip_cos_f(vsip_scalar_f a){ return (vsip_scalar_f)cos(a); } vsip_scalar_d vsip_cosh_d(vsip_scalar_d a){ return (vsip_scalar_d)cosh(a); } vsip_scalar_f vsip_cosh_f(vsip_scalar_f a){ return (vsip_scalar_f)cosh(a); } vsip_scalar_d vsip_sin_d(vsip_scalar_d a){ return (vsip_scalar_d)sin(a); } vsip_scalar_f vsip_sin_f(vsip_scalar_f a){ return (vsip_scalar_f)sin(a); } vsip_scalar_d vsip_sinh_d(vsip_scalar_d a){ return (vsip_scalar_d)sinh(a); } vsip_scalar_f vsip_sinh_f(vsip_scalar_f a){ return (vsip_scalar_f)sinh(a); } vsip_scalar_d vsip_ceil_d(vsip_scalar_d a){ return (vsip_scalar_d)ceil(a); } vsip_scalar_f vsip_ceil_f(vsip_scalar_f a){ return (vsip_scalar_f)ceil(a); } vsip_scalar_d vsip_atan2_d(vsip_scalar_d a, vsip_scalar_d b){ return (vsip_scalar_d) atan2(a,b); } vsip_scalar_f vsip_atan2_f(vsip_scalar_f a, vsip_scalar_f b){ return (vsip_scalar_f) atan2(a,b); } vsip_scalar_d vsip_hypot_d(vsip_scalar_d a, vsip_scalar_d b){ vsip_scalar_d retval = 0.0; vsip_scalar_d x=(vsip_scalar_d)fabs(a); vsip_scalar_d y=(vsip_scalar_d)fabs(b); if (a == 0.0) retval = y; else if (b == 0.0) retval = x; else if (y < x) retval = x * (vsip_scalar_d)sqrt(1.0 + (y/x) * (y/x)); else retval = y * (vsip_scalar_d)sqrt(1.0 + (x/y) * (x/y)); return retval; } vsip_scalar_f vsip_hypot_f(vsip_scalar_f a, vsip_scalar_f b){ vsip_scalar_f retval = 0.0; vsip_scalar_f x=(vsip_scalar_f)fabs(a); vsip_scalar_f y=(vsip_scalar_f)fabs(b); if (a == 0.0) retval = y; else if (b == 0.0) retval = x; else if (y < x) retval = x * (vsip_scalar_f)sqrt(1.0 + (y/x) * (y/x)); else retval = y * (vsip_scalar_f)sqrt(1.0 + (x/y) * (x/y)); return retval; } vsip_scalar_d vsip_exp_d(vsip_scalar_d a){ return (vsip_scalar_d)exp(a); } vsip_scalar_f vsip_exp_f(vsip_scalar_f a){ return (vsip_scalar_f)exp(a); } vsip_scalar_d vsip_floor_d(vsip_scalar_d a){ return (vsip_scalar_d)floor(a); } vsip_scalar_f vsip_floor_f(vsip_scalar_f a){ return (vsip_scalar_f)floor(a); } vsip_scalar_d vsip_log_d(vsip_scalar_d a){ return (vsip_scalar_d)log(a); } vsip_scalar_f vsip_log_f(vsip_scalar_f a){ return (vsip_scalar_f)log(a); } vsip_scalar_d vsip_log10_d(vsip_scalar_d a){ return (vsip_scalar_d)log10(a); } vsip_scalar_f vsip_log10_f(vsip_scalar_f a){ return (vsip_scalar_f)log10(a); } vsip_scalar_d vsip_mag_d(vsip_scalar_d a){ return (vsip_scalar_d)fabs(a); } vsip_scalar_f vsip_mag_f(vsip_scalar_f a){ return (vsip_scalar_f)fabs(a); } vsip_scalar_d vsip_pow_d(vsip_scalar_d x, vsip_scalar_d y){ return (vsip_scalar_d)pow(x,y); } vsip_scalar_f vsip_pow_f(vsip_scalar_f x, vsip_scalar_f y){ return (vsip_scalar_f)pow(x,y); } vsip_scalar_d vsip_sqrt_d(vsip_scalar_d a){ return (vsip_scalar_d)sqrt(a); } vsip_scalar_f vsip_sqrt_f(vsip_scalar_f a){ return (vsip_scalar_f)sqrt(a); } vsip_scalar_d vsip_tan_d(vsip_scalar_d a){ return (vsip_scalar_d)tan(a); } vsip_scalar_f vsip_tan_f(vsip_scalar_f a){ return (vsip_scalar_f)tan(a); } vsip_scalar_d vsip_tanh_d(vsip_scalar_d a){ return (vsip_scalar_d)tanh(a); } vsip_scalar_f vsip_tanh_f(vsip_scalar_f a){ return (vsip_scalar_f)tanh(a); } vsip_scalar_d vsip_exp10_d(vsip_scalar_d x){ return (vsip_scalar_d)pow(10.0,x); } vsip_scalar_f vsip_exp10_f(vsip_scalar_f x){ return (vsip_scalar_f)pow(10.0,x); } vsip_scalar_d vsip_min_d(vsip_scalar_d x,vsip_scalar_d y){ return (vsip_scalar_d) (x<y) ? x:y;} vsip_scalar_f vsip_min_f(vsip_scalar_f x,vsip_scalar_f y){ return (vsip_scalar_f) (x<y) ? x:y;} vsip_scalar_d vsip_max_d(vsip_scalar_d x,vsip_scalar_d y){ return (vsip_scalar_d) (x<y) ? y:x;} vsip_scalar_f vsip_max_f(vsip_scalar_f x,vsip_scalar_f y){ return (vsip_scalar_f) (x<y) ? y:x;} <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: marg_d.h,v 2.0 2003/02/22 15:23:24 judd Exp $ */ #include"VU_cmprintm_d.include" #include"VU_mprintm_d.include" static void marg_d(void){ printf("\n*****\nTEST marg_d\n"); { vsip_cmview_d *a = vsip_cmcreate_d(22,22,VSIP_COL,VSIP_MEM_NONE); vsip_cvview_d *a_v = vsip_cvbind_d(vsip_cmgetblock_d(a),0,1,22*22); vsip_cmview_d *b = vsip_cmsubview_d(a,0,0,3,3); vsip_mview_d *chk = vsip_mcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_vview_d *a_r, *a_i; vsip_mview_d *arg = vsip_mcreate_d(3,3,VSIP_COL,VSIP_MEM_NONE); vsip_scalar_d data[] = {1.5708, 0.5880, -.1651, 1.3258, .2450, -.2783, .9828, 0.0, -.3588}; vsip_block_d *block = vsip_blockbind_d(data,9,VSIP_MEM_NONE); vsip_mview_d *ans = vsip_mbind_d(block,0,3,3,1,3); vsip_blockadmit_d(block,VSIP_TRUE); vsip_cmputrowstride_d(b,6); vsip_cmputcolstride_d(b,2); a_r = vsip_vrealview_d(a_v); a_i = vsip_vimagview_d(a_v); vsip_vramp_d(0,.1,a_r); vsip_vramp_d(1,-.1,a_i); printf("call vsip_marg_d(b,arg)\n"); printf("input matrix b\n"); VU_cmprintm_d("8.6",b); vsip_marg_d(b,arg); printf("output arg\n"); VU_mprintm_d("8.6",arg); printf("answer to 4 digits\n"); VU_mprintm_d("8.4",ans); vsip_msub_d(arg,ans,chk); vsip_mmag_d(chk,chk); if(vsip_msumval_d(chk) > .0009) printf("error\n"); else printf("correct\n"); vsip_cmdestroy_d(b); vsip_vdestroy_d(a_i); vsip_vdestroy_d(a_r); vsip_cvdestroy_d(a_v); vsip_cmalldestroy_d(a); vsip_malldestroy_d(arg); vsip_malldestroy_d(ans); vsip_malldestroy_d(chk); } return; } <file_sep>/* // vsipUnsafePointer.c // vsip // // Created by <NAME> on 12/26/16. // Copyright © 2016 JVSIP. All rights reserved. */ #include"vsip.h" #include"vsip_blockattributes_d.h" #include"vsip_blockattributes_f.h" #include"vsip_cblockattributes_d.h" #include"vsip_cblockattributes_f.h" double* vsipUnsafeBlockPtr_d(vsip_block_d *blk, vsip_stride *stride){ *stride = blk->rstride; return blk->array; } float* vsipUnsafeBlockPtr_f(vsip_block_f *blk, vsip_stride *stride){ *stride = blk->rstride; return blk->array; } double* vsipUnsafeBlockPtr_cdR(vsip_cblock_d *blk, vsip_stride *stride){ *stride = blk->cstride; return blk->R->array; } float* vsipUnsafeBlockPtr_cfR(vsip_cblock_f *blk, vsip_stride *stride){ *stride = blk->cstride; return blk->R->array; } double* vsipUnsafeBlockPtr_cdI(vsip_cblock_d *blk, vsip_stride *stride){ *stride = blk->cstride; return blk->I->array; } float* vsipUnsafeBlockPtr_cfI(vsip_cblock_f *blk, vsip_stride *stride){ *stride = blk->cstride; return blk->I->array; } <file_sep>/* Created by RJudd July 4, 2002 */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_crfftmop_f_loop.h,v 2.0 2003/02/22 15:18:31 judd Exp $ */ #ifndef VI_CRFFTMOP_F_LOOP_H #define VI_CRFFTMOP_F_LOOP_H 1 /* Use a loop of vsip_crfftop_f.h to calculate fftm */ /* input matrix x, output matrix y, fftm object fftm */ #include"VI_mrowview_f.h" #include"VI_mcolview_f.h" #include"VI_cmrowview_f.h" #include"VI_cmcolview_f.h" void vsip_crfftmop_f( const vsip_fftm_f *Offt, const vsip_cmview_f *Z, const vsip_mview_f *X) { vsip_fftm_f Nfft = *Offt; vsip_fftm_f *fftm = &Nfft; vsip_fft_f *fft = (vsip_fft_f*)fftm->ext_fftm_obj; vsip_index k = 0; vsip_cvview_f vv; vsip_vview_f zz; if(fftm->major == VSIP_ROW){ while(k < X->col_length){ vsip_crfftop_f(fft, VI_cmrowview_f(Z,k,&vv), VI_mrowview_f(X,k,&zz)); k++; } } else { /* must be column */ while(k < X->row_length){ vsip_crfftop_f(fft, VI_cmcolview_f(Z,k,&vv), VI_mcolview_f(X,k,&zz)); k++; } } } #endif /* VI_CRFFTMOP_F_LOOP_H */ <file_sep>/* Created RJudd */ /* Retired */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmprod4_f.h,v 2.1 2006/04/09 20:55:28 judd Exp $ */ #include"VU_cmprintm_f.include" static void cmprod4_f(void){ printf("********\nTEST cmprod4_f\n"); { vsip_scalar_f datal_r[] = {1.0, 2.0, 3.0, 4.0, 5.0, 5.0, 0.1, 0.2, 0.3, 0.4, 4.0, 3.0, 2.0, 0.0, -1.0, 1.0}; vsip_scalar_f datal_i[] = {9.0, 3.0, 2.0, 4.3, 3.2, 5.0, 0.1, 1.2, 0.3, 1.4, 0.3, 2.0, -2.1, 0.1, 1.0, 2.0}; vsip_scalar_f datar_r[] = {0.1, 0.2, 0.3, 0.4, 1.0, 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 2.4, -1.1, -2.2, -2.3, -1.4, 3.1, 0.2, 1.1, 1.4, -2.1, -1.0, 1.5, 2.4, 3.1, 2.2, 1.3, 0.4, -1.1, -1.3, 4.3, -1.4}; vsip_scalar_f datar_i[] = { 1.1, 5.2, 3.3, 1.4, 2.1, 1.0, 1.2, 1.2, 4.1, 3.0, 2.3, 2.3, 1.1, -6.2, -1.3, 9.3, 2.1, 2.0, 2.1, 1.3, 1.4, -0.2, -2.3, 0.5, 1.0, 2.2, -2.3, 3.4, 4.6, 5.0, 2.1, 7.3}; /* we use vsip_cmprod_f to fill up the answer data space */ vsip_scalar_f ans_data_r[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; vsip_scalar_f ans_data_i[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; vsip_cblock_f *blockl = vsip_cblockbind_f(datal_r,datal_i,16,VSIP_MEM_NONE); vsip_cblock_f *blockr = vsip_cblockbind_f(datar_r,datar_i,32,VSIP_MEM_NONE); vsip_cblock_f *block_ans = vsip_cblockbind_f(ans_data_r,ans_data_i,32,VSIP_MEM_NONE); vsip_cblock_f *block = vsip_cblockcreate_f(250,VSIP_MEM_NONE); vsip_cmview_f *ml = vsip_cmbind_f(blockl,0,4,4,1,4); vsip_cmview_f *mr = vsip_cmbind_f(blockr,0,8,4,1,8); vsip_cmview_f *ans = vsip_cmbind_f(block_ans,0,8,4,1,8); vsip_cmview_f *a = vsip_cmbind_f(block,70,-1,4,-6,4); vsip_cmview_f *b = vsip_cmbind_f(block,71, 1,4,5,8); vsip_cmview_f *c = vsip_cmbind_f(block,220,-9,4,-1,8); vsip_cmview_f *chk = vsip_cmcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *chk_r = vsip_mrealview_f(chk); vsip_cblockadmit_f(blockl,VSIP_TRUE); vsip_cblockadmit_f(blockr,VSIP_TRUE); vsip_cblockadmit_f(block_ans,VSIP_TRUE); vsip_cmcopy_f_f(ml,a); vsip_cmcopy_f_f(mr,b); vsip_cmprod_f(a,b,ans); vsip_cmprod4_f(a,b,c); printf("vsip_cmprod4_f(a,b,c)\n"); printf("a\n"); VU_cmprintm_f("6.4",a); printf("b\n"); VU_cmprintm_f("6.4",b); printf("c\n"); VU_cmprintm_f("6.4",c); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); { /* ccc */ vsip_cmview_f *a1 = vsip_cmcreate_f(4,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod4_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* ccr */ vsip_cmview_f *a1 = vsip_cmcreate_f(4,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod4_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* crc */ vsip_cmview_f *a1 = vsip_cmcreate_f(4,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod4_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* crr */ vsip_cmview_f *a1 = vsip_cmcreate_f(4,4,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod4_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* rcc */ vsip_cmview_f *a1 = vsip_cmcreate_f(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod4_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* rcr */ vsip_cmview_f *a1 = vsip_cmcreate_f(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod4_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* rrc */ vsip_cmview_f *a1 = vsip_cmcreate_f(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(4,8,VSIP_COL,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod4_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } { /* rrr */ vsip_cmview_f *a1 = vsip_cmcreate_f(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *b1 = vsip_cmcreate_f(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmview_f *c1 = vsip_cmcreate_f(4,8,VSIP_ROW,VSIP_MEM_NONE); vsip_cmcopy_f_f(a,a1); vsip_cmcopy_f_f(b,b1); vsip_cmprod4_f(a1,b1,c1); printf("c1\n"); VU_cmprintm_f("6.4",c1); printf("right answer\n"); VU_cmprintm_f("6.4",ans); vsip_cmsub_f(c1,ans,chk); vsip_cmmag_f(chk,chk_r); vsip_mclip_f(chk_r,.0001,.0001,0,1,chk_r); if(vsip_msumval_f(chk_r) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_f(a1); vsip_cmalldestroy_f(b1); vsip_cmalldestroy_f(c1); } vsip_cmalldestroy_f(ml); vsip_cmalldestroy_f(mr); vsip_cmdestroy_f(a); vsip_cmdestroy_f(b); vsip_cmalldestroy_f(c); vsip_cmalldestroy_f(ans); vsip_mdestroy_f(chk_r); vsip_cmalldestroy_f(chk); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cvrsdiv_f.h,v 2.0 2003/02/22 15:23:23 judd Exp $ */ #include"VU_cvprintm_f.include" static void cvrsdiv_f(void){ printf("\n********\nTEST cvrsdiv_f\n"); { vsip_scalar_f beta = 2.5; vsip_cvview_f *a = vsip_cvcreate_f(7,VSIP_MEM_NONE); vsip_cvview_f *c = vsip_cvcreate_f(7,VSIP_MEM_NONE); vsip_vview_f *c_i = vsip_vimagview_f(c); vsip_cvview_f *chk = vsip_cvcreate_f(7,VSIP_MEM_NONE); vsip_vview_f *chk_i = vsip_vimagview_f(chk); vsip_scalar_f data_r[] ={.1, .2, .3, .4, .5, .6, .7}; vsip_scalar_f data_i[] ={7,6,5,4,3,2,1}; vsip_scalar_f data_ans[] ={0.0400, 2.8000, 0.0800, 2.4000, 0.1200, 2.0000, 0.1600, 1.600, 0.2000, 1.2000, 0.2400, 0.8000, 0.2800, 0.4000}; vsip_cblock_f *cblock = vsip_cblockbind_f(data_r,data_i,7,VSIP_MEM_NONE); vsip_cblock_f *cblock_ans = vsip_cblockbind_f(data_ans, (vsip_scalar_f*)NULL,7,VSIP_MEM_NONE); vsip_cvview_f *u_a = vsip_cvbind_f(cblock,0,1,7); vsip_cvview_f *u_ans = vsip_cvbind_f(cblock_ans,0,1,7); vsip_cblockadmit_f(cblock,VSIP_TRUE); vsip_cblockadmit_f(cblock_ans,VSIP_TRUE); vsip_cvcopy_f_f(u_a,a); printf("call vsip_cvrsdiv_f(a,beta,c)\n"); printf("beta = %f\n",beta); printf("a =\n");VU_cvprintm_f("8.6",a); printf("test normal out of place\n"); vsip_cvrsdiv_f(a,beta,c); printf("c =\n");VU_cvprintm_f("8.6",c); printf("right answer =\n");VU_cvprintm_f("8.4",u_ans); vsip_cvsub_f(u_ans,c,chk); vsip_cvmag_f(chk,chk_i); vsip_vclip_f(chk_i,.0002,.0002,0,1,chk_i); if(vsip_vsumval_f(chk_i) > .5) printf("error\n"); else printf("correct\n"); printf("test a,c inplace\n"); vsip_cvrsdiv_f(a,beta,a); vsip_cvsub_f(u_ans,a,chk); vsip_cvmag_f(chk,chk_i); vsip_vclip_f(chk_i,.0002,.0002,0,1,chk_i); if(vsip_vsumval_f(chk_i) > .5) printf("error\n"); else printf("correct\n"); vsip_cvalldestroy_f(a); vsip_vdestroy_f(c_i); vsip_cvalldestroy_f(c); vsip_vdestroy_f(chk_i); vsip_cvalldestroy_f(chk); vsip_cvalldestroy_f(u_a); vsip_cvalldestroy_f(u_ans); } return; } <file_sep>//: K-Omega Beaformer Example //: This example is a straightforward conversion (more or less) of a C example using C-VSIPL //: The C code is stored in the Resources directory along with the parameters. import Cocoa import vsip var filePath = Bundle.main.path(forResource: "param_file", ofType: nil) let param = Param(parameterFile: filePath) param.log() let ts = TimeSeries(param: param) let kw = KW(param: param) let Navg = param.Navg! let dtaIn = ts.instance() let gramOut = kw.instance() kw.zero(); for _ in 0..<Navg { ts.zero(); ts.nb_sim(); ts.noise_sim(); kw.komega(m_data: dtaIn); } for i in 0..<vsip_mgetrowlength_d(gramOut){/* move zero to middle */ let v = vsip_mcolview_d(gramOut, i); vsip_vfreqswap_d(v) vsip_vdestroy_d(v) } /* massage the data for plot*/ var max = vsip_mmaxval_d(gramOut, nil) let avg = vsip_mmeanval_d(gramOut); vsip_mclip_d(gramOut,0.0, max, avg/100000.0, max, gramOut); vsip_mlog10_d(gramOut,gramOut); let min = -vsip_mminval_d(gramOut, nil) vsip_smadd_d(min, gramOut, gramOut); max = vsip_mmaxval_d(gramOut, nil); vsip_smmul_d(1.0/max, gramOut, gramOut); /* output data and plot with octave */ let fptr = fopen("/Users/judd/gramOut","w"); let size = Int(vsip_mgetrowlength_d(gramOut) * vsip_mgetcollength_d(gramOut)) var out: [Double] = Array<Double>(repeating: 0.0, count: size) vsip_mcopyto_user_d(gramOut, VSIP_COL, &out) let imageContext = makeRGBImage(width: 128, height: 512, buffer: out) let image = imageContext.makeImage() let nsimage = NSImage(cgImage: image!, size: NSSize(width: 128, height: 512)) fwrite(out,size,MemoryLayout<vsip_scalar_d>.size,fptr) fclose(fptr) let w = Int(vsip_mgetrowlength_d(gramOut)) let h = Int(vsip_mgetcollength_d(gramOut)) let s = NSSize(width: w, height: h) CGBitmapInfo.alphaInfoMask CGBitmapInfo.floatComponents CGBitmapInfo.floatInfoMask <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_length_d.h,v 2.1 2007/04/18 17:05:56 judd Exp $ */ static void get_put_length_d(void){ printf("********\nTEST get_put_length_d\n"); { vsip_offset ivo = 3, icvo=10; vsip_stride ivs = 0, icvs=0; vsip_length ivl = 3, icvl=4; vsip_length jvl = 5, jcvl=7; vsip_stride irs = 0, ics = 0; vsip_length irl = 2, icl = 3; vsip_length jrl = 5, jcl = 2; vsip_stride ixs = 0, iys = 0, izs = 0; vsip_length ixl = 2, iyl = 3, izl = 4; vsip_length jxl = 3, jyl = 4, jzl = 2; vsip_block_d *b = vsip_blockcreate_d(80,VSIP_MEM_NONE); vsip_cblock_d *cb = vsip_cblockcreate_d(80,VSIP_MEM_NONE); vsip_vview_d *v = vsip_vbind_d(b,ivo,ivs,ivl); vsip_mview_d *m = vsip_mbind_d(b,ivo,ics,icl,irs,irl); vsip_tview_d *t = vsip_tbind_d(b,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_cvview_d *cv = vsip_cvbind_d(cb,icvo,icvs,icvl); vsip_cmview_d *cm = vsip_cmbind_d(cb,ivo,ics,icl,irs,irl); vsip_ctview_d *ct = vsip_ctbind_d(cb,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_length s; printf("test vgetlength_d\n"); fflush(stdout); { s = vsip_vgetlength_d(v); (s == ivl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputlength_d\n"); fflush(stdout); { vsip_vputlength_d(v,jvl); s = vsip_vgetlength_d(v); (s == jvl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test cvgetlength_d\n"); fflush(stdout); { s = vsip_cvgetlength_d(cv); (s == icvl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputlength_d\n"); fflush(stdout); { vsip_cvputlength_d(cv,jcvl); s = vsip_cvgetlength_d(cv); (s == jcvl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /*************************************************************************/ printf("test mgetrowlength_d\n"); fflush(stdout); { s = vsip_mgetrowlength_d(m); (s == irl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputrowlength_d\n"); fflush(stdout); { vsip_mputrowlength_d(m,jrl); s = vsip_mgetrowlength_d(m); (s == jrl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test mgetcollength_d\n"); fflush(stdout); { s = vsip_mgetcollength_d(m); (s == icl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputcollength_d\n"); fflush(stdout); { vsip_mputcollength_d(m,jcl); s = vsip_mgetcollength_d(m); (s == jcl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test cmgetrowlength_d\n"); fflush(stdout); { s = vsip_cmgetrowlength_d(cm); (s == irl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test cmputrowlength_d\n"); fflush(stdout); { vsip_cmputrowlength_d(cm,jrl); s = vsip_cmgetrowlength_d(cm); (s == jrl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test cmgetcollength_d\n"); fflush(stdout); { s = vsip_cmgetcollength_d(cm); (s == icl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test cmputcollength_d\n"); fflush(stdout); { vsip_cmputcollength_d(cm,jcl); s = vsip_cmgetcollength_d(cm); (s == jcl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /*************************************************************************/ printf("test tgetxlength_d\n"); fflush(stdout); { s = vsip_tgetxlength_d(t); (s == ixl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputxlength_d\n"); fflush(stdout); { vsip_tputxlength_d(t,jxl); s = vsip_tgetxlength_d(t); (s == jxl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test ctgetxlength_d\n"); fflush(stdout); { s = vsip_ctgetxlength_d(ct); (s == ixl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test ctputxlength_d\n"); fflush(stdout); { vsip_ctputxlength_d(ct,jxl); s = vsip_ctgetxlength_d(ct); (s == jxl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test tgetylength_d\n"); fflush(stdout); { s = vsip_tgetylength_d(t); (s == iyl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputylength_d\n"); fflush(stdout); { vsip_tputylength_d(t,jyl); s = vsip_tgetylength_d(t); (s == jyl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test ctgetylength_d\n"); fflush(stdout); { s = vsip_ctgetylength_d(ct); (s == iyl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test ctputylength_d\n"); fflush(stdout); { vsip_ctputylength_d(ct,jyl); s = vsip_ctgetylength_d(ct); (s == jyl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test tgetzlength_d\n"); fflush(stdout); { s = vsip_tgetzlength_d(t); (s == izl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputzlength_d\n"); fflush(stdout); { vsip_tputzlength_d(t,jzl); s = vsip_tgetzlength_d(t); (s == jzl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test ctgetzlength_d\n"); fflush(stdout); { s = vsip_ctgetzlength_d(ct); (s == izl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test ctputzlength_d\n"); fflush(stdout); { vsip_ctputzlength_d(ct,jzl); s = vsip_ctgetzlength_d(ct); (s == jzl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } vsip_vdestroy_d(v); vsip_mdestroy_d(m); vsip_talldestroy_d(t); vsip_cvdestroy_d(cv); vsip_cmdestroy_d(cm); vsip_ctalldestroy_d(ct); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_attrib_f.h,v 2.0 2003/02/22 15:23:33 judd Exp $ */ static void get_put_attrib_f(void){ printf("********\nTEST get_put_attrib_f\n"); { vsip_offset ivo = 3, icvo=10; vsip_stride ivs = 2, icvs=-1; vsip_length ivl = 3, icvl=4; vsip_offset jvo = 2, jcvo=0; vsip_stride jvs = 3, jcvs=1; vsip_length jvl = 5, jcvl=7; vsip_stride irs = 1, ics = 3; vsip_length irl = 2, icl = 3; vsip_stride jrs = 5, jcs = 2; vsip_length jrl = 5, jcl = 2; vsip_stride ixs = 2, iys = 4, izs = 14; vsip_length ixl = 2, iyl = 3, izl = 4; vsip_stride jxs = 4, jys = 14, jzs = 2; vsip_length jxl = 3, jyl = 4, jzl = 2; vsip_block_f *b = vsip_blockcreate_f(80,VSIP_MEM_NONE); vsip_cblock_f *cb = vsip_cblockcreate_f(80,VSIP_MEM_NONE); vsip_vview_f *v = vsip_vbind_f(b,ivo,ivs,ivl); vsip_mview_f *m = vsip_mbind_f(b,ivo,ics,icl,irs,irl); vsip_tview_f *t = vsip_tbind_f(b,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_cvview_f *cv = vsip_cvbind_f(cb,icvo,icvs,icvl); vsip_cmview_f *cm = vsip_cmbind_f(cb,ivo,ics,icl,irs,irl); vsip_ctview_f *ct = vsip_ctbind_f(cb,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_vattr_f attr; vsip_cvattr_f cattr; vsip_mattr_f mattr; vsip_cmattr_f cmattr; vsip_tattr_f tattr; vsip_ctattr_f ctattr; printf("test vgetattrib_f\n"); fflush(stdout); { vsip_vgetattrib_f(v,&attr); (attr.offset == ivo) ? printf("offset correct\n") : printf("offset error \n"); (attr.stride == ivs) ? printf("stride correct\n") : printf("stride error \n"); (attr.length == ivl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputattrib_f\n"); fflush(stdout); { attr.offset = jvo; attr.stride = jvs; attr.length = jvl; vsip_vputattrib_f(v,&attr); vsip_vgetattrib_f(v,&attr); (attr.offset == jvo) ? printf("offset correct\n") : printf("offset error \n"); (attr.stride == jvs) ? printf("stride correct\n") : printf("stride error \n"); (attr.length == jvl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test cvgetattrib_f\n"); fflush(stdout); { vsip_cvgetattrib_f(cv,&cattr); (cattr.offset == icvo) ? printf("offset correct\n") : printf("offset error \n"); (cattr.stride == icvs) ? printf("stride correct\n") : printf("stride error \n"); (cattr.length == icvl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test cvputattrib_f\n"); fflush(stdout); { cattr.offset = jcvo; cattr.stride = jcvs; cattr.length = jcvl; vsip_cvputattrib_f(cv,&cattr); vsip_cvgetattrib_f(cv,&cattr); (cattr.offset == jcvo) ? printf("offset correct\n") : printf("offset error \n"); (cattr.stride == jcvs) ? printf("stride correct\n") : printf("stride error \n"); (cattr.length == jcvl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /**************************************************************************/ printf("test mgetattrib_f\n"); fflush(stdout); { vsip_mgetattrib_f(m,&mattr); (mattr.offset == ivo) ? printf("offset correct\n") : printf("offset error \n"); (mattr.col_stride == ics) ? printf("col_stride correct\n") : printf("col_stride error \n"); (mattr.row_stride == irs) ? printf("row_stride correct\n") : printf("row_stride error \n"); (mattr.col_length == icl) ? printf("col_length correct\n") : printf("col_length error \n"); (mattr.row_length == irl) ? printf("row_length correct\n") : printf("row_length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputattrib_f\n"); fflush(stdout); { mattr.offset = jvo; mattr.col_stride = jcs; mattr.col_length = jcl; mattr.row_stride = jrs; mattr.row_length = jrl; vsip_mputattrib_f(m,&mattr); vsip_mgetattrib_f(m,&mattr); (mattr.offset == jvo) ? printf("offset correct\n") : printf("offset error \n"); (mattr.col_stride == jcs) ? printf("col_stride correct\n") : printf("col_stride error \n"); (mattr.col_length == jcl) ? printf("col_length correct\n") : printf("col_length error \n"); (mattr.row_stride == jrs) ? printf("row_stride correct\n") : printf("row_stride error \n"); (mattr.row_length == jrl) ? printf("row_length correct\n") : printf("row_length error \n"); fflush(stdout); } printf("test cmgetattrib_f\n"); fflush(stdout); { vsip_cmgetattrib_f(cm,&cmattr); (cmattr.offset == ivo) ? printf("offset correct\n") : printf("offset error \n"); (cmattr.col_stride == ics) ? printf("col_stride correct\n") : printf("col_stride error \n"); (cmattr.col_length == icl) ? printf("col_length correct\n") : printf("col_length error \n"); (cmattr.row_stride == irs) ? printf("row_stride correct\n") : printf("row_stride error \n"); (cmattr.row_length == irl) ? printf("row_length correct\n") : printf("row_length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test cmputattrib_f\n"); fflush(stdout); { cmattr.offset = jvo; cmattr.col_stride = jcs; cmattr.col_length = jcl; cmattr.row_stride = jrs; cmattr.row_length = jrl; vsip_cmputattrib_f(cm,&cmattr); vsip_cmgetattrib_f(cm,&cmattr); (cmattr.offset == jvo) ? printf("offset correct\n") : printf("offset error \n"); (cmattr.col_stride == jcs) ? printf("col_stride correct\n") : printf("col_stride error \n"); (cmattr.col_length == jcl) ? printf("col_length correct\n") : printf("col_length error \n"); (cmattr.row_stride == jrs) ? printf("row_stride correct\n") : printf("row_stride error \n"); (cmattr.row_length == jrl) ? printf("row_length correct\n") : printf("row_length error \n"); fflush(stdout); } /**************************************************************************/ printf("test tgetattrib_f\n"); fflush(stdout); { vsip_tgetattrib_f(t,&tattr); (tattr.offset == ivo) ? printf("offset correct\n") : printf("offset error \n"); (tattr.z_stride == izs) ? printf("z_stride correct\n") : printf("z_stride error \n"); (tattr.z_length == izl) ? printf("z_length correct\n") : printf("z_length error \n"); (tattr.y_stride == iys) ? printf("y_stride correct\n") : printf("y_stride error \n"); (tattr.y_length == iyl) ? printf("y_length correct\n") : printf("y_length error \n"); (tattr.x_stride == ixs) ? printf("x_stride correct\n") : printf("x_stride error \n"); (tattr.x_length == ixl) ? printf("x_length correct\n") : printf("x_length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputattrib_f\n"); fflush(stdout); { tattr.offset = jvo; tattr.z_stride = jzs; tattr.z_length = jzl; tattr.y_stride = jys; tattr.y_length = jyl; tattr.x_stride = jxs; tattr.x_length = jxl; vsip_tputattrib_f(t,&tattr); vsip_tgetattrib_f(t,&tattr); (tattr.offset == jvo) ? printf("offset correct\n") : printf("offset error \n"); (tattr.z_stride == jzs) ? printf("z_stride correct\n") : printf("z_stride error \n"); (tattr.z_length == jzl) ? printf("z_length correct\n") : printf("z_length error \n"); (tattr.y_stride == jys) ? printf("y_stride correct\n") : printf("y_stride error \n"); (tattr.y_length == jyl) ? printf("y_length correct\n") : printf("y_length error \n"); (tattr.x_stride == jxs) ? printf("x_stride correct\n") : printf("x_stride error \n"); (tattr.x_length == jxl) ? printf("x_length correct\n") : printf("x_length error \n"); fflush(stdout); } printf("test ctgetattrib_f\n"); fflush(stdout); { vsip_ctgetattrib_f(ct,&ctattr); (ctattr.offset == ivo) ? printf("offset correct\n") : printf("offset error \n"); (ctattr.z_stride == izs) ? printf("z_stride correct\n") : printf("z_stride error \n"); (ctattr.z_length == izl) ? printf("z_length correct\n") : printf("z_length error \n"); (ctattr.y_stride == iys) ? printf("y_stride correct\n") : printf("y_stride error \n"); (ctattr.y_length == iyl) ? printf("y_length correct\n") : printf("y_length error \n"); (ctattr.x_stride == ixs) ? printf("x_stride correct\n") : printf("x_stride error \n"); (ctattr.x_length == ixl) ? printf("x_length correct\n") : printf("x_length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test ctputattrib_f\n"); fflush(stdout); { ctattr.offset = jvo; ctattr.z_stride = jzs; ctattr.z_length = jzl; ctattr.y_stride = jys; ctattr.y_length = jyl; ctattr.x_stride = jxs; ctattr.x_length = jxl; vsip_ctputattrib_f(ct,&ctattr); vsip_ctgetattrib_f(ct,&ctattr); (ctattr.offset == jvo) ? printf("offset correct\n") : printf("offset error \n"); (ctattr.z_stride == jzs) ? printf("z_stride correct\n") : printf("z_stride error \n"); (ctattr.z_length == jzl) ? printf("z_length correct\n") : printf("z_length error \n"); (ctattr.y_stride == jys) ? printf("y_stride correct\n") : printf("y_stride error \n"); (ctattr.y_length == jyl) ? printf("y_length correct\n") : printf("y_length error \n"); (ctattr.x_stride == jxs) ? printf("x_stride correct\n") : printf("x_stride error \n"); (ctattr.x_length == jxl) ? printf("x_length correct\n") : printf("x_length error \n"); fflush(stdout); } vsip_vdestroy_f(v); vsip_mdestroy_f(m); vsip_talldestroy_f(t); vsip_cvdestroy_f(cv); vsip_cmdestroy_f(cm); vsip_ctalldestroy_f(ct); } return; } <file_sep>#! python # Estimate two-norm (sigma0) and singular values (sigma0, sigma1) # of a two by two matrix by searching through a dense space of vectors. # Check by reproducing estimate for A matrix using Aest=U Sigma V^t # Motivating text Numerical Linear Algebra, Trefethen and Bau import pyJvsip as pv from numpy import pi,arccos from matplotlib.pyplot import * N=1000 #number of points to search through for estimates # create a vector 'arg' of evenly spaced angles between [zero, 2 pi) arg=pv.create('vview_d',N).ramp(0.0,2.0 * pi/float(N)) # Create a matrix 'X' of unit vectors representing Unit Ball in R2 X=pv.create('mview_d',2,N,'ROW').fill(0.0) x0=X.rowview(0);x1=X.rowview(1) pv.sin(arg,x0);pv.cos(arg,x1) # create matrix 'A' to examine A=pv.create('mview_d',2,2).fill(0.0) A[0,0]=1.0;A[0,1]=2.0; A[1,1]=2.0;A[1,0]=0.0 # create matrix Y=AX Y=A.prod(X) y0=Y.rowview(0);y1=Y.rowview(1) # create vector 'n' of 2-norms for Y col vectors (sqrt(y0_i^2+y1_i^2)) n=(y0.copy.sq+y1.copy.sq).sqrt # Find index of (first) maximum value and (first) minimum value i=n.maxvalindx; j=n.minvalindx sigma0=n[i];sigma1=n[j] # create estimates for V, U, Sigma (S) V=A.empty.fill(0) U=V.copy S=V.copy S[0,0]=sigma0;S[1,1]=sigma1 U[0:2,0]=Y[0:2,i];U[0:2,1]=Y[0:2,j] ut=U[0:2,0];pv.div(ut,sigma0,ut); ut=U[0:2,1];pv.div(ut,sigma1,ut); # U[0:2,0] /=sigma0; U[0:2,1]/=sigma1 #normalize u1,u2 V[0:2,0]=X[0:2,i];V[0:2,1]=X[0:2,j] #v0, v1 already normalized #estimate A from results of U,V,S Aest=U.prod(S).prod(V.transview) # #PLOT Results stk='\\stackrel' #for creating small matrices spc='\\/' #for creating some space lft='\\left[' #left bracket rgt='\\right]' #right bracket #Plot results for two norm tne = "Maximum magnitude 'x':\n "+'(%.4f, %.4f)'%(y1[i], y0[i]) tne +='\nTwo norm estimate: \n ' + "%.4f"%sigma0 figure(1,figsize=(8.5,6)) subplot(1,2,1).set_aspect('equal') title(r'Unit Ball in $\Re^2$',fontsize=14) ylabel(r'$x_0$',fontsize=14) xlabel(r'$x_1$',fontsize=14) plot(x1.list,x0.list) a00='{'+'%.4f'%Aest[0,0]+'}';a01='{'+'%.4f'%Aest[0,1]+'}' a10='{'+'%.4f'%Aest[1,0]+'}';a11='{'+'%.4f'%Aest[1,1]+'}' eqn="r\'$"+lft+stk+"{y_0}{y_1}"+rgt+"="+lft+stk+a00+a10+\ spc+stk+a01+a11+rgt eqn+= lft+stk+"{x_0}{x_1}"+rgt+"$\'" text(-1.25,1.65,eval(eqn),fontsize=20) text(x1[i],x0[i],'x',horizontalalignment='center',\ verticalalignment='center') plot([0,x1[0]],[0,x0[0]],'k') plot([0,x1[int(N/4)]],[0,x0[int(N/4)]],'g') plot([0,x1[int(N/2)]],[0,x0[int(N/2)]],'r') plot([0,x1[3*int(N/4)]],[0,x0[3*int(N/4)]],'m') subplot(1,2,2).set_aspect('equal') title(r'Transformed Unit Ball in $\Re^2$',fontsize=14) ylabel(r'$y_0$',fontsize=14) xlabel(r'$y_1$',fontsize=14) plot(y1.list,y0.list) text(y1[i],y0[i],'x',horizontalalignment='center',\ verticalalignment='center') text(-1.9,2.0,tne,fontname='sarif',fontsize=10) plot([0,y1[0]],[0,y0[0]],'k') plot([0,y1[int(N/4)]],[0,y0[int(N/4)]],'g') plot([0,y1[int(N/2)]],[0,y0[int(N/2)]],'r') plot([0,y1[3*int(N/4)]],[0,y0[3*int(N/4)]],'m') #Plot results for singular values a00='{'+'%.4f'%Aest[0,0]+'}';a01='{'+'%.4f'%Aest[0,1]+'}' a10='{'+'%.4f'%Aest[1,0]+'}';a11='{'+'%.4f'%Aest[1,1]+'}' s00='{'+'%.4f'%S[0,0]+'}';s01='{'+'%.4f'%S[0,1]+'}' s10='{'+'%.4f'%S[1,0]+'}';s11='{'+'%.4f'%S[1,1]+'}' u00='{'+'%.4f'%U[0,0]+'}';u01='{'+'%.4f'%U[0,1]+'}' u10='{'+'%.4f'%U[1,0]+'}';u11='{'+'%.4f'%U[1,1]+'}' v00='{'+'%.4f'%V[0,0]+'}';v01='{'+'%.4f'%V[0,1]+'}' v10='{'+'%.4f'%V[1,0]+'}';v11='{'+'%.4f'%V[1,1]+'}' estEqn="r\'$\\left[" +stk+a00+a10+spc+stk+a01+a11+"\\right] = " estEqn+="\\left[" +stk+u00+u10+spc+stk+u01+u11+"\\right] " estEqn+="\\left[" +stk+s00+s10+spc+stk+s01+s11+"\\right] " estEqn+="\\left[" +stk+v00+v01+spc+stk+v10+v11+"\\right]$\'" figure(2,figsize=(9,6.5)) subplot(1,2,1).set_aspect('equal') title(r'Unit Ball in $\Re^2$',fontsize=14) text(-1.6,1.50,eval(estEqn),fontsize=14) #Use a tilde to indicate these are estimates eqnUSV=r'$\mathrm{\tilde{A} = \tilde{U}\/\tilde{\Sigma}\/\tilde{V}^{\/T}}$' text(-1.4,1.75,eqnUSV,fontsize=16) #text(.5,V[0,0],r'$ \hat v_0$',rotation=25,fontsize=16) theta=180.0/pi * arg[i] text(V[1,0]*0.5,V[0,0]*0.5,r'$\hat v_0$',rotation=theta, fontsize=16,\ horizontalalignment='center',verticalalignment='bottom') #text(-.1,.5,r'$ \hat v_1$',rotation = -65,fontsize=16) theta=180.0/pi * arg[j] text(V[1,1]*0.5,V[0,1]*0.5,r'$\hat v_1$',rotation=theta, fontsize=16, \ horizontalalignment='center',verticalalignment='bottom') ylabel(r'$x_0$',fontsize=14) xlabel(r'$x_1$',fontsize=14) plot(x1.list,x0.list) text(x1[i],x0[i],'x',horizontalalignment='center',\ verticalalignment='center') text(x1[j],x0[j],'x',horizontalalignment='center',\ verticalalignment='center') plot([0,x1[i]],[0,x0[i]],'k') plot([0,x1[j]],[0,x0[j]],'g') subplot(1,2,2).set_aspect('equal') title(r'Transformed Unit Ball in $\Re^2$',fontsize=14) ylabel(r'$y_0$',fontsize=14) xlabel(r'$y_1$',fontsize=14) plot(y1.list,y0.list) text(y1[i],y0[i],'x',horizontalalignment='center',\ verticalalignment='center') text(y1[j],y0[j],'x',horizontalalignment='center',\ verticalalignment='center') cos0=y1[i]/sigma0;sin0=y0[i]/sigma0;cos1=y1[j]/sigma1;sin1=y0[j]/sigma1 theta=arccos(cos0)*180.0/pi text(y1[i]/2,y0[i]/2,r'$ \sigma_0 \hat u_0$',rotation=theta,fontsize=16,\ horizontalalignment='center',verticalalignment='top') theta=arccos(cos1)*180.0/pi text(y1[j]/2,y0[j]/2,r'$ \sigma_0 \hat u_1$',rotation=theta,fontsize=16,\ horizontalalignment='center',verticalalignment='bottom') plot([0,y1[i]],[0,y0[i]],'k') plot([0,y1[j]],[0,y0[j]],'g') show() <file_sep>MAKE=make CFLAGS= DFLAGS= -O3 LIBS= -lvsip -lm CC=cc INCLUDE=-I../../../include LIBDIR=-L../../../lib HEADERS = param.h kw.h ts.h SOURCE = param.c kw.c ts.c beamformer_ex.c OBJECTS = param.o kw.o ts.o all:beamformer param.o:param.c param.h $(CC) -c $(DFLAGS) param.c $(INCLUDE) kw.o:kw.c kw.h param.h $(CC) -c $(DFLAGS) kw.c $(INCLUDE) ts.o:ts.c ts.h param.h $(CC) -c $(DFLAGS) ts.c $(INCLUDE) beamformer: beamformer_ex.c param.h kw.h ts.h $(OBJECTS) $(SOURCE) $(HEADERS) cc -o beamformer_ex $(DFLAGS) $(CFLAGS) beamformer_ex.c\ $(OBJECTS) $(INCLUDE) $(LIBDIR) $(LIBS) clean: rm -f *.o beamformer_ex gramOut <file_sep> // SwiftVsip // // Created by <NAME> on 9/3/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import vsip // MARK: - Elementary Math Functions public func acos(_ input: Vector, resultsIn: Vector) { assert(sizeEqual(input, against: resultsIn), "vectors must be the same size") switch (input.type, resultsIn.type) { case (.f, .f): vsip_vacos_f(input.vsip, resultsIn.vsip) case (.d, .d): vsip_vacos_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for this type vector") } } public func acos(_ input: Matrix, resultsIn: Matrix) { assert(sizeEqual(input, against: resultsIn), "vectors must be the same size") switch (input.type, resultsIn.type) { case (.f, .f): vsip_macos_f(input.vsip, resultsIn.vsip) case (.d, .d): vsip_macos_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for this type vector") } } public func asin(_ input: Vector, resultsIn: Vector) { assert(sizeEqual(input, against: resultsIn), "vectors must be the same size") switch (input.type, resultsIn.type) { case (.f, .f): vsip_vasin_f(input.vsip, resultsIn.vsip) case (.d, .d): vsip_vasin_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for this type vector") } } public func asin(_ input: Matrix, resultsIn: Matrix) { assert(sizeEqual(input, against: resultsIn), "vectors must be the same size") switch (input.type, resultsIn.type) { case (.f, .f): vsip_masin_f(input.vsip, resultsIn.vsip) case (.d, .d): vsip_masin_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for this type vector") } } public func atan(_ input: Vector, resultsIn: Vector) { assert(sizeEqual(input, against: resultsIn), "View sizes must be the same") switch input.type { case .f: vsip_vatan_f(input.vsip, resultsIn.vsip) case .d: vsip_vatan_d(input.vsip, resultsIn.vsip) default: precondition(true, "function not supported for this type vector") break } } public func atan(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_matan_f(input.vsip, resultsIn.vsip) case .d: vsip_matan_d(input.vsip, resultsIn.vsip) default: precondition(true, "function not supported for this type matrix") break } } public func atan2(numerator: Vector, denominator: Vector, resultsIn: Vector) { let tn = numerator.type let td = denominator.type let to = resultsIn.type assert(tn == td && tn == to, "View types must agree") assert(sizeEqual(numerator, against: denominator) && sizeEqual(numerator, against: resultsIn), "View sizes musta be equal") switch tn{ case .f: vsip_vatan2_f(numerator.vsip,denominator.vsip,resultsIn.vsip) case .d: vsip_vatan2_d(numerator.vsip,denominator.vsip,resultsIn.vsip) default: preconditionFailure("function not supported for this type matrix") break } } public func atan2(numerator: Matrix, denominator: Matrix, resultsIn: Matrix) { let tn = numerator.type let td = denominator.type let to = resultsIn.type assert(tn == td && tn == to, "input types must be the same") assert(sizeEqual(numerator, against: denominator) && sizeEqual(numerator, against: resultsIn), "View sizes musta be equal") switch tn { case .f: vsip_matan2_f(numerator.vsip,denominator.vsip,resultsIn.vsip) case .d: vsip_matan2_d(numerator.vsip,denominator.vsip,resultsIn.vsip) default: preconditionFailure("function not supported for this type matrix") break } } public func cos(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vcos_f(input.vsip, resultsIn.vsip) case .d: vsip_vcos_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func cos(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_mcos_f(input.vsip, resultsIn.vsip) case .d: vsip_mcos_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func cosh(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vcosh_f(input.vsip, resultsIn.vsip) case .d: vsip_vcosh_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func cosh(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_mcosh_f(input.vsip, resultsIn.vsip) case .d: vsip_mcosh_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func sin(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vsin_f(input.vsip, resultsIn.vsip) case .d: vsip_vsin_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func sin(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_msin_f(input.vsip, resultsIn.vsip) case .d: vsip_msin_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func sinh(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vsinh_f(input.vsip, resultsIn.vsip) case .d: vsip_vsinh_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func sinh(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_msinh_f(input.vsip, resultsIn.vsip) case .d: vsip_msinh_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func exp(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vexp_f(input.vsip, resultsIn.vsip) case .d: vsip_vexp_d(input.vsip, resultsIn.vsip) case .cf: vsip_cvexp_f(input.vsip, resultsIn.vsip) case .cd: vsip_cvexp_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func exp(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_mexp_f(input.vsip, resultsIn.vsip) case .d: vsip_mexp_d(input.vsip, resultsIn.vsip) case .cf: vsip_cmexp_f(input.vsip, resultsIn.vsip) case .cd: vsip_cmexp_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func exp10(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vexp10_f(input.vsip, resultsIn.vsip) case .d: vsip_vexp10_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func exp10(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_mexp10_f(input.vsip, resultsIn.vsip) case .d: vsip_mexp10_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func log(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vlog_f(input.vsip, resultsIn.vsip) case .d: vsip_vlog_d(input.vsip, resultsIn.vsip) case .cf: vsip_cvlog_f(input.vsip, resultsIn.vsip) case .cd: vsip_cvlog_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func log(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_mlog_f(input.vsip, resultsIn.vsip) case .d: vsip_mlog_d(input.vsip, resultsIn.vsip) case .cf: vsip_cmlog_f(input.vsip, resultsIn.vsip) case .cd: vsip_cmlog_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func log10(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vlog10_f(input.vsip, resultsIn.vsip) case .d: vsip_vlog10_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func log10(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_mlog10_f(input.vsip, resultsIn.vsip) case .d: vsip_mlog10_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func sqrt(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vsqrt_f(input.vsip, resultsIn.vsip) case .d: vsip_vsqrt_d(input.vsip, resultsIn.vsip) case .cf: vsip_cvsqrt_f(input.vsip, resultsIn.vsip) case .cd: vsip_cvsqrt_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func sqrt(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_msqrt_f(input.vsip, resultsIn.vsip) case .d: vsip_msqrt_d(input.vsip, resultsIn.vsip) case .cf: vsip_cmsqrt_f(input.vsip, resultsIn.vsip) case .cd: vsip_cmsqrt_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func tan(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vtan_f(input.vsip, resultsIn.vsip) case .d: vsip_vtan_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func tan(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_mtan_f(input.vsip, resultsIn.vsip) case .d: vsip_mtan_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func tanh(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_vtanh_f(input.vsip, resultsIn.vsip) case .d: vsip_vtanh_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func tanh(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .f: vsip_mtanh_f(input.vsip, resultsIn.vsip) case .d: vsip_mtanh_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } // MARK: - Unary Functions public func arg(_ input: Vector, resultsIn: Vector) { let type = (input.type, resultsIn.type) assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch type { case (.cf, .f): vsip_varg_f(input.vsip, resultsIn.vsip) case (.cd, .d): vsip_varg_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for input/resultsIn views") } } public func arg(_ input: Matrix, resultsIn: Matrix) { let type = (input.type, resultsIn.type) assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch type { case (.cf, .f): vsip_marg_f(input.vsip, resultsIn.vsip) case (.cd, .d): vsip_marg_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for input/resultsIn views") } } public func ceil(_ input: Vector, resultsIn: Vector){ assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch (input.type, resultsIn.type) { case (.d, .d): vsip_vceil_d_d(input.vsip, resultsIn.vsip) case (.d,.i): vsip_vceil_d_i(input.vsip, resultsIn.vsip) case (.f, .f): vsip_vceil_f_f(input.vsip, resultsIn.vsip) case (.f,.i): vsip_vceil_f_i(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for input/resultsIn views") break } } public func ceil(_ input: Matrix, resultsIn: Matrix){ assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch (input.type, resultsIn.type) { case (.d, .d): vsip_mceil_d_d(input.vsip, resultsIn.vsip) case (.d,.i): vsip_mceil_d_i(input.vsip, resultsIn.vsip) case (.f, .f): vsip_mceil_f_f(input.vsip, resultsIn.vsip) case (.f,.i): vsip_mceil_f_i(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for input/resultsIn views") break } } public func conj(_ input: Vector, resultsIn: Vector) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .cf: vsip_cvconj_f(input.vsip, resultsIn.vsip) case .cd: vsip_cvconj_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func conj(_ input: Matrix, resultsIn: Matrix) { assert(input.type == resultsIn.type, "View types must agree") assert(sizeEqual(input, against: resultsIn), "Views must be the same size") switch input.type { case .cf: vsip_cmconj_f(input.vsip, resultsIn.vsip) case .cd: vsip_cmconj_d(input.vsip, resultsIn.vsip) default: preconditionFailure("function not supported") break } } public func neg(_ input: Vector, resultsIn: Vector){ assert(sizeEqual(input, against: resultsIn), "View size of input an resultsIn must be equal for neg") assert(input.type == resultsIn.type, "View types of input and resultsIn must be the same for neg") switch input.type { case .f: vsip_vneg_f(input.vsip,resultsIn.vsip) case .d: vsip_vneg_d(input.vsip,resultsIn.vsip) case .cf: vsip_cvneg_f(input.vsip,resultsIn.vsip) case .cd: vsip_cvneg_d(input.vsip,resultsIn.vsip) case .i: vsip_vneg_i(input.vsip,resultsIn.vsip) case .li: vsip_vneg_li(input.vsip,resultsIn.vsip) case .vi: vsip_vneg_si(input.vsip,resultsIn.vsip) default: assert(false, "type not found for neg") break } } public func neg(_ input: Matrix, resultsIn: Matrix){ assert(sizeEqual(input, against: resultsIn), "View size of input an resultsIn must be equal for neg") assert(input.type == resultsIn.type, "View types of input and resultsIn must be the same for neg") switch input.type { case .f: vsip_mneg_f(input.vsip,resultsIn.vsip) case .d: vsip_mneg_d(input.vsip,resultsIn.vsip) case .cf: vsip_cmneg_f(input.vsip,resultsIn.vsip) case .cd: vsip_cmneg_d(input.vsip,resultsIn.vsip) default: assert(false, "type not found for neg") break } } public func sumval(_ input: Vector) -> Scalar { switch input.type { case .d: return Scalar(vsip_vsumval_d(input.vsip)) case .f: return Scalar(vsip_vsumval_f(input.vsip)) case .cd: return Scalar(vsip_cvsumval_d(input.vsip)) case .cf: return Scalar(vsip_cvsumval_f(input.vsip)) case .i: return Scalar(vsip_vsumval_i(input.vsip)) case .bl: return Scalar(vsip_vsumval_bl(input.vsip)) default: preconditionFailure("sumval not supported for this type") } } public func sumval(_ input: Matrix) -> Scalar { switch input.type { case .d: return Scalar(vsip_msumval_d(input.vsip)) case .f: return Scalar(vsip_msumval_f(input.vsip)) case .cd: return Scalar(vsip_cmsumval_d(input.vsip)) case .cf: return Scalar(vsip_cmsumval_f(input.vsip)) case .bl: return Scalar(vsip_msumval_bl(input.vsip)) default: preconditionFailure("sumval not supported for this type") } } public func sumsqval(_ input: Vector) -> Scalar { switch input.type { case .d: return Scalar(Double(vsip_vsumsqval_d(input.vsip))) case .f: return Scalar(Float(vsip_vsumsqval_f(input.vsip))) default: preconditionFailure("sumsqval not supported for this type") break } } public func sumsqval(_ input: Matrix) -> Scalar { switch input.type { case .d: return Scalar(Double(vsip_msumsqval_d(input.vsip))) case .f: return Scalar(Float(vsip_msumsqval_f(input.vsip))) default: preconditionFailure("sumsqval not supported for this type") break } } // MARK: - Binary Functions public func add(_ one: Vector, _ to: Vector, resultsIn: Vector) { assert(sizeEqual(one, against: to),"Views must be the same size") assert(to.type == resultsIn.type, "Output view type not compliant with input") switch one.type { case .f: switch to.type{ case .f: vsip_vadd_f(one.vsip, to.vsip, resultsIn.vsip) case .cf: vsip_rcvadd_f(one.vsip, to.vsip, resultsIn.vsip) default: break } case .d: switch to.type{ case .d: vsip_vadd_d(one.vsip, to.vsip, resultsIn.vsip) case .cd: vsip_rcvadd_d(one.vsip, to.vsip, resultsIn.vsip) default: break } case .cf: vsip_cvadd_f(one.vsip, to.vsip, resultsIn.vsip) case .cd: vsip_cvadd_d(one.vsip, to.vsip, resultsIn.vsip) case .i: vsip_vadd_d(one.vsip, to.vsip, resultsIn.vsip) case .li: vsip_vadd_li(one.vsip, to.vsip, resultsIn.vsip) case .uc: vsip_vadd_li(one.vsip, to.vsip, resultsIn.vsip) case .si: vsip_vadd_si(one.vsip, to.vsip, resultsIn.vsip) case .vi: vsip_vadd_vi(one.vsip, to.vsip, resultsIn.vsip) default: preconditionFailure("View type not supported") break } } public func add(_ one: Matrix, _ to: Matrix, resultsIn: Matrix) { assert(sizeEqual(one, against: to),"Views must be the same size") assert(to.type == resultsIn.type, "Output view type not compliant with input") switch one.type { case .f: switch to.type{ case .f: vsip_madd_f(one.vsip, to.vsip, resultsIn.vsip) case .cf: vsip_rcmadd_f(one.vsip, to.vsip, resultsIn.vsip) default: break } case .d: switch to.type{ case .d: vsip_madd_d(one.vsip, to.vsip, resultsIn.vsip) case .cd: vsip_rcmadd_d(one.vsip, to.vsip, resultsIn.vsip) default: break } case .cf: vsip_cmadd_f(one.vsip, to.vsip, resultsIn.vsip) case .cd: vsip_cmadd_d(one.vsip, to.vsip, resultsIn.vsip) case .i: vsip_madd_d(one.vsip, to.vsip, resultsIn.vsip) case .li: vsip_madd_li(one.vsip, to.vsip, resultsIn.vsip) case .si: vsip_madd_si(one.vsip, to.vsip, resultsIn.vsip) default: preconditionFailure("View type not supported") break } } public func add(_ scalar: Double, _ vector: Vector, resultsIn: Vector){ add(Scalar(scalar), vector, resultsIn: resultsIn) } public func add(_ scalar: Float, _ vector: Vector, resultsIn: Vector){ add(Scalar(scalar), vector, resultsIn: resultsIn) } public func add(_ scalar: Int, _ vector: Vector, resultsIn: Vector){ add(Scalar(scalar), vector, resultsIn: resultsIn) } public func add(_ scalar: Scalar, _ vector: Vector, resultsIn: Vector){ assert(vector.type == resultsIn.type, "View types must agrees") let t = (scalar.type, vector.type, resultsIn.type) switch t { case (.f, .f, .f): vsip_svadd_f(scalar.vsip_f, vector.vsip, resultsIn.vsip) case (.d, .d, .d): vsip_svadd_d(scalar.vsip_d, vector.vsip, resultsIn.vsip) case (.f, .cf, .cf): vsip_rscvadd_f(scalar.vsip_f, vector.vsip, resultsIn.vsip) case (.d, .cd, .cd): vsip_rscvadd_d(scalar.vsip_d, vector.vsip, resultsIn.vsip) case (.cf, .cf, .cf): vsip_csvadd_f(scalar.vsip_cf, vector.vsip, resultsIn.vsip) case (.cd, .cd, .cd): vsip_csvadd_d(scalar.vsip_cd, vector.vsip, resultsIn.vsip) case (.i, .i, .i): vsip_svadd_i(scalar.vsip_i, vector.vsip, resultsIn.vsip) case (.li, .li, .li): vsip_svadd_li(scalar.vsip_li, vector.vsip, resultsIn.vsip) case (.si, .si, .si): vsip_svadd_si(scalar.vsip_si, vector.vsip, resultsIn.vsip) case (.uc, .uc, .uc): vsip_svadd_uc(scalar.vsip_uc, vector.vsip, resultsIn.vsip) case (.vi, .vi, .vi): vsip_svadd_vi(scalar.vsip_vi, vector.vsip, resultsIn.vsip) default: preconditionFailure("Argument string not supported for svadd") } } public func add(_ scalar: Double, _ matrix: Matrix, resultsIn: Matrix){ add(Scalar(scalar), matrix, resultsIn: resultsIn) } public func add(_ scalar: Float, _ matrix: Matrix, resultsIn: Matrix){ add(Scalar(scalar), matrix, resultsIn: resultsIn) } public func add(_ scalar: Scalar, _ matrix: Matrix, resultsIn: Matrix){ assert(sizeEqual(matrix, against: resultsIn),"Views must be the same size") let t = (scalar.type, matrix.type, resultsIn.type) switch t { case (.f, .f, .f): vsip_smadd_f(scalar.vsip_f, matrix.vsip, resultsIn.vsip) case (.d, .d, .d): vsip_smadd_d(scalar.vsip_d, matrix.vsip, resultsIn.vsip) case (.f, .cf, .cf): vsip_rscmadd_f(scalar.vsip_f, matrix.vsip, resultsIn.vsip) case (.d, .cd, .cd): vsip_rscmadd_d(scalar.vsip_d, matrix.vsip, resultsIn.vsip) case (.cf, .cf, .cf): vsip_csmadd_f(scalar.vsip_cf, matrix.vsip, resultsIn.vsip) case (.cd, .cd, .cd): vsip_csmadd_d(scalar.vsip_cd, matrix.vsip, resultsIn.vsip) default: preconditionFailure("Argument string not supported for scalar matrix add") } } public func div(numerator aView: Vector, denominator by: Vector, quotient resultsIn: Vector){ assert(sizeEqual(aView, against: by),"Views must be the same size") assert(sizeEqual(aView, against: resultsIn),"Views must be the same size") let t = (aView.type, by.type, resultsIn.type) switch t { case (.d, .cd, .cd): vsip_rcvdiv_d(aView.vsip, by.vsip, resultsIn.vsip) case (.f, .cf, .cf): vsip_rcvdiv_f(aView.vsip, by.vsip, resultsIn.vsip) case (.d, .d, .d): vsip_vdiv_d(aView.vsip, by.vsip, resultsIn.vsip) case (.f, .f, .f): vsip_vdiv_f(aView.vsip, by.vsip, resultsIn.vsip) case (.cd, .d, .cd): vsip_crvdiv_d(aView.vsip, by.vsip, resultsIn.vsip) case (.cf, .f, .cf): vsip_crvdiv_f(aView.vsip, by.vsip, resultsIn.vsip) case (.cd, .cd, .cd): vsip_cvdiv_d(aView.vsip, by.vsip, resultsIn.vsip) case (.cf, .cf, .cf): vsip_cvdiv_f(aView.vsip, by.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for input/resultsIn views of type (\t)") } } public func div(numerator aView: Matrix, denominator by: Matrix, quotient resultsIn: Matrix){ assert(sizeEqual(aView, against: by),"Views must be the same size") assert(sizeEqual(aView, against: resultsIn),"Views must be the same size") let t = (aView.type, by.type, resultsIn.type) switch t { case (.cd, .cd, .cd): vsip_cmdiv_d(aView.vsip, by.vsip, resultsIn.vsip) case (.cf, .cf, .cf): vsip_cmdiv_f(aView.vsip, by.vsip, resultsIn.vsip) case (.cd, .d, .cd): vsip_crmdiv_d(aView.vsip, by.vsip, resultsIn.vsip) case (.cf, .f, .cf): vsip_crmdiv_f(aView.vsip, by.vsip, resultsIn.vsip) case (.d, .d, .d): vsip_mdiv_d(aView.vsip, by.vsip, resultsIn.vsip) case (.f, .f, .f): vsip_mdiv_f(aView.vsip, by.vsip, resultsIn.vsip) case (.d, .cd, .cd): vsip_rcmdiv_d(aView.vsip, by.vsip, resultsIn.vsip) case (.f, .cf, .cf): vsip_rcmdiv_f(aView.vsip, by.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for input/resultsIn views of type (\t)") } } public func mul(_ one: Vector, _ to: Vector, resultsIn: Vector) { assert(sizeEqual(one, against: to),"Views must be the same size") switch (one.type, to.type, resultsIn.type) { case (.f,.f,.f): vsip_vmul_f(one.vsip, to.vsip, resultsIn.vsip) case (.f,.cf, .cf): vsip_rcvmul_f(one.vsip, to.vsip, resultsIn.vsip) case (.d, .d,.d): vsip_vmul_d(one.vsip, to.vsip, resultsIn.vsip) case (.d, .cd, .cd): vsip_rcvmul_d(one.vsip, to.vsip, resultsIn.vsip) case (.cf, .cf, .cf): vsip_cvmul_f(one.vsip, to.vsip, resultsIn.vsip) case (.cd, .cd, .cd): vsip_cvmul_d(one.vsip, to.vsip, resultsIn.vsip) case (.i, .i, .i): vsip_vmul_d(one.vsip, to.vsip, resultsIn.vsip) case (.li, .li, .li): vsip_vmul_li(one.vsip, to.vsip, resultsIn.vsip) case (.uc,.uc,.uc): vsip_vmul_uc(one.vsip, to.vsip, resultsIn.vsip) case (.si,.si,.si): vsip_vmul_si(one.vsip, to.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for input/resultsIn views") } } public func mul(_ one: Matrix, _ to: Matrix, resultsIn: Matrix) { assert(sizeEqual(one, against: to),"Views must be the same size") switch (one.type, to.type, resultsIn.type) { case (.f, .f, .f): vsip_mmul_f(one.vsip, to.vsip, resultsIn.vsip) case (.f, .cf, .cf): vsip_rcmmul_f(one.vsip, to.vsip, resultsIn.vsip) case (.d, .d, .d): vsip_mmul_d(one.vsip, to.vsip, resultsIn.vsip) case (.f, .cd, .cd): vsip_rcmmul_d(one.vsip, to.vsip, resultsIn.vsip) case (.cf, .cf, .cf): vsip_cmmul_f(one.vsip, to.vsip, resultsIn.vsip) case (.cd, .cd, .cd): vsip_cmmul_d(one.vsip, to.vsip, resultsIn.vsip) default: preconditionFailure("function not supported for input/resultsIn views") } } public func mul(_ scalar: Double, _ vector: Vector, resultsIn: Vector){ mul(Scalar(scalar), vector, resultsIn: resultsIn) } public func mul(_ scalar: Float, _ vector: Vector, resultsIn: Vector){ mul(Scalar(scalar), vector, resultsIn: resultsIn) } public func mul(_ scalar: Int, _ vector: Vector, resultsIn: Vector){ mul(Scalar(scalar), vector, resultsIn: resultsIn) } public func mul(_ scalar: Scalar,_ vector: Vector, resultsIn: Vector){ assert(sizeEqual(vector, against: resultsIn), "View sizes must be the same") let t = (scalar.type, vector.type, resultsIn.type) switch t { case (.f, .f, .f): vsip_svmul_f(scalar.vsip_f, vector.vsip, resultsIn.vsip) case (.d, .d, .d): vsip_svmul_d(scalar.vsip_d, vector.vsip, resultsIn.vsip) case (.f, .cf, .cf): vsip_rscvmul_f(scalar.vsip_f, vector.vsip, resultsIn.vsip) case (.d, .cd, .cd): vsip_rscvmul_d(scalar.vsip_d, vector.vsip, resultsIn.vsip) case (.cf, .cf, .cf): vsip_csvmul_f(scalar.vsip_cf, vector.vsip, resultsIn.vsip) case (.cd, .cd, .cd): vsip_csvmul_d(scalar.vsip_cd, vector.vsip, resultsIn.vsip) case (.i, .i, .i): vsip_svmul_i(scalar.vsip_i, vector.vsip, resultsIn.vsip) case (.li, .li, .li): vsip_svmul_li(scalar.vsip_li, vector.vsip, resultsIn.vsip) case (.si, .si, .si): vsip_svmul_si(scalar.vsip_si, vector.vsip, resultsIn.vsip) case (.uc, .uc, .uc): vsip_svmul_uc(scalar.vsip_uc, vector.vsip, resultsIn.vsip) default: preconditionFailure("Argument string not supported for svmul") } } public func mul(_ scalar: Double, _ matrix: Matrix, resultsIn: Matrix){ mul(Scalar(scalar), matrix, resultsIn: resultsIn) } public func mul(_ scalar: Float, _ matrix: Matrix, resultsIn: Matrix){ mul(Scalar(scalar), matrix, resultsIn: resultsIn) } public func mul(_ scalar: Scalar,_ matrix: Matrix, resultsIn: Matrix){ assert(sizeEqual(matrix, against: resultsIn),"Views must be the same size") let t = (scalar.type, matrix.type, resultsIn.type) switch t { case (.f, .f, .f): vsip_smmul_f(scalar.vsip_f, matrix.vsip, resultsIn.vsip) case (.d, .d, .d): vsip_smmul_d(scalar.vsip_d, matrix.vsip, resultsIn.vsip) case (.f,.cf, .cf): vsip_rscmmul_f(scalar.vsip_f, matrix.vsip, resultsIn.vsip) case (.d, .cd, .cd): vsip_rscmmul_d(scalar.vsip_d, matrix.vsip, resultsIn.vsip) case (.cd, .cd, .cd): vsip_csmmul_d(scalar.vsip_cd, matrix.vsip, resultsIn.vsip) case (.cf, .cf, .cf): vsip_csmmul_f(scalar.vsip_cf, matrix.vsip, resultsIn.vsip) default: preconditionFailure("Argument string not supported for mul") } } public func vmmul(vector: Vector, matrix: Matrix, major: vsip_major, resultsIn: Matrix){ let vsipVec = vector.vsip let vsipMat = matrix.vsip let vsipOut = resultsIn.vsip let t = (vector.type, matrix.type, resultsIn.type) switch t { case(.cd, .cd, .cd): vsip_cvmmul_d ( vsipVec, vsipMat, major, vsipOut) case(.cf, .cf, .cf): vsip_cvmmul_f ( vsipVec, vsipMat, major, vsipOut) case(.d, .cd, .cd): vsip_rvcmmul_d ( vsipVec, vsipMat, major, vsipOut) case(.f, .cf, .cf): vsip_rvcmmul_f ( vsipVec, vsipMat, major, vsipOut) case(.d, .d, .d): vsip_vmmul_d ( vsipVec, vsipMat, major, vsipOut) case(.f, .f, .f): vsip_vmmul_f ( vsipVec, vsipMat, major, vsipOut) default: preconditionFailure("Argument list not supported for vmmul") } } public func sub(_ aView: Vector, subtract: Vector, resultsIn: Vector){ assert(sizeEqual(aView, against: subtract),"Views must be the same size") assert(sizeEqual(aView, against: resultsIn), "Views must be the same size") let t = (aView.type, subtract.type, resultsIn.type) switch t{ case (.cd, .d, .cd): vsip_crvsub_d (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.cf, .f, .cf): vsip_crvsub_f (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.cd, .cd, .cd): vsip_cvsub_d (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.cf, .cf, .cf): vsip_cvsub_f (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.d, .cd, .cd): vsip_rcvsub_d (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.f, .cf, .cf): vsip_rcvsub_f (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.d, .d, .d): vsip_vsub_d (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.f, .f, .f): vsip_vsub_f (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.i, .i, .i): vsip_vsub_i (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.li, .li, .li): vsip_vsub_li (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.si, .si, .si): vsip_vsub_si (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.uc, .uc, .uc): vsip_vsub_uc (aView.vsip,subtract.vsip,resultsIn.vsip ) default: preconditionFailure("function not supported for input/resultsIn views") } } public func sub(_ aView: Matrix, subtract: Matrix, resultsIn: Matrix){ assert(sizeEqual(aView, against: subtract),"Views must be the same size") assert(sizeEqual(aView, against: resultsIn), "Views must be the same size") let t = (aView.type, subtract.type, resultsIn.type) switch t{ case (.cd, .cd, .cd): vsip_cmsub_d (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.cf, .cf, .cf): vsip_cmsub_f (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.cd, .d, .cd): vsip_crmsub_d (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.cf, .f, .cf): vsip_crmsub_f (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.si, .si, .si): vsip_msub_si (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.d, .cd, .cd): vsip_rcmsub_d (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.d, .d, .d): vsip_msub_d (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.f, .f, .f): vsip_msub_f (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.i, .i, .i): vsip_msub_i (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.li, .li, .li): vsip_msub_li (aView.vsip,subtract.vsip,resultsIn.vsip ) case (.f, .cf, .cf): vsip_rcmsub_f (aView.vsip,subtract.vsip,resultsIn.vsip ) default: preconditionFailure("function not supported for input/resultsIn views \(t)") } } // Mark: - Random public class Rand { fileprivate var tryVsip : OpaquePointer? var vsip: OpaquePointer { get { return tryVsip! } } let jInit : JVSIP var myId : NSNumber? public init(seed: vsip_index, numberOfSubSequences: vsip_index, mySequence: vsip_index, portable: Bool){ let rng = portable ? VSIP_PRNG : VSIP_NPRNG let id = mySequence let numprocs = numberOfSubSequences if let randObj = vsip_randcreate(seed, numprocs, id, rng){ tryVsip = randObj } else { preconditionFailure("Failed to create vsip rand object") } jInit = JVSIP() myId = jInit.myId } public convenience init(seed: vsip_index, portable: Bool){ self.init(seed: seed, numberOfSubSequences: 1, mySequence: 1, portable: portable) } public func randu(_ view: Vector){ let t = view.type switch t{ case .f: vsip_vrandu_f(self.vsip,view.vsip) case .d: vsip_vrandu_d(self.vsip,view.vsip) case .cf: vsip_cvrandu_f(self.vsip,view.vsip) case .cd: vsip_cvrandu_d(self.vsip,view.vsip) default: preconditionFailure("Type \(t) not defined for randu") } } public func randu(_ view: Matrix){ let t = view.type switch t { case .f: vsip_mrandu_f(self.vsip,view.vsip) case .d: vsip_mrandu_d(self.vsip,view.vsip) case .cf: vsip_cmrandu_f(self.vsip,view.vsip) case .cd: vsip_cmrandu_d(self.vsip,view.vsip) default: preconditionFailure("Type \(t) not defined for randu") } } public func randn(_ view: Vector) { let t = view.type switch t{ case .f: vsip_vrandn_f(self.vsip,view.vsip) case .d: vsip_vrandn_d(self.vsip,view.vsip) case .cf: vsip_cvrandn_f(self.vsip,view.vsip) case .cd: vsip_cvrandn_d(self.vsip,view.vsip) default: preconditionFailure("Type \(t) not defined for randn") } } public func randn(_ view: Matrix) { let t = view.type switch t{ case .f: vsip_mrandn_f(self.vsip,view.vsip) case .d: vsip_mrandn_d(self.vsip,view.vsip) case .cf: vsip_cmrandn_f(self.vsip,view.vsip) case .cd: vsip_cmrandn_d(self.vsip,view.vsip) default: preconditionFailure("Type \(t) not defined for randn") } } deinit{ //let id = self.myId?.int32Value vsip_randdestroy(self.vsip) /* if _isDebugAssertConfiguration(){ print("randdestroy id \(id!)") }*/ } } // MARK: - Element Generation and Copy public func copy(from: Matrix, to: Matrix) { let t = (from.type, to.type) switch t{ case (.f, .f): vsip_mcopy_f_f(from.vsip, to.vsip) case (.f, .d): vsip_mcopy_f_d(from.vsip, to.vsip) case (.d, .f): vsip_mcopy_d_f(from.vsip, to.vsip) case(.d, .d): vsip_mcopy_d_d(from.vsip, to.vsip) case (.cf, .cf): vsip_cmcopy_f_f(from.vsip, to.vsip) case (.cf, .cd): vsip_cmcopy_f_d(from.vsip, to.vsip) case (.cd, .cf): vsip_cmcopy_d_f(from.vsip, to.vsip) case(.cd, .cd): vsip_cmcopy_d_d(from.vsip, to.vsip) case(.i, .i): vsip_mcopy_i_i(from.vsip, to.vsip) case(.f, .i): vsip_mcopy_f_i(from.vsip, to.vsip) case(.i, .f): vsip_mcopy_f_i(from.vsip, to.vsip) case(.d, .i): vsip_mcopy_f_i(from.vsip, to.vsip) case(.i, .d): vsip_mcopy_f_i(from.vsip, to.vsip) default: preconditionFailure("Copy not supported for type \(t)") } } public func copy(from: Vector, to: Vector) { let t = (from.type, to.type) switch t { case (.f, .f): vsip_vcopy_f_f(from.vsip, to.vsip) case (.f, .d): vsip_vcopy_f_d(from.vsip, to.vsip) case (.d, .f): vsip_vcopy_d_f(from.vsip, to.vsip) case(.d, .d): vsip_vcopy_d_d(from.vsip, to.vsip) case (.cf, .cf): vsip_cvcopy_f_f(from.vsip, to.vsip) case (.cf, .cd): vsip_cvcopy_f_d(from.vsip, to.vsip) case (.cd, .cf): vsip_cvcopy_d_f(from.vsip, to.vsip) case(.cd, .cd): vsip_cvcopy_d_d(from.vsip, to.vsip) case(.i, .i): vsip_vcopy_i_i(from.vsip, to.vsip) case(.f, .i): vsip_vcopy_f_i(from.vsip, to.vsip) case(.i, .f): vsip_vcopy_f_i(from.vsip, to.vsip) case(.d, .i): vsip_vcopy_f_i(from.vsip, to.vsip) case(.i, .d): vsip_vcopy_f_i(from.vsip, to.vsip) default: preconditionFailure("Copy not supported for type \(t)") } } // MARK: - Linear Algebra Matrix and Vector Operations public func herm(_ complexInputMatrix: Matrix, output: Matrix){ let vsipA = complexInputMatrix.vsip let vsipB = output.vsip let t = (complexInputMatrix.type, output.type) switch t { case (.cf, .cf): vsip_cmherm_f(vsipA, vsipB) case (.cd, .cd): vsip_cmherm_d(vsipA, vsipB) default: preconditionFailure("Type not supported for herm") } } public func jdot(_ complexInputVector: Vector,dot complexOuputVector: Vector) -> Scalar { let vsipA = complexInputVector.vsip let vsipB = complexOuputVector.vsip let t = (complexInputVector.type, complexInputVector.type) switch t { case (.cf, .cf): return Scalar(vsip_cvjdot_f(vsipA, vsipB)) case (.cd, .cd): return Scalar(vsip_cvjdot_d(vsipA, vsipB)) default: preconditionFailure("Type not supported for jdot") } } public func gemp(alpha: Scalar, matA: Matrix, opA: vsip_mat_op, matB: Matrix, opB: vsip_mat_op, beta: Scalar, matC: Matrix) { let t = (matA.type, matB.type, matC.type) let vsipA = matA.vsip let vsipB = matB.vsip let vsipC = matC.vsip switch(t){ case (.d, .d, .d): vsip_gemp_d(alpha.reald, vsipA, opA, vsipB, opB, beta.reald, vsipC) case (.f, .f, .f): vsip_gemp_f(alpha.realf, vsipA, opA, vsipB, opB, beta.realf, vsipC) case (.cd, .cd, .cd): vsip_cgemp_d(alpha.vsip_cd, vsipA, opA, vsipB, opB, beta.vsip_cd, vsipC) case (.cf, .cf, .cf): vsip_cgemp_f(alpha.vsip_cf, vsipA, opA, vsipB, opB, beta.vsip_cf, vsipC) default: preconditionFailure("Type not supported for gemp") } } public func gems(alpha: Scalar, matA: Matrix, opA: vsip_mat_op, beta: Scalar, matC: Matrix){ let t = (matA.type, matC.type) let vsipA = matA.vsip let vsipC = matC.vsip switch(t){ case (.d, .d): vsip_gems_d(alpha.reald, vsipA, opA, beta.reald, vsipC) case (.f, .f): vsip_gems_f(alpha.realf, vsipA, opA, beta.realf, vsipC) case (.cd, .cd): vsip_cgems_d(alpha.vsip_cd, vsipA, opA, beta.vsip_cd, vsipC) case (.cf, .cf): vsip_cgems_f(alpha.vsip_cf, vsipA, opA, beta.vsip_cf, vsipC) default: preconditionFailure("Type not supported for gemp") } } public func kron(alpha: Scalar, vecX: Vector, vecY: Vector, resutltsIn matC: Matrix){ let t = (vecX.type, vecY.type, matC.type) let vsipX = vecX.vsip let vsipY = vecY.vsip let vsipC = matC.vsip switch(t){ case (.f, .f, .f): vsip_vkron_f(alpha.realf, vsipX, vsipY, vsipC) case (.d, .d, .d): vsip_vkron_d(alpha.reald, vsipX, vsipY, vsipC) case (.cf, .cf, .cf): vsip_cvkron_f(alpha.vsip_cf, vsipX, vsipY, vsipC) case (.cd, .cd, .cd): vsip_cvkron_d(alpha.vsip_cd, vsipX, vsipY, vsipC) default: preconditionFailure("Kron not supported for argument list") } } public func kron(alpha: Scalar, matA: Matrix, matB: Matrix, resutltsIn matC: Matrix){ let t = (matA.type, matB.type, matC.type) let vsipA = matA.vsip let vsipB = matB.vsip let vsipC = matC.vsip switch(t){ case (.f, .f, .f): vsip_mkron_f(alpha.realf, vsipA, vsipB, vsipC) case (.d, .d, .d): vsip_mkron_d(alpha.reald, vsipA, vsipB, vsipC) case (.cf, .cf, .cf): vsip_cmkron_f(alpha.vsip_cf, vsipA, vsipB, vsipC) case (.cd, .cd, .cd): vsip_cmkron_d(alpha.vsip_cd, vsipA, vsipB, vsipC) default: preconditionFailure("Kron not supported for argument list") } } public func prod3(_ matA: Matrix,times matB: Matrix, resutltsIn matC: Matrix){ let t = (matA.type, matB.type, matC.type) let vsipA = matA.vsip let vsipB = matB.vsip let vsipC = matC.vsip switch(t){ case (.f, .f, .f): vsip_mprod3_f(vsipA, vsipB, vsipC) case (.d, .d, .d): vsip_mprod3_d(vsipA, vsipB, vsipC) case (.cf, .cf, .cf): vsip_cmprod3_f(vsipA, vsipB, vsipC) case (.cd, .cd, .cd): vsip_cmprod3_d(vsipA, vsipB, vsipC) default: preconditionFailure("VSIP function prod3 not supported for argument list") } } public func prod3(_ matA: Matrix,times vecB: Vector, resutltsIn vecC: Vector){ let t = (matA.type, vecB.type, vecC.type) let vsipA = matA.vsip let vsipB = vecB.vsip let vsipC = vecC.vsip switch(t){ case (.f, .f, .f): vsip_mvprod3_f(vsipA, vsipB, vsipC) case (.d, .d, .d): vsip_mvprod3_d(vsipA, vsipB, vsipC) case (.cf, .cf, .cf): vsip_cmvprod3_f(vsipA, vsipB, vsipC) case (.cd, .cd, .cd): vsip_cmvprod3_d(vsipA, vsipB, vsipC) default: preconditionFailure("VSIP function prod4 not supported for argument list") } } public func prod4(_ matA: Matrix, times matB: Matrix, resutltsIn matC: Matrix){ let t = (matA.type, matB.type, matC.type) let vsipA = matA.vsip let vsipB = matB.vsip let vsipC = matC.vsip switch(t){ case (.f, .f, .f): vsip_mprod4_f(vsipA, vsipB, vsipC) case (.d, .d, .d): vsip_mprod4_d(vsipA, vsipB, vsipC) case (.cf, .cf, .cf): vsip_cmprod4_f(vsipA, vsipB, vsipC) case (.cd, .cd, .cd): vsip_cmprod4_d(vsipA, vsipB, vsipC) default: preconditionFailure("VSIP function prod4 not supported for argument list") } } public func prod4(_ matA: Matrix, times vecB: Vector, resutltsIn vecC: Vector){ let t = (matA.type, vecB.type, vecC.type) let vsipA = matA.vsip let vsipB = vecB.vsip let vsipC = vecC.vsip switch(t){ case (.f, .f, .f): vsip_mvprod4_f(vsipA, vsipB, vsipC) case (.d, .d, .d): vsip_mvprod4_d(vsipA, vsipB, vsipC) case (.cf, .cf, .cf): vsip_cmvprod4_f(vsipA, vsipB, vsipC) case (.cd, .cd, .cd): vsip_cmvprod4_d(vsipA, vsipB, vsipC) default: preconditionFailure("VSIP function prod4 not supported for argument list") } } public func prod(_ matA: Matrix,times matB: Matrix,resultsIn matC: Matrix){ let t = (matA.type, matB.type, matC.type) let vsipA = matA.vsip let vsipB = matB.vsip let vsipC = matC.vsip switch(t){ case (.cd, .cd, .cd): vsip_cmprod_d ( vsipA, vsipB, vsipC ) case (.cf, .cf, .cf): vsip_cmprod_f ( vsipA, vsipB, vsipC ) case (.d, .d, .d): vsip_mprod_d ( vsipA, vsipB, vsipC ) case (.f, .f, .f): vsip_mprod_f ( vsipA, vsipB, vsipC ) default: preconditionFailure("VSIP function prod not supported for argument list") } } public func prod(_ matA: Matrix, times vecB: Vector,resultsIn vecC: Vector){ let t = (matA.type, vecB.type, vecC.type) let vsipA = matA.vsip let vsipB = vecB.vsip let vsipC = vecC.vsip switch(t){ case (.cd, .cd, .cd): vsip_cmvprod_d ( vsipA, vsipB, vsipC ) case (.cf, .cf, .cf): vsip_cmvprod_f ( vsipA, vsipB, vsipC ) case (.d, .d, .d): vsip_mvprod_d ( vsipA, vsipB, vsipC ) case (.f, .f, .f): vsip_mvprod_f ( vsipA, vsipB, vsipC ) default: preconditionFailure("VSIP function prod not supported for argument list") } } public func prod(_ vecA: Vector, times matB: Matrix, resultsIn vecC: Vector){ let t = (vecA.type, matB.type, vecC.type) let vsipA = vecA.vsip let vsipB = matB.vsip let vsipC = vecC.vsip switch(t){ case (.cd, .cd, .cd): vsip_cvmprod_d ( vsipA, vsipB, vsipC ) case (.cf, .cf, .cf): vsip_cvmprod_f ( vsipA, vsipB, vsipC ) case (.d, .d, .d): vsip_vmprod_d ( vsipA, vsipB, vsipC ) case (.f, .f, .f): vsip_vmprod_f ( vsipA, vsipB, vsipC ) default: preconditionFailure("VSIP function prod not supported for argument list") } } public func prodh(_ matA: Matrix,timesHermitian matB: Matrix, resultsIn matC: Matrix){ let t = (matA.type, matB.type, matC.type) let vsipA = matA.vsip let vsipB = matB.vsip let vsipC = matC.vsip switch(t){ case (.cd, .cd, .cd): vsip_cmprodh_d ( vsipA, vsipB, vsipC ) case (.cf, .cf, .cf): vsip_cmprodh_f ( vsipA, vsipB, vsipC ) default: preconditionFailure("VSIP function prodh not supported for argument list") } } public func prodj(_ matA: Matrix, timesConjugate matB: Matrix, resultsIn matC: Matrix){ let t = (matA.type, matB.type, matC.type) let vsipA = matA.vsip let vsipB = matB.vsip let vsipC = matC.vsip switch(t){ case (.cd, .cd, .cd): vsip_cmprodj_d ( vsipA, vsipB, vsipC ) case (.cf, .cf, .cf): vsip_cmprodj_f ( vsipA, vsipB, vsipC ) default: preconditionFailure("VSIP function prodj not supported for argument list") } } public func prodt(_ matA: Matrix,timesTranspose matB: Matrix, resultsIn matC: Matrix){ let t = (matA.type, matB.type, matC.type) let vsipA = matA.vsip let vsipB = matB.vsip let vsipC = matC.vsip switch(t){ case (.cd, .cd, .cd): vsip_cmprodt_d ( vsipA, vsipB, vsipC ) case (.cf, .cf, .cf): vsip_cmprodt_f ( vsipA, vsipB, vsipC ) case (.d, .d, .d): vsip_mprodt_d ( vsipA, vsipB, vsipC ) case (.f, .f, .f): vsip_mprodt_f ( vsipA, vsipB, vsipC ) default: preconditionFailure("VSIP function prodt not supported for argument list") } } public func trans(_ matA: Matrix, transposeIn matC: Matrix){ let t = (matA.type, matC.type) let vsipA = matA.vsip let vsipC = matC.vsip switch(t) { case (.cd, .cd): vsip_cmtrans_d(vsipA, vsipC) case(.cf, .cf): vsip_cmtrans_f(vsipA, vsipC) case(.d, .d): vsip_mtrans_d(vsipA, vsipC) case(.f, .f): vsip_mtrans_f(vsipA, vsipC) default: preconditionFailure("VSIP function trans not supported for argument list") } } public func dot(product vecX: Vector, with vecY: Vector) -> Scalar { let t = (vecX.type, vecY.type) let vsipX = vecX.vsip let vsipY = vecY.vsip switch(t){ case (.f, .f): return Scalar(Float(vsip_vdot_f(vsipX, vsipY))) case (.d, .d): return Scalar(Double(vsip_vdot_d(vsipX, vsipY))) case (.cf, .cf): return Scalar(vsip_cvdot_f(vsipX, vsipY)) case (.cd, .cd): return Scalar(vsip_cvdot_d(vsipX, vsipY)) default: preconditionFailure("Kron not supported for argument list") } } public func outer(alpha: Scalar, vecX: Vector, vecY: Vector, matC: Matrix){ let vsipX = vecX.vsip let vsipY = vecY.vsip let vsipC = matC.vsip let t = (vecX.type, vecY.type, matC.type) switch(t){ case (.f, .f, .f): vsip_vouter_f(alpha.realf, vsipX, vsipY, vsipC) case (.d, .d, .d): vsip_vouter_d(alpha.reald, vsipX, vsipY, vsipC) case (.cf, .cf, .cf): vsip_cvouter_f(alpha.vsip_cf, vsipX, vsipY, vsipC) case (.cd, .cd, .cd): vsip_cvouter_d(alpha.vsip_cd, vsipX, vsipY, vsipC) default: preconditionFailure("Function outer not supported for argument list") } } // Mark: - Simple Solvers public func covsol(_ A: Matrix, inputOutput: Matrix) -> Int { let t = (A.type, inputOutput.type) switch t { case (.f, .f): return Int(vsip_covsol_f(A.vsip, inputOutput.vsip)) case (.d, .d): return Int(vsip_covsol_d(A.vsip, inputOutput.vsip)) case (.cf, .cf): return Int(vsip_ccovsol_f(A.vsip, inputOutput.vsip)) case (.cd, .cd): return Int(vsip_ccovsol_d(A.vsip, inputOutput.vsip)) default: preconditionFailure("Type \(t) not supported by covsol") } } <file_sep>/* Created RJudd */ /********************************************************************** // TASP VSIPL Documentation and Code includes no warranty, / // express or implied, including the warranties of merchantability / // and fitness for a particular purpose. No person or organization / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_splineattributes_f.h,v 2.1 2008/08/17 20:45:48 judd Exp $ */ #include"vsip.h" #include"VI.h" struct vsip_splineattributes_f{ vsip_scalar_f *h,*b,*u,*v,*z; int markings; }; <file_sep>// // main.swift // JVExVector // // Created by <NAME> on 10/15/16. // Copyright © 2016 JVSIP. All rights reserved. // import Foundation var v = JVVector_d() if let view = JVVector_d(length: 10) { v = view v.ramp(start: 0.1, step: 0.2) } else { precondition(false, "Malloc Failure") } print("vector of length 10 and offset 0") for i in 0..<v.length{ print(v[i]) } v.length = 5 v.stride = 2 print("vector of length 5 and offset 0") for i in 0..<v.length{ print(v[i]) } v.offset = 1 print("vector of length 5 and offset 1") for i in 0..<v.length{ print(v[i]) } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_offset_f.h,v 2.1 2007/04/18 17:05:56 judd Exp $ */ static void get_put_offset_f(void){ printf("********\nTEST get_put_offset_f\n"); { vsip_offset ivo = 3, icvo=10; vsip_stride ivs = 0, icvs=0; vsip_length ivl = 3, icvl=4; vsip_offset jvo = 2, jcvo=0; vsip_stride irs = 0, ics = 0; vsip_length irl = 2, icl = 3; vsip_stride ixs = 0, iys = 0, izs = 0; vsip_length ixl = 2, iyl = 3, izl = 4; vsip_block_f *b = vsip_blockcreate_f(80,VSIP_MEM_NONE); vsip_cblock_f *cb = vsip_cblockcreate_f(80,VSIP_MEM_NONE); vsip_vview_f *v = vsip_vbind_f(b,ivo,ivs,ivl); vsip_mview_f *m = vsip_mbind_f(b,ivo,ics,icl,irs,irl); vsip_tview_f *t = vsip_tbind_f(b,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_cvview_f *cv = vsip_cvbind_f(cb,icvo,icvs,icvl); vsip_cmview_f *cm = vsip_cmbind_f(cb,ivo,ics,icl,irs,irl); vsip_ctview_f *ct = vsip_ctbind_f(cb,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_offset s; printf("test vgetoffset_f\n"); fflush(stdout); { s = vsip_vgetoffset_f(v); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputoffset_f\n"); fflush(stdout); { vsip_vputoffset_f(v,jvo); s = vsip_vgetoffset_f(v); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } printf("test cvgetoffset_f\n"); fflush(stdout); { s = vsip_cvgetoffset_f(cv); (s == icvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputoffset_f\n"); fflush(stdout); { vsip_cvputoffset_f(cv,jcvo); s = vsip_cvgetoffset_f(cv); (s == jcvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /*************************************************************************/ printf("test mgetoffset_f\n"); fflush(stdout); { s = vsip_mgetoffset_f(m); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputoffset_f\n"); fflush(stdout); { vsip_mputoffset_f(m,jvo); s = vsip_mgetoffset_f(m); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } printf("test cmgetoffset_f\n"); fflush(stdout); { s = vsip_cmgetoffset_f(cm); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test cmputoffset_f\n"); fflush(stdout); { vsip_cmputoffset_f(cm,jvo); s = vsip_cmgetoffset_f(cm); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /*************************************************************************/ printf("test tgetoffset_f\n"); fflush(stdout); { s = vsip_tgetoffset_f(t); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputoffset_f\n"); fflush(stdout); { vsip_tputoffset_f(t,jvo); s = vsip_tgetoffset_f(t); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } printf("test ctgetoffset_f\n"); fflush(stdout); { s = vsip_ctgetoffset_f(ct); (s == ivo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test ctputoffset_f\n"); fflush(stdout); { vsip_ctputoffset_f(ct,jvo); s = vsip_ctgetoffset_f(ct); (s == jvo) ? printf("offset correct\n") : printf("offset error \n"); fflush(stdout); } vsip_vdestroy_f(v); vsip_mdestroy_f(m); vsip_talldestroy_f(t); vsip_cvdestroy_f(cv); vsip_cmdestroy_f(cm); vsip_ctalldestroy_f(ct); } return; } <file_sep>print('TEST vsiputils create and destroy routines') print('this test just does a create and destroy for each supported VSIP type') print('No \'additional\' output means the test passes') import vsiputils as vsip #block create/destroy a=vsip.create('block_f',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('block_d',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('cblock_f',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('cblock_d',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('block_i',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('block_si',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('block_uc',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('block_vi',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('block_mi',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('block_bl',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) #vector view create/destroy a=vsip.create('vview_d',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('vview_f',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('vview_d',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('cvview_f',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('cvview_d',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('vview_i',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('vview_si',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('vview_uc',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('vview_vi',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('vview_mi',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('vview_bl',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) # rand create/destroy a=vsip.create('randstate',(3,1,1,vsip.VSIP_PRNG)) vsip.destroy(a) # window create destroy a=vsip.create('blackman_d',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('blackman_f',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('hanning_d',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('hanning_f',(100,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('kaiser_d',(100,0.5,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('kaiser_f',(100,0.35,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('cheby_d',(100,50,vsip.VSIP_MEM_NONE)) vsip.destroy(a) a=vsip.create('cheby_f',(100,35,vsip.VSIP_MEM_NONE)) vsip.destroy(a) #lu create destroy a=vsip.create('lu_d',10) vsip.destroy(a) a=vsip.create('lu_f',(10,)) vsip.destroy(a) a=vsip.create('clu_f',(10)) vsip.destroy(a) a=vsip.create('clu_d',10) vsip.destroy(a) #cholesky solvers create/destroy a=vsip.create('chol_f',(vsip.VSIP_TR_LOW,10)) vsip.destroy(a) a=vsip.create('chol_d',(vsip.VSIP_TR_UPP,10)) vsip.destroy(a) a=vsip.create('cchol_f',(vsip.VSIP_TR_LOW,10)) vsip.destroy(a) a=vsip.create('cchol_d',(vsip.VSIP_TR_UPP,10)) vsip.destroy(a) # qr solvers create/destroy a=vsip.create('qr_f',(10,5,vsip.VSIP_QRD_NOSAVEQ)) vsip.destroy(a) a=vsip.create('qr_d',(9,4,vsip.VSIP_QRD_SAVEQ)) vsip.destroy(a) a=vsip.create('cqr_f',(11,7,vsip.VSIP_QRD_NOSAVEQ)) vsip.destroy(a) a=vsip.create('cqr_d',(8,4,vsip.VSIP_QRD_SAVEQ1)) vsip.destroy(a) #svd solvers create/destroy a=vsip.create('sv_f',(10,5,vsip.VSIP_SVD_UVNOS,vsip.VSIP_SVD_UVPART)) vsip.destroy(a) a=vsip.create('sv_d',(7,9,vsip.VSIP_SVD_UVFULL,vsip.VSIP_SVD_UVNOS)) vsip.destroy(a) #fir filters create/destroy b=vsip.create('vview_f',(10,vsip.VSIP_MEM_NONE)) a=vsip.create('fir_f',(b,vsip.VSIP_NONSYM,100,2,vsip.VSIP_STATE_NO_SAVE,0,vsip.VSIP_ALG_TIME)) vsip.destroy(a) vsip.destroy(b) b=vsip.create('vview_d',(11,vsip.VSIP_MEM_NONE)) a=vsip.create('fir_d',(b,vsip.VSIP_SYM_EVEN_LEN_ODD,101,5,vsip.VSIP_STATE_SAVE,0,vsip.VSIP_ALG_TIME)) vsip.destroy(a) vsip.destroy(b) b=vsip.create('cvview_f',(8,vsip.VSIP_MEM_NONE)) a=vsip.create('cfir_f',(b,vsip.VSIP_SYM_EVEN_LEN_EVEN,150,3,vsip.VSIP_STATE_NO_SAVE,0,vsip.VSIP_ALG_TIME)) vsip.destroy(a) vsip.destroy(b) b=vsip.create('cvview_d',(6,vsip.VSIP_MEM_NONE)) a=vsip.create('cfir_d',(b,vsip.VSIP_NONSYM,104,1,vsip.VSIP_STATE_SAVE,0,vsip.VSIP_ALG_TIME)) vsip.destroy(a) vsip.destroy(b) #FFT create/destroy a=vsip.create('ccfftop_f',(100,1,vsip.VSIP_FFT_FWD,0,vsip.VSIP_ALG_TIME)) vsip.destroy(a) a=vsip.create('ccfftop_d',(101,.5,vsip.VSIP_FFT_FWD,0,vsip.VSIP_ALG_TIME)) vsip.destroy(a) a=vsip.create('ccfftip_f',(102,.1,vsip.VSIP_FFT_INV,0,vsip.VSIP_ALG_TIME)) vsip.destroy(a) a=vsip.create('ccfftip_d',(103,2,vsip.VSIP_FFT_INV,0,vsip.VSIP_ALG_TIME)) vsip.destroy(a) a=vsip.create('rcfftop_f',(100,2,0,vsip.VSIP_ALG_TIME)) vsip.destroy(a) a=vsip.create('rcfftop_d',(100,1,0,vsip.VSIP_ALG_TIME)) vsip.destroy(a) a=vsip.create('crfftop_f',(100,.001,0,vsip.VSIP_ALG_TIME)) vsip.destroy(a) a=vsip.create('crfftop_d',(100,1.0/100.0,0,vsip.VSIP_ALG_TIME)) vsip.destroy(a) #FFTM create/destroy a=vsip.create('ccfftmop_f',(10,9,1.0,vsip.VSIP_FFT_FWD,vsip.VSIP_ROW,0,vsip.VSIP_ALG_TIME)) vsip.destroy(a) a=vsip.create('ccfftmop_d',(10,9,1.0,vsip.VSIP_FFT_INV,vsip.VSIP_COL,0,vsip.VSIP_ALG_TIME)) vsip.destroy(a) a=vsip.create('ccfftmip_f',(10,9,1.0,vsip.VSIP_FFT_INV,vsip.VSIP_COL,0,vsip.VSIP_ALG_TIME)) vsip.destroy(a) a=vsip.create('ccfftmip_d',(10,9,1.0,vsip.VSIP_FFT_FWD,vsip.VSIP_ROW,0,vsip.VSIP_ALG_TIME)) vsip.destroy(a) a=vsip.create('rcfftmop_f',(100,11,1.0,vsip.VSIP_COL,0,vsip.VSIP_ALG_TIME)) vsip.destroy(a) a=vsip.create('rcfftmop_d',(10,100,1.0,vsip.VSIP_ROW,0,vsip.VSIP_ALG_TIME)) vsip.destroy(a) a=vsip.create('crfftmop_f',(11,100,1.0,vsip.VSIP_ROW,0,vsip.VSIP_ALG_TIME)) vsip.destroy(a) a=vsip.create('crfftmop_d',(8,64,1.0,vsip.VSIP_COL,0,vsip.VSIP_ALG_TIME)) vsip.destroy(a) <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: minvclip_f.h,v 2.0 2003/02/22 15:23:25 judd Exp $ */ #include"VU_mprintm_f.include" static void minvclip_f(void){ printf("\n******\nTEST madd_f\n"); { vsip_scalar_f data1[]= {.1, .2, .3, 4, 5, 6, 7, 8, 9}; vsip_scalar_f ans[] = {0.1, 0.2, 0.0, 1, 1, 1, 7.0, 8.0, 9.0}; vsip_mview_f *a = vsip_mbind_f( vsip_blockbind_f(data1,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_mview_f *b = vsip_mcreate_f(3,3,VSIP_COL,VSIP_MEM_NONE); vsip_mview_f *mans = vsip_mbind_f( vsip_blockbind_f(ans,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_mview_f *chk = vsip_mcreate_f(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_scalar_f min = .25; vsip_scalar_f mid = 1.0; vsip_scalar_f max = 6.5; vsip_scalar_f minval = 0.0; vsip_scalar_f maxval = 1.0; vsip_blockadmit_f(vsip_mgetblock_f(a),VSIP_TRUE); vsip_blockadmit_f(vsip_mgetblock_f(mans),VSIP_TRUE); printf("call vsip_minvclip_f(a,min,mid,max,minval,maxval,b)\n"); printf("min = %f\n",min); printf("mid = %f\n",mid); printf("max = %f\n",max); printf("min to mid value = %f\n",minval); printf("mid to max value = %f\n",maxval); printf("a =\n");VU_mprintm_f("8.6",a); vsip_minvclip_f(a,min,mid,max,minval,maxval,b); printf("b =\n");VU_mprintm_f("8.6",b); printf("\nright answer =\n"); VU_mprintm_f("6.4",mans); vsip_msub_f(mans,b,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,0,.0001,0,1,chk); if(fabs(vsip_msumval_f(chk)) > .5) printf("error\n"); else printf("correct\n"); printf(" a,b inplace\n"); vsip_minvclip_f(a,min,mid,max,minval,maxval,a); printf("a =\n");VU_mprintm_f("8.6",a); vsip_msub_f(mans,a,chk); vsip_mmag_f(chk,chk); vsip_mclip_f(chk,0,.0001,0,1,chk); if(fabs(vsip_msumval_f(chk)) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_f(a); vsip_malldestroy_f(b); vsip_malldestroy_f(mans); vsip_malldestroy_f(chk); } return; } <file_sep># Swift JVsip (SJVsip) A signal processig library. ## About The **SJVsip** project is an example of encapsulation of the **C VSIPL** library under a Swift object oriented wrapper. ## Example ``` import vsip //Needed for some flags; for insance VSIP_ROW import SJVsip // a vector of length 10 and type double let aVector = Vector(length: 10, type: .d) //a Matrix of size (5,10) and type double let aMatrix = Matrix(collength: 5, rowlength: 10, type: .d, major: VSIP_ROW) //fill with some random data aVector.randn(8); aMatrix.randn(4) let output = Vector(length: aMatrix.collength, type: aMatrix.type) prod(aMatrix, aVector, outputIn: output) ``` <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: svd1_f.h,v 1.2 2008/09/21 17:17:49 judd Exp $ */ #include"VU_mprintm_f.include" #include"VU_vprintm_f.include" static void svd1_f(void){ printf("********\nTEST svd1 for float\n"); { vsip_index i; vsip_length M=5, N=6; vsip_scalar_f data[30] = { -1, 2, 0,-3, 6, \ 8, 5, 4,-2, 1, \ 2, 3, 4, 5, 6, \ 7, 8, 9,10,11, \ -1,-2,-3,-4,-5, \ -0,-4,-5,-3,-2}; vsip_vview_f *s = vsip_vcreate_f(((M > N) ? N : M),VSIP_MEM_NONE); vsip_sv_f *svd = vsip_svd_create_f(M,N,VSIP_SVD_UVFULL,VSIP_SVD_UVFULL); vsip_block_f *block = vsip_blockbind_f(data,(M * N),VSIP_MEM_NONE); vsip_mview_f *A0 = vsip_mbind_f(block,0,N,M,1,N); vsip_block_f *vblk = vsip_blockcreate_f(300,VSIP_MEM_NONE); vsip_mview_f *A = vsip_mbind_f(vblk,3,3 * N, M,2 , N); vsip_mview_f *U = vsip_mcreate_f(M,M,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *V = vsip_mcreate_f(N,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *B = vsip_mcreate_f(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_f(block,VSIP_TRUE); vsip_mcopy_f_f(A0,A); printf("in = ");VU_mprintm_f("6.3",A); if(vsip_svd_f(svd,A,s)){ printf("svd error\n"); return; } /* create the singular value matrix */ vsip_mfill_f(0.0,B); for(i=0; i<vsip_vgetlength_f(s); i++) vsip_mput_f(B,i,i,vsip_vget_f(s,i)); vsip_svdmatu_f(svd, 0, M-1, U); vsip_svdmatv_f(svd, 0, N-1, V); printf("U = ");VU_mprintm_f("12.10",U); printf("B = ");VU_mprintm_f("12.10",B); printf("V = ");VU_mprintm_f("12.10",V); VU_vprintm_f("12.10",s); { /* check that A0 = U * B * V' */ vsip_scalar_mi mi; vsip_scalar_f chk = 1.0; vsip_scalar_f lim = 5 * FLT_EPSILON * fabs(vsip_mmaxmgval_f(A0,&mi)); vsip_mview_f *dif=vsip_mcreate_f(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *out = vsip_mcreate_f(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *Vt = vsip_mtransview_f(V); vsip_mprod_f(U,B,dif); vsip_mprod_f(dif,Vt,out); vsip_msub_f(out,A0,dif); vsip_mmag_f(dif, dif); chk = vsip_msumval_f(dif)/(2 * M * N); printf("%20.18e - %20.18e = %e\n",lim,chk, (lim - chk)); if(chk > lim){ printf("error\n"); } else { printf("correct\n"); } vsip_malldestroy_f(dif); vsip_malldestroy_f(out); vsip_mdestroy_f(Vt); } vsip_svd_destroy_f(svd); vsip_malldestroy_f(A0); vsip_malldestroy_f(A); vsip_valldestroy_f(s); vsip_malldestroy_f(U); vsip_malldestroy_f(B); vsip_malldestroy_f(V); } return; } <file_sep>/* * svd6.h * VSIP_svd_dev * * Created by <NAME> on 9/13/08. * Copyright 2008 Home. All rights reserved * */ #include"VU_vprintm_d.include" static void svd6_d(void){ printf("********\nTEST svd6 for double\n"); { vsip_index i; vsip_length M=50, N=100; vsip_randstate *state=vsip_randcreate(4,1,0,VSIP_PRNG); vsip_vview_d *s = vsip_vcreate_d(((M > N) ? N : M),VSIP_MEM_NONE); vsip_sv_d *svd = vsip_svd_create_d(M,N,VSIP_SVD_UVFULL,VSIP_SVD_UVFULL); vsip_mview_d *A0 = vsip_mcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_vview_d *va0 = vsip_vbind_d(vsip_mgetblock_d(A0),0,1,M*N); vsip_mview_d *A = vsip_mcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *U = vsip_mcreate_d(M,M,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *V = vsip_mcreate_d(N,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *B = vsip_mcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_vrandn_d(state,va0); vsip_svmul_d(1E-10,va0,va0); vsip_mcopy_d_d(A0,A); if(vsip_svd_d(svd,A,s)){ printf("svd error\n"); return; } /* create the singular value matrix */ vsip_mfill_d(0.0,B); for(i=0; i<vsip_vgetlength_d(s); i++) vsip_mput_d(B,i,i,vsip_vget_d(s,i)); vsip_svdmatu_d(svd, 0, M-1, U); vsip_svdmatv_d(svd, 0, N-1, V); VU_vprintm_d("12.10",s); { /* check that A0 = U * B * V' */ vsip_scalar_d chk = 1.0; vsip_scalar_d lim = 5 * DBL_EPSILON * sqrt(vsip_msumsqval_d(A0)); vsip_mview_d *dif=vsip_mcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *out = vsip_mcreate_d(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *Vt = vsip_mtransview_d(V); vsip_mprod_d(U,B,dif); vsip_mprod_d(dif,Vt,out); vsip_msub_d(out,A0,dif); vsip_mmag_d(dif, dif); chk = vsip_msumval_d(dif)/(2 * M * N); printf("%20.18e - %20.18e = %e\n",lim,chk, (lim - chk)); if(chk > lim){ printf("error\n"); } else { printf("correct\n"); } vsip_malldestroy_d(dif); vsip_malldestroy_d(out); vsip_mdestroy_d(Vt); } vsip_randdestroy(state); vsip_vdestroy_d(va0); vsip_svd_destroy_d(svd); vsip_malldestroy_d(A0); vsip_malldestroy_d(A); vsip_valldestroy_d(s); vsip_malldestroy_d(U); vsip_malldestroy_d(B); vsip_malldestroy_d(V); } return; } <file_sep>/* Created RJudd */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vcopyfrom_user_si.h,v 1.1 2007/04/21 19:38:33 judd Exp $ */ #include"VU_vprintm_si.include" static void vcopyfrom_user_si(void){ printf("********\nTEST vcopyfrom_user_si\n"); { int i; vsip_block_si *block = vsip_blockcreate_si(200,VSIP_MEM_NONE); vsip_scalar_si input[5]={0,1,2,3,4}; vsip_vview_si *view = vsip_vbind_si(block,100,3,5); vsip_vview_si *all = vsip_vbind_si(block,0,1,200); vsip_scalar_si check = 0; vsip_vfill_si(-1,all); vsip_vcopyfrom_user_si(input,view); VU_vprintm_si("3",view); for(i=0; i<5; i++){ check += fabs((float)(input[i] - vsip_vget_si(view,(vsip_index)i))); } if(check < 0.1){ printf("correct\n"); } else { printf("error\n"); } vsip_vdestroy_si(all); vsip_vdestroy_si(view); vsip_blockdestroy_si(block); } return; } <file_sep>// // Vector.swift // vsip // // Created by <NAME> on 4/22/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import vsip public class Vector : View { fileprivate var tryVsip: OpaquePointer? = nil public var vsip: OpaquePointer { get { return tryVsip! } } // vector bind private func vBind(_ offset : Int, stride : Int, length : Int) -> OpaquePointer? { let blk = self.block.vsip let t = self.block.type switch t { case .f: return vsip_vbind_f(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .d: return vsip_vbind_d(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .cf: return vsip_cvbind_f(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .cd: return vsip_cvbind_d(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .i: return vsip_vbind_i(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .li: return vsip_vbind_li(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .si: return vsip_vbind_si(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .uc: return vsip_vbind_uc(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .vi: return vsip_vbind_vi(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .mi: return vsip_vbind_mi(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) case .bl: return vsip_vbind_bl(blk, vsip_offset(offset), vsip_stride(stride), vsip_length(length)) } } public init(block: Block, offset: Int, stride: Int, length: Int){ super.init(block: block, shape: .v) if let v = self.vBind(offset, stride: stride, length: length){ self.tryVsip = v } else { preconditionFailure("Failed to bind to a vsip vector") } } // vector create public convenience init(length : Int, type : Block.Types){ let blk = Block(length: length, type: type) self.init(block: blk, offset: 0, stride: 1, length: length) } // create view to hold derived subview public init(block: Block, cView: OpaquePointer){ super.init(block: block, shape: .v) self.tryVsip = cView } deinit{ let t = self.block.type let id = self.myId.int32Value switch t { case .f: vsip_vdestroy_f(self.vsip) if _isDebugAssertConfiguration(){ print("vdestroy_f id \(id)") } case .d: vsip_vdestroy_d(self.vsip) if _isDebugAssertConfiguration(){ print("vdestroy_d id \(id)") } case .cf: vsip_cvdestroy_f(self.vsip) if _isDebugAssertConfiguration(){ print("cvdestroy_f id \(id)") } case .cd: vsip_cvdestroy_d(self.vsip) if _isDebugAssertConfiguration(){ print("cvdestroy_d id \(id)") } case .i: vsip_vdestroy_i(self.vsip) if _isDebugAssertConfiguration(){ print("vdestroy_i id \(id)") } case .li: vsip_vdestroy_li(self.vsip) if _isDebugAssertConfiguration(){ print("vdestroy_li id \(id)") } case .si: vsip_vdestroy_si(self.vsip) if _isDebugAssertConfiguration(){ print("vdestroy_si id \(id)") } case .uc: vsip_vdestroy_uc(self.vsip) if _isDebugAssertConfiguration(){ print("vdestroy_uc id \(id)") } case .vi: vsip_vdestroy_vi(self.vsip) if _isDebugAssertConfiguration(){ print("vdestroy_vi id \(id)") } case .mi: vsip_vdestroy_mi(self.vsip) if _isDebugAssertConfiguration(){ print("vdestroy_mi id \(id)") } case .bl: vsip_vdestroy_bl(self.vsip) if _isDebugAssertConfiguration(){ print("vdestroy_bl id \(id)") } } } // MARK: Attributes public var offset: Int { get{ switch self.type { case .f : return Int(vsip_vgetoffset_f(self.vsip)) case .d : return Int(vsip_vgetoffset_d(self.vsip)) case .cf : return Int(vsip_cvgetoffset_f(self.vsip)) case .cd : return Int(vsip_cvgetoffset_d(self.vsip)) case .si : return Int(vsip_vgetoffset_si(self.vsip)) case .i : return Int(vsip_vgetoffset_i(self.vsip)) case .li : return Int(vsip_vgetoffset_li(self.vsip)) case .uc : return Int(vsip_vgetoffset_uc(self.vsip)) case .vi : return Int(vsip_vgetoffset_vi(self.vsip)) case .mi : return Int(vsip_vgetoffset_mi(self.vsip)) case .bl : return Int(vsip_vgetoffset_bl(self.vsip)) } } set(offset){ switch self.type { case .f : vsip_vputoffset_f(self.vsip, vsip_offset(offset)) case .d : vsip_vputoffset_d(self.vsip, vsip_offset(offset)) case .cf : vsip_cvputoffset_f(self.vsip, vsip_offset(offset)) case .cd : vsip_cvputoffset_d(self.vsip, vsip_offset(offset)) case .si : vsip_vputoffset_si(self.vsip, vsip_offset(offset)) case .i : vsip_vputoffset_i(self.vsip, vsip_offset(offset)) case .li : vsip_vputoffset_li(self.vsip, vsip_offset(offset)) case .uc : vsip_vputoffset_uc(self.vsip, vsip_offset(offset)) case .mi : vsip_vputoffset_mi(self.vsip, vsip_offset(offset)) case .vi : vsip_vputoffset_vi(self.vsip, vsip_offset(offset)) case .bl : vsip_vputoffset_bl(self.vsip, vsip_offset(offset)) } } } public var stride: Int { get{ switch self.type { case .f : return Int(vsip_vgetstride_f(self.vsip)) case .d : return Int(vsip_vgetstride_d(self.vsip)) case .cf : return Int(vsip_cvgetstride_f(self.vsip)) case .cd : return Int(vsip_cvgetstride_d(self.vsip)) case .si : return Int(vsip_vgetstride_si(self.vsip)) case .i : return Int(vsip_vgetstride_i(self.vsip)) case .li : return Int(vsip_vgetstride_li(self.vsip)) case .uc : return Int(vsip_vgetstride_uc(self.vsip)) case .vi : return Int(vsip_vgetstride_vi(self.vsip)) case .mi : return Int(vsip_vgetstride_mi(self.vsip)) case .bl : return Int(vsip_vgetstride_bl(self.vsip)) } } set(stride){ switch self.type { case .f : vsip_vputstride_f(self.vsip, vsip_stride(stride)) case .d : vsip_vputstride_d(self.vsip, vsip_stride(stride)) case .cf : vsip_cvputstride_f(self.vsip, vsip_stride(stride)) case .cd : vsip_cvputstride_d(self.vsip, vsip_stride(stride)) case .si : vsip_vputstride_si(self.vsip, vsip_stride(stride)) case .i : vsip_vputstride_i(self.vsip, vsip_stride(stride)) case .li : vsip_vputstride_li(self.vsip, vsip_stride(stride)) case .uc : vsip_vputstride_uc(self.vsip, vsip_stride(stride)) case .mi : vsip_vputstride_mi(self.vsip, vsip_stride(stride)) case .vi : vsip_vputstride_vi(self.vsip, vsip_stride(stride)) case .bl : vsip_vputstride_bl(self.vsip, vsip_stride(stride)) } } } public var length: Int { get{ switch self.type { case .f : return Int(vsip_vgetlength_f(self.vsip)) case .d : return Int(vsip_vgetlength_d(self.vsip)) case .cf : return Int(vsip_cvgetlength_f(self.vsip)) case .cd : return Int(vsip_cvgetlength_d(self.vsip)) case .si : return Int(vsip_vgetlength_si(self.vsip)) case .i : return Int(vsip_vgetlength_i(self.vsip)) case .li : return Int(vsip_vgetlength_li(self.vsip)) case .uc : return Int(vsip_vgetlength_uc(self.vsip)) case .vi : return Int(vsip_vgetlength_vi(self.vsip)) case .mi : return Int(vsip_vgetlength_mi(self.vsip)) case .bl : return Int(vsip_vgetlength_bl(self.vsip)) } } set(length){ switch self.type { case .f : vsip_vputlength_f(self.vsip, vsip_length(length)) case .d : vsip_vputlength_d(self.vsip, vsip_length(length)) case .cf : vsip_cvputlength_f(self.vsip, vsip_length(length)) case .cd : vsip_cvputlength_d(self.vsip, vsip_length(length)) case .si : vsip_vputlength_si(self.vsip, vsip_length(length)) case .i : vsip_vputlength_i(self.vsip, vsip_length(length)) case .li : vsip_vputlength_li(self.vsip, vsip_length(length)) case .uc : vsip_vputlength_uc(self.vsip, vsip_length(length)) case .mi : vsip_vputlength_mi(self.vsip, vsip_length(length)) case .vi : vsip_vputlength_vi(self.vsip, vsip_length(length)) case .bl : vsip_vputlength_bl(self.vsip, vsip_length(length)) } } } // MARK: sub views public var real: Vector{ get{ let ans = super.real(self.vsip) // C VSIP real view let blk = ans.0 let v = ans.1 return Vector(block: blk, cView: v) } } public var imag: Vector{ get{ let ans = super.imag(self.vsip) // C VSIP imag view let blk = ans.0! let v = ans.1! return Vector(block: blk, cView: v) } } // vector subscript operator public subscript(index: Int) -> (Block.Types?, NSNumber?, NSNumber?) { get{ return super.get(self.vsip, index: vsip_index(index)) } set(value){ super.put(self.vsip, index: vsip_index(index), value: value) } } public subscript() -> (Block.Types?, NSNumber?, NSNumber?){ get{ return self[0] } set(value){ self.fill(value) } } // MARK: data generators public func ramp(_ start : NSNumber, increment : NSNumber) -> Vector { switch self.type { case .d: vsip_vramp_d(start.doubleValue, increment.doubleValue, self.vsip) case .f: vsip_vramp_f(start.floatValue, increment.floatValue, self.vsip) case .i: vsip_vramp_i(start.int32Value, increment.int32Value, self.vsip) case .si: vsip_vramp_si(start.int16Value, increment.int16Value, self.vsip) case .uc: vsip_vramp_uc(start.uint8Value, increment.uint8Value, self.vsip) case .vi: vsip_vramp_vi(start.uintValue, increment.uintValue, self.vsip) default: print("Type " + self.type.rawValue + " not supported for ramp") } return self } public func ramp(_ start : Double, increment : Double) -> Vector { let s = NSNumber( value: start) let i = NSNumber( value: increment) return ramp(s, increment: i) } public func ramp(_ start : Float, increment : Float) -> Vector { let s = NSNumber( value: start) let i = NSNumber( value: increment) return ramp(s, increment: i) } public func ramp(_ start : Int, increment : Int) -> Vector { let s = NSNumber( value: start) let i = NSNumber( value: increment) return ramp(s, increment: i) } public func ramp(_ start : UInt, increment : UInt) -> Vector { let s = NSNumber( value: start) let i = NSNumber( value: increment) return ramp(s, increment: i) } public func ramp(_ start : vsip_scalar_si, increment : vsip_scalar_si) -> Vector { let s = NSNumber( value: start) let i = NSNumber( value: increment) return ramp(s, increment: i) } public func ramp(_ start : UInt8, increment : UInt8) -> Vector { let s = NSNumber( value: start) let i = NSNumber( value: increment) return ramp(s, increment: i) } public func fill(_ value: (Block.Types?, NSNumber?, NSNumber?)){ switch self.type{ case .d: vsip_vfill_d(value.1!.doubleValue,self.vsip) case .f: vsip_vfill_f(value.1!.floatValue,self.vsip) case .cd: vsip_cvfill_d(vsip_cmplx_d(value.1!.doubleValue,value.2!.doubleValue),self.vsip) case .cf: vsip_cvfill_f(vsip_cmplx_f(value.1!.floatValue,value.2!.floatValue),self.vsip) case .vi: vsip_vfill_vi(value.1!.uintValue,self.vsip) case .i: vsip_vfill_i(value.1!.int32Value,self.vsip) case .li: vsip_vfill_li(value.1!.intValue,self.vsip) case .si: vsip_vfill_si(value.1!.int16Value,self.vsip) case .uc: vsip_vfill_uc(value.1!.uint8Value,self.vsip) default: break } } public func fill(_ value: Vsip.Scalar){ switch self.type{ case .d: vsip_vfill_d(value.vsip_d,self.vsip) case .f: vsip_vfill_f(value.vsip_f,self.vsip) case .cd: vsip_cvfill_d(value.vsip_cd,self.vsip) case .cf: vsip_cvfill_f(value.vsip_cf,self.vsip) case .vi: vsip_vfill_vi(value.vsip_vi,self.vsip) case .i: vsip_vfill_i(value.vsip_i,self.vsip) case .li: vsip_vfill_li(value.vsip_li,self.vsip) case .si: vsip_vfill_si(value.vsip_si,self.vsip) case .uc: vsip_vfill_uc(value.vsip_uc,self.vsip) default: break } } public func fill(_ value: NSNumber){ switch self.type{ case .d: vsip_vfill_d(value.doubleValue,self.vsip) case .f: vsip_vfill_f(value.floatValue,self.vsip) case .cd: vsip_cvfill_d(vsip_cmplx_d(value.doubleValue,0.0),self.vsip) case .cf: vsip_cvfill_f(vsip_cmplx_f(value.floatValue,0.0),self.vsip) case .vi: vsip_vfill_vi(value.uintValue,self.vsip) case .i: vsip_vfill_i(value.int32Value,self.vsip) case .li: vsip_vfill_li(value.intValue,self.vsip) case .si: vsip_vfill_si(value.int16Value,self.vsip) case .uc: vsip_vfill_uc(value.uint8Value,self.vsip) default: break } } public func fill(_ value: vsip_cscalar_d){ self.fill((Block.Types.cd, NSNumber(value: value.r), NSNumber(value: value.i))) } public func fill(_ value: vsip_cscalar_f){ self.fill((Block.Types.cd, NSNumber(value: value.r), NSNumber(value: value.i))) } public func randn(_ seed: vsip_index, portable: Bool) -> Vector { let state = Vsip.Rand(seed: seed, portable: portable) state.randn(self) return self } public func randn(_ seed: vsip_index) -> Vector { return self.randn(seed, portable: true) } public func randu(_ seed: vsip_index, portable: Bool) -> Vector{ let state = Vsip.Rand(seed: seed, portable: portable) state.randu(self) return self } public func randu(_ seed: vsip_index) -> Vector { return self.randu(seed, portable: true) } // create empty vector of same type and view size. New data space created public var empty: Vector { return Vector(length: self.length, type: self.type) } public func empty(_ type: Block.Types) -> Vector { return Vector(length: self.length, type: type) } public var copy: Vector { let view = self.empty switch view.type{ case .f: vsip_vcopy_f_f(self.vsip,view.vsip) case .d: vsip_vcopy_d_d(self.vsip, view.vsip) case .cf: vsip_cvcopy_f_f(self.vsip,view.vsip) case .cd: vsip_cvcopy_d_d(self.vsip, view.vsip) case .i: vsip_vcopy_i_i(self.vsip,view.vsip) case .si: vsip_vcopy_si_si(self.vsip, view.vsip) case .vi: vsip_vcopy_vi_vi(self.vsip,view.vsip) case .mi: vsip_vcopy_mi_mi(self.vsip, view.vsip) default: break } return view } public func copy(_ output: Vector) -> Vector{ let t = (self.type, output.type) switch t{ case (.f,.f): vsip_vcopy_f_f(self.vsip,output.vsip) case (.f,.cf): let r = output.real;let i = output.real vsip_vcopy_f_f(self.vsip,r.vsip) vsip_vfill_f(0.0,i.vsip) case (.d,.d): vsip_vcopy_d_d(self.vsip,output.vsip) case (.d,.cd): let r = output.real;let i = output.real vsip_vcopy_d_d(self.vsip,r.vsip) vsip_vfill_d(0.0,i.vsip) case (.d,.f): vsip_vcopy_d_f(self.vsip,output.vsip) case (.f,.d): vsip_vcopy_f_d(self.vsip,output.vsip) case (.i,.f): vsip_vcopy_i_f(self.vsip,output.vsip) case (.i,.d): vsip_vcopy_i_d(self.vsip, output.vsip) case (.i,.i): vsip_vcopy_i_i(self.vsip, output.vsip) case (.i,.uc): vsip_vcopy_i_uc(self.vsip, output.vsip) case (.i,.vi): vsip_vcopy_i_vi(self.vsip, output.vsip) case (.si, .si): vsip_vcopy_si_si(self.vsip, output.vsip) case (.si, .d): vsip_vcopy_si_d(self.vsip, output.vsip) case (.si, .f): vsip_vcopy_si_f(self.vsip, output.vsip) case (.vi,.vi): vsip_vcopy_vi_vi(self.vsip, output.vsip) case (.vi, .i): vsip_vcopy_vi_i(self.vsip, output.vsip) case (.vi,.d): vsip_vcopy_vi_d(self.vsip, output.vsip) default: break } return output } public var clone: Vector? { return Vector(block: self.block, offset: self.offset, stride: self.stride, length: self.length) } // MARK: Print public func mString(_ format: String) -> String { let fmt = formatFmt(format) var retval = "" let n = self.length - 1 for i in 0...n{ retval += (i == 0) ? "[" : " " retval += super.scalarString(fmt, value: self[i]) retval += (i == n) ? "]\n" : ";\n" } return retval } public func mPrint(_ format: String){ let m = mString(format) print(m) } // MARK: Elementary Functions public func acos(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vacos_d(self.vsip, out.vsip) case .f: vsip_vacos_f(self.vsip, out.vsip) default: return out } return out } public func asin(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vasin_d(self.vsip, out.vsip) case .f: vsip_vasin_f(self.vsip, out.vsip) default: return out } return out } public func atan(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vatan_d(self.vsip, out.vsip) case .f: vsip_vatan_f(self.vsip, out.vsip) default: return out } return out } public func cos(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vcos_d(self.vsip, out.vsip) case .f: vsip_vcos_f(self.vsip, out.vsip) default: return out } return out } public func sin(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vasin_d(self.vsip, out.vsip) case .f: vsip_vasin_f(self.vsip, out.vsip) default: return out } return out } public func tan(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vtan_d(self.vsip, out.vsip) case .f: vsip_vtan_f(self.vsip, out.vsip) default: return out } return out } public func exp(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vexp_d(self.vsip, out.vsip) case .f: vsip_vexp_f(self.vsip, out.vsip) default: return out } return out } public func exp10(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vexp10_d(self.vsip, out.vsip) case .f: vsip_vexp10_f(self.vsip, out.vsip) default: return out } return out } public func log(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vlog_d(self.vsip, out.vsip) case .f: vsip_vlog_f(self.vsip, out.vsip) default: return out } return out } public func log10(_ out: Vector) -> Vector { switch self.type{ case .d: vsip_vlog10_d(self.vsip, out.vsip) case .f: vsip_vlog10_f(self.vsip, out.vsip) default: return out } return out } // MARK: Binary Functions public func add(_ to: Vector, resultIn: Vector) -> Vector{ switch self.type{ case .f: vsip_vadd_f(self.vsip, to.vsip, resultIn.vsip) case .d: vsip_vadd_d(self.vsip, to.vsip, resultIn.vsip) case .cf: vsip_cvadd_f(self.vsip, to.vsip, resultIn.vsip) case .cd: vsip_cvadd_d(self.vsip, to.vsip, resultIn.vsip) case .si: vsip_vadd_si(self.vsip, to.vsip, resultIn.vsip) case .i: vsip_vadd_i(self.vsip, to.vsip, resultIn.vsip) case .li: vsip_vadd_li(self.vsip, to.vsip, resultIn.vsip) case .uc: vsip_vadd_uc(self.vsip, to.vsip, resultIn.vsip) case .vi: vsip_vadd_vi(self.vsip, to.vsip, resultIn.vsip) default: break } return resultIn } public func sub(_ from: Vector, resultIn: Vector) -> Vector{ switch self.type{ case .f: vsip_vsub_f(self.vsip, from.vsip, resultIn.vsip) case .d: vsip_vadd_d(self.vsip, from.vsip, resultIn.vsip) case .cf: vsip_cvsub_f(self.vsip, from.vsip, resultIn.vsip) case .cd: vsip_cvsub_d(self.vsip, from.vsip, resultIn.vsip) case .si: vsip_vsub_si(self.vsip, from.vsip, resultIn.vsip) case .i: vsip_vsub_i(self.vsip, from.vsip, resultIn.vsip) case .uc: vsip_vsub_uc(self.vsip, from.vsip, resultIn.vsip) default: break } return resultIn } } <file_sep>#ifndef _TS_H #define _TS_H 1 #include<vsip.h> #include"param.h" /* * fir => FIR is a low pass filter for the noise. * noise => is a vector to hold the output of the random generator. * bl_noise => holds the output of the bandlimited noise after the * FIR filter. * rand => random object holding the state of the generator. * t => is a vector of times coresponding to the sensor * samples in a time series. * t_dt => is a vector of times with the delay time corresponding * to a propagation time given a particular noise direction * added to t. t_dt = t + Dsens/c * cos(bearing); * m_data => the matrix holding the input data * v_data => a vector allocated on the same block as m_data for * use for vector views of m_data */ typedef struct { double Fs; double c; double Dsens; int Nsens; int Nsim_noise; int Nsim_freqs; int Nts; vsip_fir_f *fir; vsip_vview_f *noise; vsip_vview_f *bl_noise; vsip_randstate *rand; vsip_vview_f *t; vsip_vview_f *t_dt; vsip_mview_f *m_data; vsip_vview_f *v_data; double *freqs; double *bearings; } ts_obj; int ts_init(ts_obj*, param_obj*); void ts_fin(ts_obj*); vsip_mview_f* ts_instance(ts_obj*); void ts_zero(ts_obj*); void ts_sim_nb(ts_obj*); void ts_sim_noise(ts_obj*); #endif /* _TS_H */ <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mviewattributes_li.h,v 2.0 2003/02/22 15:48:15 judd Exp $ */ #ifndef _vsip_mviewattributes_li_h #define _vsip_mviewattributes_li_h 1 #include"vsip.h" #include"VI.h" #include"vsip_blockattributes_li.h" struct vsip_mviewattributes_li{ vsip_block_li* block; vsip_offset offset; vsip_stride row_stride; vsip_length row_length; vsip_stride col_stride; vsip_length col_length; int markings; /* to indicate valid object */ }; #endif /* _vsip_mviewattributes_li_h */ <file_sep>// // JVSIP.swift // SJVsip // // Created by <NAME> on 11/4/17. // Copyright © 2017 JVSIP. All rights reserved. // /** An instance of JVSIP class is stored in every VSIP object. The first time it is called it will call vsip_init When the garbage collector has collected the last one vsip_finalize is called The reference count is kept as a class variable */ import Foundation import vsip public class JVSIP { static var vsipInit : UInt = 0 static var num = NSNumber(value: 0 as Int32) var myId: NSNumber func initInc() { JVSIP.vsipInit += 1; } func initDec() { JVSIP.vsipInit -= 1; } func vsipInitGTzero() -> Bool{ if JVSIP.vsipInit > 0{ return true } else { return false } } func vsipInitEQzero() -> Bool{ if JVSIP.vsipInit == 0{ return true } else { return false } } init() { self.myId = JVSIP.num if self.vsipInitGTzero(){ self.initInc() } else { let jInit = vsip_init(nil) if jInit != 0 { print("vsip_init failed; returned \(jInit)") } /* if _isDebugAssertConfiguration(){ print("called vsip_init") }*/ self.initInc() } let n = JVSIP.num.int32Value + 1 JVSIP.num = NSNumber(value: n as Int32) self.myId = JVSIP.num /* if _isDebugAssertConfiguration(){ print("called jinit id \(self.myId)") }*/ } deinit{ self.initDec() if self.vsipInitEQzero(){ vsip_finalize(nil) /* if _isDebugAssertConfiguration(){ print("called vsip_finalize") }*/ } } } <file_sep>// // extensionBlocks.swift // SJVsip // // Created by <NAME> on 11/4/17. // Copyright © 2017 JVSIP. All rights reserved. // import Foundation // Return JVSIP Swift View object. Allows block.bind for shape vector extension Block { public func bind(offset : Int, stride : Int, length : Int) -> Vector { return Vector(block: self, offset: offset, stride: stride, length: length) } // Return JVSIP Swift View object. Allows block.bind for shape matrix public func bind(offset : Int, columnStride : Int, columnLength : Int, rowStride : Int, rowLength : Int) -> Matrix { return Matrix(block: self, offset: offset, columnStride: columnStride, columnLength: columnLength, rowStride: rowStride, rowLength: rowLength) } public func vector() -> Vector{ return self.bind(offset: 0, stride: 1, length: self.length) } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mtanh_d.h,v 2.0 2003/02/22 15:23:26 judd Exp $ */ #include"VU_mprintm_d.include" static void mtanh_d(void){ printf("\n*******\nTEST mtanh_d\n\n"); { vsip_scalar_d data[] = {0, .1, .2, .4, .8, 1.6}; vsip_scalar_d ans[] = {0, .0997, .1974, .3799,.6640,.9217}; vsip_block_d *block = vsip_blockbind_d(data,6,VSIP_MEM_NONE); vsip_block_d *ans_block = vsip_blockbind_d(ans,6,VSIP_MEM_NONE); vsip_mview_d *a = vsip_mbind_d(block,0,1,2,2,3); vsip_mview_d *ansv = vsip_mbind_d(ans_block,0,1,2,2,3); vsip_mview_d *b = vsip_mcreate_d(2,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *chk = vsip_mcreate_d(2,3,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_d(block,VSIP_TRUE); vsip_blockadmit_d(ans_block,VSIP_TRUE); printf("vsip_mtanh_d(a,b)\n"); vsip_mtanh_d(a,b); printf("matrix a\n");VU_mprintm_d("8.6",a); printf("matrix b\n");VU_mprintm_d("8.6",b); printf("right answer \n");VU_mprintm_d("8.4",ansv); vsip_msub_d(b,ansv,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); printf("inplace\n"); vsip_mtanh_d(a,a); vsip_msub_d(a,ansv,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_d(a); vsip_malldestroy_d(b); vsip_malldestroy_d(chk); vsip_malldestroy_d(ansv); } return; } <file_sep>/* Created RJudd August 28, 1999 */ /* SPAWARSYSCEN D881 */ /* private attributes for real qrd */ #ifndef _vsip_cqrddattributes_d_h #define _vsip_cqrdattributes_d_h 1 #include"vsip_cmviewattributes_d.h" #include"vsip_cvviewattributes_d.h" #include"vsip_mviewattributes_d.h" #include"vsip_vviewattributes_d.h" #include"VI.h" struct vsip_cqrdattributes_d{ vsip_qrd_qopt qopt; vsip_length M; vsip_length N; vsip_cmview_d *A; vsip_cmview_d AA; vsip_cvview_d *v; vsip_cvview_d *w; vsip_cvview_d *cI; vsip_scalar_d *beta; }; #endif /*_vsip_cqrdattributes_d_h */ <file_sep>import pyJvsip as pv import numpy as np import matplotlib.pyplot as plt def view_read(fname): from pyJvsip import create as create fd=open(fname,'r') t=fd.readline().split()[0] assert t in ['vview_f','mview_f','vview_d','mview_d'], 'Type <:%s:> not supported'%t if 'mview' in t: sz=fd.readline().split() M=pv.create(t,int(sz[0]),int(sz[1])) for lin in fd: a=lin.split() r=int(a[0]);c=int(a[1]);x=float(a[2]) M[r,c]=x else: sz=fd.readline().split() M=create(t,int(sz)) for lin in fd: a=lin.split() i=int(a[0]);x=float(a[2]) M[i]=x fd.close() return M gram = view_read('gram_output') fig = plt.figure() ax = fig.add_subplot(111) plt.imshow(gram.list,origin='lower') ax.set_yticks([0,31,63,95,127]) ax.set_xticks([0,51,103,154,206,256]) ax.set_yticklabels([r'$-\kappa$','$-\kappa /2$','$0$','$\kappa /2$','$\kappa$']) ax.set_xticklabels([' 0 ','100','200','300','400','500']) ax.set_title(r'$\vec{\kappa}\omega$ plot') ax.set_xlabel('Frequency (Hz)') ax.set_ylabel(r'$\kappa \cdot \cos(\theta)$') plt.show() <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_stride_d.h,v 2.1 2007/04/18 17:05:56 judd Exp $ */ static void get_put_stride_d(void){ printf("********\nTEST get_put_stride_d\n"); { vsip_offset ivo = 3, icvo=10; vsip_stride ivs = 2, icvs=-1; vsip_length ivl = 3, icvl=4; vsip_stride jvs = 3, jcvs=1; vsip_stride irs = 1, ics = 3; vsip_length irl = 2, icl = 3; vsip_stride jrs = 5, jcs = 2; vsip_stride ixs = 2, iys = 4, izs = 14; vsip_length ixl = 2, iyl = 3, izl = 4; vsip_stride jxs = 4, jys = 14, jzs = 2; vsip_block_d *b = vsip_blockcreate_d(80,VSIP_MEM_NONE); vsip_cblock_d *cb = vsip_cblockcreate_d(80,VSIP_MEM_NONE); vsip_vview_d *v = vsip_vbind_d(b,ivo,ivs,ivl); vsip_mview_d *m = vsip_mbind_d(b,ivo,ics,icl,irs,irl); vsip_tview_d *t = vsip_tbind_d(b,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_cvview_d *cv = vsip_cvbind_d(cb,icvo,icvs,icvl); vsip_cmview_d *cm = vsip_cmbind_d(cb,ivo,ics,icl,irs,irl); vsip_ctview_d *ct = vsip_ctbind_d(cb,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_stride s; printf("test vgetstride_d\n"); fflush(stdout); { s = vsip_vgetstride_d(v); (s == ivs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputstride_d\n"); fflush(stdout); { vsip_vputstride_d(v,jvs); s = vsip_vgetstride_d(v); (s == jvs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test cvgetstride_d\n"); fflush(stdout); { s = vsip_cvgetstride_d(cv); (s == icvs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputstride_d\n"); fflush(stdout); { vsip_cvputstride_d(cv,jcvs); s = vsip_cvgetstride_d(cv); (s == jcvs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /*************************************************************************/ printf("test mgetrowstride_d\n"); fflush(stdout); { s = vsip_mgetrowstride_d(m); (s == irs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputrowstride_d\n"); fflush(stdout); { vsip_mputrowstride_d(m,jrs); s = vsip_mgetrowstride_d(m); (s == jrs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test mgetcolstride_d\n"); fflush(stdout); { s = vsip_mgetcolstride_d(m); (s == ics) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputcolstride_d\n"); fflush(stdout); { vsip_mputcolstride_d(m,jcs); s = vsip_mgetcolstride_d(m); (s == jcs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test cmgetrowstride_d\n"); fflush(stdout); { s = vsip_cmgetrowstride_d(cm); (s == irs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test cmputrowstride_d\n"); fflush(stdout); { vsip_cmputrowstride_d(cm,jrs); s = vsip_cmgetrowstride_d(cm); (s == jrs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test cmgetcolstride_d\n"); fflush(stdout); { s = vsip_cmgetcolstride_d(cm); (s == ics) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test cmputcolstride_d\n"); fflush(stdout); { vsip_cmputcolstride_d(cm,jcs); s = vsip_cmgetcolstride_d(cm); (s == jcs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /*************************************************************************/ printf("test tgetxstride_d\n"); fflush(stdout); { s = vsip_tgetxstride_d(t); (s == ixs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputxstride_d\n"); fflush(stdout); { vsip_tputxstride_d(t,jxs); s = vsip_tgetxstride_d(t); (s == jxs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test ctgetxstride_d\n"); fflush(stdout); { s = vsip_ctgetxstride_d(ct); (s == ixs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test ctputxstride_d\n"); fflush(stdout); { vsip_ctputxstride_d(ct,jxs); s = vsip_ctgetxstride_d(ct); (s == jxs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test tgetystride_d\n"); fflush(stdout); { s = vsip_tgetystride_d(t); (s == iys) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputystride_d\n"); fflush(stdout); { vsip_tputystride_d(t,jys); s = vsip_tgetystride_d(t); (s == jys) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test ctgetystride_d\n"); fflush(stdout); { s = vsip_ctgetystride_d(ct); (s == iys) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test ctputystride_d\n"); fflush(stdout); { vsip_ctputystride_d(ct,jys); s = vsip_ctgetystride_d(ct); (s == jys) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test tgetzstride_d\n"); fflush(stdout); { s = vsip_tgetzstride_d(t); (s == izs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputzstride_d\n"); fflush(stdout); { vsip_tputzstride_d(t,jzs); s = vsip_tgetzstride_d(t); (s == jzs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test ctgetzstride_d\n"); fflush(stdout); { s = vsip_ctgetzstride_d(ct); (s == izs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test ctputzstride_d\n"); fflush(stdout); { vsip_ctputzstride_d(ct,jzs); s = vsip_ctgetzstride_d(ct); (s == jzs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } vsip_vdestroy_d(v); vsip_mdestroy_d(m); vsip_talldestroy_d(t); vsip_cvdestroy_d(cv); vsip_cmdestroy_d(cm); vsip_ctalldestroy_d(ct); } return; } <file_sep>/* Created RJudd September 17, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cblockfind_f.c,v 2.0 2003/02/22 15:18:38 judd Exp $ */ #include"vsip.h" #include"vsip_cblockattributes_f.h" void (vsip_cblockfind_f)( const vsip_cblock_f* b, vsip_scalar_f* *Rp, vsip_scalar_f* *Ip) { #if defined(VSIP_DEFAULT_SPLIT) #include"VI_cblockfind_f_ds.h" #elif defined(VSIP_ALWAYS_SPLIT) #include"VI_cblockfind_f_as.h" #elif defined(VSIP_ALWAYS_INTERLEAVED) #include"VI_cblockfind_f_ai.h" #else #include"VI_cblockfind_f_di.h" #endif return; } <file_sep>/* Created RJudd September 16, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cblockbind_f.c,v 2.2 2009/05/20 17:11:15 judd Exp $ */ #include"vsip.h" #include"vsip_cblockattributes_f.h" #include"vsip_blockattributes_f.h" vsip_cblock_f* (vsip_cblockbind_f)( vsip_scalar_f* const Rp, vsip_scalar_f* const Ip, vsip_length N, vsip_memory_hint h) { vsip_cblock_f* b = (vsip_cblock_f*)malloc(sizeof(vsip_cblock_f)); if(b != (vsip_cblock_f*)NULL) b->hint = h; #if defined(VSIP_DEFAULT_SPLIT) #include"VI_cblockbind_f_ds.h" #elif defined(VSIP_ALWAYS_SPLIT) #include"VI_cblockbind_f_as.h" #elif defined(VSIP_ALWAYS_INTERLEAVED) #include"VI_cblockbind_f_ai.h" #else #include"VI_cblockbind_f_di.h" #endif return b; } <file_sep>/* Created RJudd */ /* */ #include"VU_cvprintm_d.include" static void cvfreqswap_d(void){ printf("*********\nTEST vfreqswap_d\n"); { vsip_length M=8,N=9; vsip_cvview_d *even = vsip_cvcreate_d(M,VSIP_MEM_NONE); vsip_cvview_d *ans_even=vsip_cvcreate_d(M,VSIP_MEM_NONE); vsip_vview_d *v; vsip_cvview_d *odd = vsip_cvcreate_d(N,VSIP_MEM_NONE); vsip_cvview_d *ans_odd=vsip_cvcreate_d(N,VSIP_MEM_NONE); vsip_scalar_d even_ans_r[] = {4, 5, 6, 7, 0, 1, 2, 3}; vsip_scalar_d even_ans_i[]={-4, -5, -6, -7, -0, -1, -2, -3}; vsip_scalar_d odd_ans_r[] = {4, 5, 6, 7, 8, 0, 1, 2, 3}; vsip_scalar_d odd_ans_i[]={-4,-5,-6,-7,-8,0,-1,-2,-3}; vsip_cvcopyfrom_user_d(even_ans_r,even_ans_i, ans_even); vsip_cvcopyfrom_user_d(odd_ans_r,odd_ans_i, ans_odd); v=vsip_vrealview_d(even);vsip_vramp_d(0,1,v);vsip_vdestroy_d(v); v=vsip_vimagview_d(even);vsip_vramp_d(0,-1,v);vsip_vdestroy_d(v); v=vsip_vrealview_d(odd);vsip_vramp_d(0,1,v);vsip_vdestroy_d(v); v=vsip_vimagview_d(odd);vsip_vramp_d(0,-1,v);vsip_vdestroy_d(v); printf("INPUT even\n");VU_cvprintm_d("2.1",even); vsip_cvfreqswap_d(even); printf("For even expect\n");VU_cvprintm_d("2.1",ans_even); printf("for even result\n");VU_cvprintm_d("2.1",even); { vsip_cvsub_d(even,ans_even,ans_even); if(vsip_vcmaxmgsqval_d(ans_even,NULL) > .00001){ printf("error\n"); }else{ printf("correct\n"); } } printf("INPUT odd\n");VU_cvprintm_d("2.1",odd); vsip_cvfreqswap_d(odd); printf("For odd expect\n");VU_cvprintm_d("2.1",ans_odd); printf("for odd result\n");VU_cvprintm_d("2.1",odd); { vsip_cvsub_d(odd,ans_odd,ans_odd); if(vsip_vcmaxmgsqval_d(ans_odd,NULL) > .00001){ printf("error\n"); }else{ printf("correct\n"); } } vsip_cvalldestroy_d(even); vsip_cvalldestroy_d(odd); } } <file_sep># -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <markdowncell> # ## Elementary Math operations using pyJvsip # These are examples of operations defined in the C VSIPL spec in the Vector and Elementwise chapter under Elementary Math Functions. # <codecell> import pyJvsip as pv f='%.3f' # <markdowncell> # We create a vector and put some date into it. Most elementary operations are done as properties if a method is used. Methods are frequently in-place. Use a function for out of place, or a copy of the input vector. # <codecell> try: pi except: from math import pi a=pv.create('vview_d',10).ramp(0,2*pi/10.0) # <markdowncell> # In-Place using method # <codecell> a.mprint(f) a.sin a.mprint(f) # <markdowncell> # out-of-place using method # <codecell> b=a.copy.asin b.mprint(f) a.mprint(f) # <markdowncell> # out-of-place using function call # <codecell> pv.sin(b,a) b.mprint(f) a.mprint(f) # <markdowncell> # in-place using function call # <codecell> pv.sin(b,b) b.mprint(f) # <markdowncell> # All the elementary functions work the same except for atan2 which has three arguments (two input and an output). There is no view method in pyJvsip for atan2, only a function call. <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* new version done August 2000 */ /* $Id: vsip_mprod_d.c,v 2.4 2006/11/27 21:39:41 judd Exp $ */ #include"vsip.h" #include"vsip_mviewattributes_d.h" #define VI_MFILL_D( la, lr) { vsip_length n_mj, n_mn; vsip_stride rst_mj, rst_mn; \ vsip_scalar_d *rpl = (lr->block->array) + lr->offset * lr->block->rstride; \ vsip_scalar_d *rpl0 = rpl; \ if(lr->row_stride < lr->col_stride){ \ n_mj = lr->row_length; n_mn = lr->col_length; rst_mj = lr->row_stride; rst_mn = lr->col_stride; rst_mj *= lr->block->rstride; rst_mn *= lr->block->rstride; \ } else { \ n_mn = lr->row_length; n_mj = lr->col_length; rst_mn = lr->row_stride; rst_mj = lr->col_stride; rst_mn *= lr->block->rstride; rst_mj *= lr->block->rstride; \ } while(n_mn-- > 0){ \ vsip_length n = n_mj; while(n-- >0){ *rpl = la; rpl += rst_mj; } rpl0 += rst_mn; rpl = rpl0; \ } } #define VI_MPROD_jki_D { \ vsip_length outer_loop = r_r_l / 3; vsip_length final_loop = r_r_l % 3; \ for(j=0; j< outer_loop; j++){ \ vsip_index my_j0 = j * 3; vsip_index my_j1 = my_j0 + 1; vsip_index my_j2 = my_j1 + 1; \ for(k=0; k< a_r_l; k++){ \ b0_scalar = bp[k * b_st_c + my_j0 * b_st_r]; \ b1_scalar = bp[k * b_st_c + my_j1 * b_st_r]; \ b2_scalar = bp[k * b_st_c + my_j2 * b_st_r]; \ for(i=0; i<a_c_l; i++){ \ a0_scalar = ap[i * a_st_c + k * a_st_r]; \ rp[my_j0 * r_st_r + i * r_st_c] += a0_scalar * b0_scalar; \ rp[my_j1 * r_st_r + i * r_st_c] += a0_scalar * b1_scalar; \ rp[my_j2 * r_st_r + i * r_st_c] += a0_scalar * b2_scalar; \ } } } if(final_loop){ \ for(j=r_r_l - final_loop; j<r_r_l; j++){ \ for(k=0; k<a_r_l; k++){ \ b0_scalar = bp[k * b_st_c + j * b_st_r]; \ for(i=0; i<a_c_l; i++) rp[j * r_st_r + i * r_st_c] += ap[i * a_st_c + k * a_st_r] * b0_scalar; \ }}}} #define VI_MPROD_ikj_D { \ vsip_length outer_loop = a_c_l/3; vsip_length final_loop = a_c_l % 3;\ for(i=0; i< outer_loop; i++){ \ vsip_index i0 = 3 * i; vsip_index i1 = i0 + 1; vsip_index i2 = i1 + 1;\ for(k=0; k<a_r_l; k++){ \ a0_scalar = ap[i0* a_st_c + k * a_st_r];\ a1_scalar = ap[i1 * a_st_c + k * a_st_r];\ a2_scalar = ap[i2 * a_st_c + k * a_st_r];\ for(j=0; j<r_r_l; j++){\ b0_scalar = bp[k * b_st_c + j * b_st_r];\ rp[i0 * r_st_c + j * r_st_r] += b0_scalar * a0_scalar;\ rp[i1 * r_st_c + j * r_st_r] += b0_scalar * a1_scalar;\ rp[i2 * r_st_c + j * r_st_r] += b0_scalar * a2_scalar;\ }}} if(final_loop) {\ for(i=a_c_l - final_loop; i< a_c_l; i++){\ for(k=0; k<a_r_l; k++){ \ a0_scalar = ap[i* a_st_c + k * a_st_r];\ for(j=0; j<r_r_l; j++){ \ rp[i * r_st_c + j * r_st_r] += bp[k * b_st_c + j * b_st_r] * a0_scalar;\ }}}}} #define VI_MPROD_jik_D { \ vsip_length outer_loop = a_c_l / 3; vsip_length final_loop = a_c_l % 3; \ for(j=0; j<outer_loop; j++){ \ vsip_index my_j0 = 3 * j;vsip_index my_j1 = my_j0 + 1;vsip_index my_j2 = my_j1 + 1; \ for(i=0; i< r_r_l; i++){ \ temp0 = 0.0;temp1 = 0.0;temp2 = 0.0;\ for(k=0; k< a_r_l; k++){\ b0_scalar = bp[i * b_st_r + k * b_st_c];\ temp0 += ap[my_j0 * a_st_c + k * a_st_r] * b0_scalar;\ temp1 += ap[my_j1 * a_st_c + k * a_st_r] * b0_scalar;\ temp2 += ap[my_j2 * a_st_c + k * a_st_r] * b0_scalar;\ }\ rp[my_j0 * r_st_c + i * r_st_r] = temp0;\ rp[my_j1 * r_st_c + i * r_st_r] = temp1;\ rp[my_j2 * r_st_c + i * r_st_r] = temp2;\ }} if(final_loop){ \ for(j=a_c_l - final_loop; j < a_c_l; j++){\ for(i=0; i<r_r_l; i++){\ temp0 = 0;\ for(k=0; k<a_r_l; k++){\ temp0 += ap[j * a_st_c + k * a_st_r] * bp[i * b_st_r + k * b_st_c];\ }\ rp[j * r_st_c + i * r_st_r] = temp0;\ }}}} void (vsip_mprod_d)( const vsip_mview_d* a, const vsip_mview_d* b, const vsip_mview_d* r) { vsip_index i,j,k; /* c => column major, r => row major */ /* decide if ccc => 0 ccr=> 1, crc => 2, etc to rrr => 7 */ unsigned method = (unsigned)(r->row_stride <= r->col_stride) + (unsigned)(b->row_stride <= b->col_stride) * 2 + (unsigned)(a->row_stride <= a->col_stride) * 4; vsip_stride a_st_r = a->row_stride * a->block->rstride, a_st_c = a->col_stride * a->block->rstride, b_st_r = b->row_stride * b->block->rstride, b_st_c = b->col_stride * b->block->rstride, r_st_r = r->row_stride * r->block->rstride, r_st_c = r->col_stride * r->block->rstride; vsip_length a_c_l = a->col_length; /* i_size */ vsip_length r_r_l = r->row_length; /* j_size */ vsip_length a_r_l = a->row_length; /* k_size */ register vsip_scalar_d a0_scalar,a1_scalar, a2_scalar, b0_scalar, b1_scalar, b2_scalar, temp0, temp1, temp2; vsip_scalar_d *ap = (a->block->array) + a->offset * a->block->rstride, *bp = (b->block->array) + b->offset * b->block->rstride, *rp = (r->block->array) + r->offset * r->block->rstride; VI_MFILL_D(0.0,r); switch(method){ case 0 : VI_MPROD_jki_D; /* printf("here ccc ex3\n"); */ break; /* ccc */ case 1 : VI_MPROD_ikj_D; /* printf("here ccr ex3\n"); */ break; /* ccr */ case 2 : VI_MPROD_jki_D; /* printf("here crc ex3\n"); */ break; /* crc */ case 3 : VI_MPROD_ikj_D; /* printf("here crr ex3\n"); */ break; /* crr */ case 4 : VI_MPROD_jik_D; /* printf("here rcc ex3\n"); */ break; /* rcc */ case 5 : VI_MPROD_jik_D; /* printf("here rcr ex3\n"); */ break; /* rcr */ case 6 : VI_MPROD_ikj_D; /* printf("here rrc ex3\n"); */ break; /* rrc */ case 7 : VI_MPROD_ikj_D; /* printf("here rrr ex3\n"); */ /* rrr */ } } <file_sep>/* Created RJudd, Retired */ /* https://github.com/rrjudd/jvsip */ /*********************************************************************** // This code includes no warranty, express or implied, including the / // warranties of merchantability and fitness for a particular purpose./ // No person or entity assumes any legal liability or responsibility / // for the accuracy, completeness, or usefulness of an information / // apparatus, product, or process disclosed, or represents that its / // use would not infringe privately owned rights. / **********************************************************************/ /* jvsip source code may not be defined in the VSIPL specification */ /* Functions I know are not VSIPL defined I will place in the jvsip */ /* name space to prevent inadvertent use. */ #include<vsip.h> #include<vsip_mviewattributes_d.h> #include<vsip_mviewattributes_f.h> #include<vsip_cmviewattributes_d.h> #include<vsip_cmviewattributes_f.h> #include"jvsip.h" void jvsip_mprod2_d( const vsip_mview_d* a, const vsip_mview_d* b, const vsip_mview_d* r) { /* st_r-> row stride, st_c=>col stride */ vsip_stride a_st_r = a->row_stride * a->block->rstride, a_st_c = a->col_stride * a->block->rstride, b_st_r = b->row_stride * b->block->rstride, b_st_c = b->col_stride * b->block->rstride, r_st_r = r->row_stride * r->block->rstride, r_st_c = r->col_stride * r->block->rstride; vsip_index j; vsip_length r_r_l = r->row_length; /* j_size */ vsip_scalar_d *ap = (a->block->array) + a->offset * a->block->rstride, *bp = (b->block->array) + b->offset * b->block->rstride, *rp = (r->block->array) + r->offset * r->block->rstride; vsip_scalar_d *b0p = bp; vsip_scalar_d *b1p = b0p + b_st_c; vsip_scalar_d *r0p = rp; vsip_scalar_d *r1p = r0p + r_st_c; register vsip_scalar_d a00,a01; register vsip_scalar_d a10,a11; a00 = *ap; a01 = *(ap + a_st_r); a10 = *(ap + a_st_c); a11 = *(ap + a_st_c + a_st_r); for( j=0; j<r_r_l; j++){ /* copying b_j into local variables allows in place operation */ register vsip_scalar_d b0 = *b0p, b1 = *b1p; *r0p = a00 * b0 + a01 * b1; *r1p = a10 * b0 + a11 * b1; b0p += b_st_r; b1p += b_st_r; r0p += r_st_r; r1p += r_st_r; } } void jvsip_mprod2_f( const vsip_mview_f* a, const vsip_mview_f* b, const vsip_mview_f* r) { /* st_r-> row stride, st_c=>col stride */ vsip_stride a_st_r = a->row_stride * a->block->rstride, a_st_c = a->col_stride * a->block->rstride, b_st_r = b->row_stride * b->block->rstride, b_st_c = b->col_stride * b->block->rstride, r_st_r = r->row_stride * r->block->rstride, r_st_c = r->col_stride * r->block->rstride; vsip_index j; vsip_length r_r_l = r->row_length; /* j_size */ vsip_scalar_f *ap = (a->block->array) + a->offset * a->block->rstride, *bp = (b->block->array) + b->offset * b->block->rstride, *rp = (r->block->array) + r->offset * r->block->rstride; vsip_scalar_f *b0p = bp; vsip_scalar_f *b1p = b0p + b_st_c; vsip_scalar_f *r0p = rp; vsip_scalar_f *r1p = r0p + r_st_c; register vsip_scalar_f a00,a01; register vsip_scalar_f a10,a11; a00 = *ap; a01 = *(ap + a_st_r); a10 = *(ap + a_st_c); a11 = *(ap + a_st_c + a_st_r); for( j=0; j<r_r_l; j++){ /* copying b_j into local variables allows in place operation */ register vsip_scalar_f b0 = *b0p, b1 = *b1p; *r0p = a00 * b0 + a01 * b1; *r1p = a10 * b0 + a11 * b1; b0p += b_st_r; b1p += b_st_r; r0p += r_st_r; r1p += r_st_r; } } void jvsip_cmprod2_d( const vsip_cmview_d* a, const vsip_cmview_d* b, const vsip_cmview_d* c) { /* st_r => stride row; st_c => stride column */ vsip_stride a_st_r = a->row_stride * a->block->cstride, a_st_c = a->col_stride * a->block->cstride, b_st_r = b->row_stride * b->block->cstride, b_st_c = b->col_stride * b->block->cstride, c_st_r = c->row_stride * c->block->cstride, c_st_c = c->col_stride * c->block->cstride; vsip_length c_r_l = c->row_length; /* j_size */ vsip_scalar_d *ap_r = (a->block->R->array) + a->offset * a->block->cstride, *ap_i = (a->block->I->array) + a->offset * a->block->cstride, *bp_r = (b->block->R->array) + b->offset * b->block->cstride, *bp_i = (b->block->I->array) + b->offset * b->block->cstride, *cp_r = (c->block->R->array) + c->offset * c->block->cstride, *cp_i = (c->block->I->array) + c->offset * c->block->cstride; /* some additional pointers to store initial data */ vsip_scalar_d *ap0_r = ap_r, *ap0_i = ap_i, *bp0_r, *bp0_i, *cp0_r, *cp0_i; register vsip_scalar_d a00_r, a01_r, a00_i, a01_i; register vsip_scalar_d a10_r, a11_r, a10_i, a11_i; /* we need local storage for a column of b */ register vsip_scalar_d b0_r, b1_r; register vsip_scalar_d b0_i, b1_i; vsip_length i; /* need a counter */ /* we copy matrix a to local storage */ a00_r = *ap0_r, a00_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a01_r = *ap0_r, a01_i = *ap0_i; ap0_r = ap_r + a_st_c; ap0_i = ap_i + a_st_c; a10_r = *ap0_r, a10_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a11_r = *ap0_r, a11_i = *ap0_i; for(i=0; i< c_r_l; i++){ /* copy i'th column of b into local */ bp0_r = bp_r + (vsip_stride)i * b_st_r; bp0_i = bp_i + (vsip_stride)i * b_st_r; b0_r = *bp0_r; b0_i = *bp0_i; bp0_r += b_st_c; bp0_i += b_st_c; b1_r = *bp0_r; b1_i = *bp0_i; /* get the pointer to the column where output will go */ cp0_r = cp_r + (vsip_stride)i * c_st_r; cp0_i = cp_i + (vsip_stride)i * c_st_r; /* do the math */ /* the real part */ *cp0_r = (a00_r * b0_r + a01_r * b1_r) - (a00_i * b0_i + a01_i * b1_i ); cp0_r += c_st_c; *cp0_r = (a10_r * b0_r + a11_r * b1_r) - (a10_i * b0_i + a11_i * b1_i ); /* the imaginary part */ *cp0_i = a00_r * b0_i + a01_r * b1_i + a00_i * b0_r + a01_i * b1_r ; cp0_i += c_st_c; *cp0_i = a10_r * b0_i + a11_r * b1_i + a10_i * b0_r + a11_i * b1_r ; } } void jvsip_cmprod2_f( const vsip_cmview_f* a, const vsip_cmview_f* b, const vsip_cmview_f* c) { /* st_r => stride row; st_c => stride column */ vsip_stride a_st_r = a->row_stride * a->block->cstride, a_st_c = a->col_stride * a->block->cstride, b_st_r = b->row_stride * b->block->cstride, b_st_c = b->col_stride * b->block->cstride, c_st_r = c->row_stride * c->block->cstride, c_st_c = c->col_stride * c->block->cstride; vsip_length c_r_l = c->row_length; /* j_size */ vsip_scalar_f *ap_r = (a->block->R->array) + a->offset * a->block->cstride, *ap_i = (a->block->I->array) + a->offset * a->block->cstride, *bp_r = (b->block->R->array) + b->offset * b->block->cstride, *bp_i = (b->block->I->array) + b->offset * b->block->cstride, *cp_r = (c->block->R->array) + c->offset * c->block->cstride, *cp_i = (c->block->I->array) + c->offset * c->block->cstride; /* some additional pointers to store initial data */ vsip_scalar_f *ap0_r = ap_r, *ap0_i = ap_i, *bp0_r, *bp0_i, *cp0_r, *cp0_i; register vsip_scalar_f a00_r, a01_r, a00_i, a01_i; register vsip_scalar_f a10_r, a11_r, a10_i, a11_i; /* we need local storage for a column of b */ register vsip_scalar_f b0_r, b1_r; register vsip_scalar_f b0_i, b1_i; vsip_length i; /* need a counter */ /* we copy matrix a to local storage */ a00_r = *ap0_r, a00_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a01_r = *ap0_r, a01_i = *ap0_i; ap0_r = ap_r + a_st_c; ap0_i = ap_i + a_st_c; a10_r = *ap0_r, a10_i = *ap0_i; ap0_r+=a_st_r; ap0_i += a_st_r; a11_r = *ap0_r, a11_i = *ap0_i; for(i=0; i< c_r_l; i++){ /* copy i'th column of b into local */ bp0_r = bp_r + (vsip_stride)i * b_st_r; bp0_i = bp_i + (vsip_stride)i * b_st_r; b0_r = *bp0_r; b0_i = *bp0_i; bp0_r += b_st_c; bp0_i += b_st_c; b1_r = *bp0_r; b1_i = *bp0_i; /* get the pointer to the column where output will go */ cp0_r = cp_r + (vsip_stride)i * c_st_r; cp0_i = cp_i + (vsip_stride)i * c_st_r; /* do the math */ /* the real part */ *cp0_r = (a00_r * b0_r + a01_r * b1_r) - (a00_i * b0_i + a01_i * b1_i ); cp0_r += c_st_c; *cp0_r = (a10_r * b0_r + a11_r * b1_r) - (a10_i * b0_i + a11_i * b1_i ); /* the imaginary part */ *cp0_i = a00_r * b0_i + a01_r * b1_i + a00_i * b0_r + a01_i * b1_r ; cp0_i += c_st_c; *cp0_i = a10_r * b0_i + a11_r * b1_i + a10_i * b0_r + a11_i * b1_r ; } } <file_sep>import Foundation public func createMandelbrotImage(width: Int, height: Int, xS: Double, yS: Double, rad: Double, maxIteration: Int) -> [Double] { var buffer = Array<Double>(repeating: 0.0, count: width * height) var minMu = Double(maxIteration) var maxMu = 0.0 for yPos in 0..<height { let yP: Double = (yS-rad) + (2.0 * rad/Double(height)) * Double(yPos); for xPos in 0..<width { let xP: Double = (xS - rad) + (2.0 * rad/Double(width)) * Double(xPos) var iteration:Int = 0 var x = 0.0 var y = 0.0 while x * x + y * y <= 4 && iteration < maxIteration { let tmp = x * x - y * y + xP y = 2 * x * y + yP x = tmp; iteration += 1 } if iteration < maxIteration { let modZ = sqrt(x * x + y * y) let mu = Double(iteration) - (log(log(modZ))) / log(2.0) if mu > maxMu { maxMu = mu } if mu < minMu { minMu = mu } buffer[yPos * width + xPos] = mu } else { buffer[yPos * width + xPos] = 0 } } } // Scale buffer values between 0 and 1 var count = width * height; while count > 0 { count -= 1 buffer[count] = (buffer[count] - minMu) / (maxMu - minMu) } return buffer } <file_sep>// // AppDelegate.swift // MatrixExplorer // // Created by <NAME> on 1/17/17. // Copyright © 2017 JVSIP. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var window: MainWindowController? func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application let window = MainWindowController() window.showWindow(self) self.window = window } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } } <file_sep>/* * vsip_vramp_vi.c * Created by <NAME> on 5/16/06. * Copyright 2006 * See Copyright statement in top level directory */ /* $Id: vsip_vramp_vi.c,v 2.4 2007/04/21 19:39:33 judd Exp $ */ #include"vsip.h" #include"vsip_vviewattributes_vi.h" void (vsip_vramp_vi)( vsip_scalar_vi x, vsip_scalar_vi y, const vsip_vview_vi* r) { vsip_length N = r->length,i; register vsip_scalar_vi start = x; register vsip_scalar_vi inc = y; vsip_stride rst = r->stride; vsip_scalar_vi *rp = (r->block->array) + r->offset; *rp = start; for(i=1; i<N; i++){ rp += rst; *rp = start + (vsip_scalar_vi)i * inc; } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mcminmgsqval_f.h,v 2.0 2003/02/22 15:23:24 judd Exp $ */ #include"VU_cmprintm_f.include" static void mcminmgsqval_f(void){ printf("\n*******\nTEST mcminmgsqval_f\n\n"); { vsip_scalar_f data_r[] = {-1, 2, 0, -5, -6, 3.4, -3.4, 5.6, -.3}; vsip_scalar_f data_i[] = {-2, 1, 2, 0, -3, -3.4, +3.4, -5.6, +.3}; vsip_cblock_f *block = vsip_cblockbind_f(data_r,data_i,9,VSIP_MEM_NONE); vsip_cmview_f *a = vsip_cmbind_f(block,0,3,3,1,3); vsip_cblock_f *block2 = vsip_cblockcreate_f(50,VSIP_MEM_NONE); vsip_cmview_f *b = vsip_cmbind_f(block2,49,-2,3,-8,3); vsip_scalar_mi index; vsip_scalar_mi ind_ans = vsip_matindex(2,2); vsip_scalar_f ans = 0.18; vsip_scalar_f val; vsip_cblockadmit_f(block,VSIP_TRUE); vsip_cmcopy_f_f(a,b); val = vsip_mcminmgsqval_f(a,&index); printf("val = vsip_mcminmgsqval_f(a,index)\n matrix a = \n");VU_cmprintm_f("8.6",a); printf("val = %f\n",val); printf("index = (%ld, %ld)\n",vsip_colindex(index),vsip_rowindex(index)); if(fabs(ans - val) > .0001) printf("value error\n"); else printf("value correct\n"); if((vsip_colindex(index) != vsip_colindex(ind_ans)) || (vsip_rowindex(index) != vsip_rowindex(ind_ans))) printf("index error\n"); else printf("index correct\n"); printf("case for non-compact matrix with negative strides\n"); val = vsip_mcminmgsqval_f(b,&index); printf("val = vsip_mcminmgsqval_f(b,index)\n matrix b = \n");VU_cmprintm_f("8.6",b); printf("val = %f\n",val); printf("index = (%ld, %ld)\n",vsip_colindex(index),vsip_rowindex(index)); if(fabs(ans - val) > .0001) printf("value error\n"); else printf("value correct\n"); if((vsip_colindex(index) != vsip_colindex(ind_ans)) || (vsip_rowindex(index) != vsip_rowindex(ind_ans))) printf("index error\n"); else printf("index correct\n"); vsip_cmalldestroy_f(a); vsip_cmalldestroy_f(b); } return; } <file_sep>// // View.cpp // cppJvsip // // Created by <NAME> on 4/27/15. // Copyright (c) 2015 <NAME>. All rights reserved. //<file_sep>/* Created RJudd August 29, 1999 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_llsqsol_f.c,v 2.1 2006/05/16 16:48:17 judd Exp $ */ #include"vsip.h" #include"vsip_qrdattributes_f.h" #include"VI_mrowview_f.h" #include"VI_vput_f.h" #include"VI_vget_f.h" static void VI_vsubvmprodIP_f( vsip_vview_f *a, vsip_mview_f *B, vsip_vview_f *r) { vsip_scalar_f temp; vsip_length nx = 0, mx = 0; vsip_scalar_f *ap = a->block->array + a->offset * a->block->rstride, *ap0 = ap, *rp = r->block->array + r->offset * a->block->rstride, *Byp = B->block->array + B->offset * a->block->rstride, *Bxp = Byp; vsip_stride BCst = B->col_stride * B->block->rstride, BRst = B->row_stride * B->block->rstride, rst = r->stride * r->block->rstride; while(nx++ < B->row_length){ temp = 0; mx = 0; while(mx++ < B->col_length){ temp += (*ap * *Byp); ap += a->stride; Byp += BCst; } *rp -= temp; ap = ap0; Byp = (Bxp += BRst); rp += rst; } } static void VI_solve_ut_f( vsip_mview_f *R, vsip_mview_f *B) { vsip_length N = R->row_length; vsip_mview_f XX = *B; vsip_mview_f *X = &XX; vsip_vview_f xx, rr; vsip_vview_f *x = VI_mrowview_f(X,(vsip_index) (N-1),&xx); vsip_vview_f *r_d = VI_mrowview_f(R,(vsip_index) 0,&rr); vsip_vview_f rr_m = rr; vsip_vview_f *r_m = &rr_m; vsip_stride d_s = R->row_stride + R->col_stride; r_d->length = 1; r_d->offset += ((N-1) * d_s); r_m->length = 0; r_m->offset = r_d->offset + R->row_stride; X->col_length = 1; X->offset = x->offset; vsip_svmul_f((vsip_scalar_f) 1.0/(VI_VGET_F(r_d,0)),x,x); N--; while(N-- >0){ r_d->offset -= d_s; r_m->length++; r_m->offset -= d_s; x->offset -= X->col_stride; VI_vsubvmprodIP_f(r_m,X,x); vsip_svmul_f((vsip_scalar_f) 1.0/(VI_VGET_F(r_d,0)),x,x); X->col_length++; X->offset = x->offset; } return; } static void VI_solve_lt_f( vsip_mview_f *R, vsip_mview_f *B) { vsip_length N = R->row_length; vsip_mview_f XX = *B; vsip_mview_f *X = &XX; vsip_vview_f xx, rr; vsip_vview_f *x = VI_mrowview_f(X,(vsip_index)0,&xx); vsip_vview_f *r_d = VI_mrowview_f(R,(vsip_index) 0,&rr); vsip_vview_f rr_m = rr; vsip_vview_f *r_m = &rr_m; vsip_stride d_s = R->row_stride + R->col_stride; r_d->length = 1; r_m->length = 0; X->col_length = 1; vsip_svmul_f((vsip_scalar_f) 1.0/(VI_VGET_F(r_d,0)),x,x); N--; while(N-- >0){ r_d->offset += d_s; r_m->length++; r_m->offset += R->col_stride; x->offset += X->col_stride; VI_vsubvmprodIP_f(r_m,X,x); vsip_svmul_f((vsip_scalar_f) 1.0/(VI_VGET_F(r_d,0)),x,x); X->col_length++; } return; } static void VI_qrdsolr_f( vsip_mview_f *R0, vsip_mat_op OpR, vsip_mview_f *X0) { vsip_mview_f XX = *X0, RR = *R0; vsip_mview_f *X= &XX, *R = &RR; if(OpR == VSIP_MAT_NTRANS){ VI_solve_ut_f(R,X); } else { vsip_stride t_s = R->row_stride; R->row_stride = R->col_stride; R->col_stride = t_s; VI_solve_lt_f(R,X); } return; } /*------------------------------------------------* | Algorithm 5.2.2 From GVL | *------------------------------------------------*/ /* --------------------------------------------------------- * | VU_givens_f.h | | Algorithm 5.1.3 From GVL | | calculate cosine "c" and sine "s" of a givens rotation | *-----------------------------------------------------------*/ static void VI_givens_f( vsip_scalar_f a, vsip_scalar_f b, vsip_scalar_f *c, vsip_scalar_f *s, vsip_scalar_f *r){ vsip_scalar_f t; if(b == 0){ *c = 1; *s = 0; } else { if(fabs(b) > fabs(a)){ t = -a/b; *s = (vsip_scalar_f)(1.0/sqrt(1 + t * t)); *c = *s * t; } else { t = -b/a; *c = (vsip_scalar_f)(1.0/sqrt(1 + t * t)); *s = *c * t; } } *r = *c * a - *s * b; return; } static int VI_givens_llsq_f( vsip_mview_f *A, vsip_mview_f *B) { int retval = 0; vsip_length m = A->col_length; vsip_length n = A->row_length; vsip_length bn = B->row_length; vsip_length i,j,k; vsip_scalar_f c=0,s=0,r=0; vsip_stride Ar_st = A->row_stride * A->block->rstride; vsip_stride Br_st = B->row_stride * B->block->rstride; for(j=0; j<n; j++){ for(i=m-1; i>j; i--){ vsip_scalar_f *a0p = A->block->array + (A->offset + (i-1) * A->col_stride + j * A->row_stride) * A->block->rstride; vsip_scalar_f *a1p = A->block->array + (A->offset + i * A->col_stride + j * A->row_stride) * A->block->rstride; vsip_scalar_f *b0p = B->block->array + (B->offset + (i-1) * B->col_stride ) * B->block->rstride; vsip_scalar_f *b1p = B->block->array + (B->offset + i * B->col_stride ) * B->block->rstride; VI_givens_f(*a0p,*a1p,&c,&s,&r); if(r == 0) retval++; *a0p = r; *a1p = 0; a1p += Ar_st; a0p +=Ar_st; for(k=1; k<n-j; k++){ vsip_scalar_f a0 = *a0p, a1 = *a1p; *a0p = a0 * c - a1 * s; *a1p = a0 * s + a1 * c; a1p += Ar_st; a0p += Ar_st; } for(k=0; k<bn; k++){ vsip_scalar_f b0 = *b0p, b1 = *b1p; *b0p = b0 * c - b1 * s; *b1p = b0 * s + b1 * c; b1p += Br_st; b0p += Br_st; } } } return retval; } int vsip_llsqsol_f( const vsip_mview_f *A, const vsip_mview_f *XB) { int retval = 0; vsip_mview_f RR = *A; vsip_mview_f *R = &RR; vsip_mview_f XX = *XB; vsip_mview_f *X = &XX; retval += VI_givens_llsq_f(R,X); R->row_length = A->row_length; R->col_length = A->col_length; X->col_length = R->col_length; VI_qrdsolr_f(R,VSIP_MAT_NTRANS,X); return retval; } <file_sep>/* Created RJudd August 29, 1999 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cllsqsol_d.c,v 2.1 2006/05/16 16:48:17 judd Exp $ */ #include"vsip.h" #include"vsip_cqrdattributes_d.h" #include"VI_cmrowview_d.h" static void VI_cvjsubvmprodIP_d( vsip_cvview_d *a, vsip_cmview_d *B, vsip_cvview_d *r) { vsip_scalar_d temp_r; vsip_scalar_d temp_i; vsip_length nx = 0, mx = 0; vsip_stride cast = a->block->cstride, crst = r->block->cstride, cBst = B->block->cstride; vsip_scalar_d *ap_r = (vsip_scalar_d*)(a->block->R->array + cast * a->offset), *ap_i = (vsip_scalar_d*)(a->block->I->array + cast * a->offset), *rp_r = (vsip_scalar_d*)(r->block->R->array + crst * r->offset), *rp_i = (vsip_scalar_d*)(r->block->I->array + crst * r->offset), *Byp_r = (vsip_scalar_d*)(B->block->R->array + cBst * B->offset), *Byp_i = (vsip_scalar_d*)(B->block->I->array + cBst * B->offset), *Bxpr = Byp_r, *Bxpi = Byp_i; vsip_length sta = cast * a->stride, str = crst * r->stride, stB = cBst * B->col_stride; while(nx++ < B->row_length){ temp_r = 0; temp_i = 0; mx = 0; while(mx++ < B->col_length){ temp_r += (*ap_r * *Byp_r + *ap_i * *Byp_i); temp_i += (*ap_r * *Byp_i - *ap_i * *Byp_r); ap_r += sta; Byp_r += stB; ap_i += sta; Byp_i += stB; } *rp_r -= temp_r; *rp_i -= temp_i; ap_r = (vsip_scalar_d*)(a->block->R->array + cast * a->offset); ap_i = (vsip_scalar_d*)(a->block->I->array + cast * a->offset); Byp_r = (Bxpr += (cBst * B->row_stride)); Byp_i = (Bxpi += (cBst * B->row_stride)); rp_r += str; rp_i += str; } } static void VI_cvsubvmprodIP_d( vsip_cvview_d *a, vsip_cmview_d *B, vsip_cvview_d *r) { vsip_scalar_d temp_r; vsip_scalar_d temp_i; vsip_length nx = 0, mx = 0; vsip_stride cast = a->block->cstride, crst = r->block->cstride, cBst = B->block->cstride; vsip_scalar_d *ap_r = (vsip_scalar_d*)(a->block->R->array + cast * a->offset), *ap_i = (vsip_scalar_d*)(a->block->I->array + cast * a->offset), *rp_r = (vsip_scalar_d*)(r->block->R->array + crst * r->offset), *rp_i = (vsip_scalar_d*)(r->block->I->array + crst * r->offset), *Byp_r = (vsip_scalar_d*)(B->block->R->array + cBst * B->offset), *Byp_i = (vsip_scalar_d*)(B->block->I->array + cBst * B->offset), *Bxpr = Byp_r, *Bxpi = Byp_i; vsip_stride sta = cast * a->stride, str = crst * r->stride, stB = cBst * B->col_stride; while(nx++ < B->row_length){ temp_r = 0; temp_i = 0; mx = 0; while(mx++ < B->col_length){ temp_r += (*ap_r * *Byp_r - *ap_i * *Byp_i); temp_i += (*ap_r * *Byp_i + *ap_i * *Byp_r); ap_r += sta; Byp_r += stB; ap_i += sta; Byp_i += stB; } *rp_r -= temp_r; *rp_i -= temp_i; ap_r = (vsip_scalar_d*)(a->block->R->array + cast * a->offset); ap_i = (vsip_scalar_d*)(a->block->I->array + cast * a->offset); Byp_r = (Bxpr += (cBst * B->row_stride)); Byp_i = (Bxpi += (cBst * B->row_stride)); rp_r += str; rp_i += str; } } static void VI_csolve_ut_d( vsip_cmview_d *R, vsip_cmview_d *B) { vsip_length N = R->row_length; vsip_cmview_d XX = *B; vsip_cmview_d *X = &XX; vsip_cvview_d xx, rr; vsip_cvview_d *x = VI_cmrowview_d(X,(vsip_index) (N-1),&xx); vsip_cvview_d *r_d = VI_cmrowview_d(R,(vsip_index) 0,&rr); vsip_cvview_d rr_m = rr; vsip_cvview_d *r_m = &rr_m; vsip_stride d_s = R->row_stride + R->col_stride; r_d->length = 1; r_d->offset += ((N-1) * d_s); r_m->length = 0; r_m->offset = r_d->offset + R->row_stride; X->col_length = 1; X->offset = x->offset; vsip_csvmul_d(vsip_crecip_d(vsip_cvget_d(r_d,0)),x,x); N--; while(N-- >0){ r_d->offset -= d_s; r_m->length++; r_m->offset -= d_s; x->offset -= X->col_stride; VI_cvsubvmprodIP_d(r_m,X,x); vsip_csvmul_d(vsip_crecip_d(vsip_cvget_d(r_d,0)),x,x); X->col_length++; X->offset = x->offset; } return; } static void VI_csolve_lt_d( vsip_cmview_d *R, vsip_cmview_d *B) { vsip_length N = R->row_length; vsip_cmview_d XX = *B; vsip_cmview_d *X = &XX; vsip_cvview_d xx, rr; vsip_cvview_d *x = VI_cmrowview_d(X,(vsip_index)0,&xx); vsip_cvview_d *r_d = VI_cmrowview_d(R,(vsip_index) 0,&rr); vsip_cvview_d rr_m = rr; vsip_cvview_d *r_m = &rr_m; vsip_stride d_s = R->row_stride + R->col_stride; r_d->length = 1; r_m->length = 0; X->col_length = 1; /* vsip_csvmul_d(vsip_crecip_d(vsip_conj_d(vsip_cvget_d(r_d,0))),x,x); */ vsip_rscvmul_d((vsip_scalar_d)1.0/(vsip_real_d(vsip_cvget_d(r_d,0))),x,x); N--; while(N-- >0){ r_d->offset += d_s; r_m->length++; r_m->offset += R->col_stride; x->offset += X->col_stride; VI_cvjsubvmprodIP_d(r_m,X,x); /* vsip_csvmul_d(vsip_crecip_d(vsip_conj_d(vsip_cvget_d(r_d,0))),x,x); */ vsip_rscvmul_d((vsip_scalar_d)1.0/(vsip_real_d(vsip_cvget_d(r_d,0))),x,x); X->col_length++; } return; } static void VI_cqrdsolr_d( vsip_cmview_d *R0, vsip_mat_op OpR, vsip_cmview_d *X0) { vsip_cmview_d XX = *X0, RR = *R0; vsip_cmview_d *X= &XX, *R = &RR; if(OpR == VSIP_MAT_NTRANS){ VI_csolve_ut_d(R,X); } else { vsip_stride t_s = R->row_stride; R->row_stride = R->col_stride; R->col_stride = t_s; VI_csolve_lt_d(R,X); } return; } static void VI_cgivens_d( vsip_cscalar_d a, vsip_cscalar_d b, vsip_cscalar_d *c, vsip_cscalar_d *s, vsip_cscalar_d *r) { vsip_scalar_d am = vsip_cmag_d(a); vsip_scalar_d bm = vsip_cmag_d(b); c->i = 0.0; if(am == 0.0){ *r = b; c->r = 0.0; s->r = 1; s->i = 0.0; } else { vsip_scalar_d scale = am + bm; vsip_cscalar_d alpha = vsip_cmplx_d(a.r/am, a.i/am); vsip_scalar_d scalesq = scale * scale; vsip_scalar_d norm = scale * (vsip_scalar_d)sqrt((am*am)/scalesq + (bm * bm)/scalesq); c->r =am/norm; s->r = (alpha.r * b.r + alpha.i * b.i)/norm; s->i = (-alpha.r * b.i + alpha.i * b.r)/norm; r->r = alpha.r * norm; r->i = alpha.i * norm; } return; } static void VI_cgivens_llsq_d( vsip_cmview_d *A,vsip_cmview_d *B) { vsip_length m = A->col_length; vsip_length n = A->row_length; vsip_length bn = B->row_length; vsip_length i,j,k; vsip_cscalar_d c,s10,s01,r; vsip_stride Ar_st = A->row_stride * A->block->cstride; vsip_stride Br_st = B->row_stride * B->block->cstride; for(j=0; j<n; j++){ for(i=m-1; i>j; i--){ vsip_scalar_d *a0p_r = A->block->R->array + (A->offset + (i-1) * A->col_stride + j * A->row_stride) * A->block->cstride; vsip_scalar_d *a0p_i = A->block->I->array + (A->offset + (i-1) * A->col_stride + j * A->row_stride) * A->block->cstride; vsip_scalar_d *a1p_r = A->block->R->array + (A->offset + i * A->col_stride + j * A->row_stride) * A->block->cstride; vsip_scalar_d *a1p_i = A->block->I->array + (A->offset + i * A->col_stride + j * A->row_stride) * A->block->cstride; vsip_scalar_d *b0p_r = B->block->R->array + (B->offset + (i-1) * B->col_stride) * B->block->cstride; vsip_scalar_d *b0p_i = B->block->I->array + (B->offset + (i-1) * B->col_stride) * B->block->cstride; vsip_scalar_d *b1p_r = B->block->R->array + (B->offset + i * B->col_stride) * B->block->cstride; vsip_scalar_d *b1p_i = B->block->I->array + (B->offset + i * B->col_stride) * B->block->cstride; vsip_cscalar_d a,b; a.r = *a0p_r; a.i = *a0p_i; b.r = *a1p_r; b.i = *a1p_i; VI_cgivens_d(a,b,&c,&s01,&r); /* rotate r so the iamginary part is 0 and store in a0p*/ *a0p_r = vsip_cmag_d(r); *a0p_i = 0; *a1p_r = 0.0; *a1p_i = 0.0; /* store a rotation vector in r */ if(*a0p_r != 0.0){ r.r = r.r / *a0p_r; r.i = - r.i / *a0p_r; } a0p_r += Ar_st; a0p_i += Ar_st; a1p_r += Ar_st; a1p_i += Ar_st; s10.r = - s01.r; s10.i = s01.i; for(k=1; k<n-j; k++){ vsip_scalar_d a0_r = *a0p_r, a1_r = *a1p_r; vsip_scalar_d a0_i = *a0p_i, a1_i = *a1p_i; vsip_cscalar_d a0; a0.r = a0_r * c.r + a1_r * s01.r - a1_i * s01.i; a0.i = a0_i * c.r + s01.r * a1_i + a1_r * s01.i; /* correct a0 for rotation and place in matrix*/ *a0p_r = r.r * a0.r - r.i * a0.i; *a0p_i = r.r * a0.i + r.i * a0.r; *a1p_r = a1_r * c.r + s10.r * a0_r - s10.i * a0_i; *a1p_i = a1_i * c.r + s10.r * a0_i + s10.i * a0_r; a0p_r += Ar_st; a0p_i += Ar_st; a1p_r += Ar_st; a1p_i += Ar_st; } for(k=0; k<bn; k++){ vsip_scalar_d b0_r = *b0p_r, b1_r = *b1p_r; vsip_scalar_d b0_i = *b0p_i, b1_i = *b1p_i; vsip_cscalar_d b0; b0.r = b0_r * c.r + b1_r * s01.r - b1_i * s01.i; b0.i = b0_i * c.r + s01.r * b1_i + b1_r * s01.i; /* correct b0 for rotation and place in matrix*/ *b0p_r = r.r * b0.r - r.i * b0.i; *b0p_i = r.r * b0.i + r.i * b0.r; *b1p_r = b1_r * c.r + s10.r * b0_r - s10.i * b0_i; *b1p_i = b1_i * c.r + s10.r * b0_i + s10.i * b0_r; b0p_r += Br_st; b0p_i += Br_st; b1p_r += Br_st; b1p_i += Br_st; } } } return; } int vsip_cllsqsol_d( const vsip_cmview_d *A, const vsip_cmview_d *XB) { int retval = 0; vsip_cmview_d RR = *A; vsip_cmview_d *R = &RR; vsip_cmview_d XX = *XB; vsip_cmview_d *X = &XX; VI_cgivens_llsq_d(R,X); R->col_length = R->row_length; X->col_length = R->col_length; VI_cqrdsolr_d(R,VSIP_MAT_NTRANS,X); return retval; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_length_vi.h,v 2.1 2007/04/18 17:05:56 judd Exp $ */ static void get_put_length_vi(void){ printf("********\nTEST get_put_length_vi\n"); { vsip_offset ivo = 3; vsip_stride ivs = 0; vsip_length ivl = 3; vsip_length jvl = 5; vsip_block_vi *b = vsip_blockcreate_vi(80,VSIP_MEM_NONE); vsip_vview_vi *v = vsip_vbind_vi(b,ivo,ivs,ivl); vsip_length s; printf("test vgetlength_vi\n"); fflush(stdout); { s = vsip_vgetlength_vi(v); (s == ivl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputlength_vi\n"); fflush(stdout); { vsip_vputlength_vi(v,jvl); s = vsip_vgetlength_vi(v); (s == jvl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } vsip_valldestroy_vi(v); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: tmisc_view_si.h,v 2.1 2009/09/05 18:01:45 judd Exp $ */ static void tmisc_view_si(void){ printf("********\nTEST tmisc_view_si\n"); { vsip_index k,j,i; vsip_scalar_si data_r[4][3][4] = {{{00, 001, 002, 003}, \ {01, 011, 012, 013}, \ {02, 021, 022, 023}}, \ {{10, 101, 102, 103}, \ {11, 111, 112, 113}, \ {12, 121, 122, 123}}, \ {{20, 201, 202, 203}, \ {21, 211, 212, 213}, \ {22, 221, 222, 223}}, \ {{30, 301, 302, 303}, \ {31, 311, 312, 313}, \ {32, 321, 322, 323}}}; /* if a problem with tcreate is suspected check both leading and trailing options here */ vsip_tview_si *tview_a = vsip_tcreate_si(12,9,12,VSIP_LEADING,VSIP_MEM_NONE); /* vsip_tview_si *tview_a = vsip_tcreate_si(12,9,12,VSIP_TRAILING,VSIP_MEM_NONE); */ vsip_block_si *block_a = vsip_tgetblock_si(tview_a); vsip_tview_si *tview_b = vsip_tsubview_si(tview_a,1,2,3,4,3,4); vsip_stride z_a_st = vsip_tgetzstride_si(tview_a); vsip_stride y_a_st = vsip_tgetystride_si(tview_a); vsip_stride x_a_st = vsip_tgetxstride_si(tview_a); vsip_offset b_o_calc = z_a_st + 2 * y_a_st + 3 * x_a_st; vsip_offset b_o_get = vsip_tgetoffset_si(tview_b); vsip_tview_si *v = vsip_tbind_si(block_a,b_o_calc, z_a_st,4, y_a_st,3, x_a_st,4); vsip_mview_si *mview = (vsip_mview_si*)NULL; vsip_vview_si *vview = (vsip_vview_si*)NULL; vsip_tview_si *tview = (vsip_tview_si*)NULL; vsip_scalar_si a; int chk = 0; printf("z_a_st %d; y_a_st %d; x_a_st %d\n",(int)z_a_st,(int)y_a_st,(int)x_a_st); fflush(stdout); printf("b_o_calc %ul; b_o_get %ul\n",(unsigned)b_o_calc,(unsigned)b_o_get); fflush(stdout); for(k = 0; k < 4; k++){ for(j = 0; j < 3; j++){ for(i = 0; i < 4; i++){ a = data_r[k][j][i]; vsip_tput_si(v,k,j,i,a); } } } printf("test tmatrixview_si\n"); printf("TMZY\n"); fflush(stdout); for(i = 0; i < 4; i++){ mview = vsip_tmatrixview_si(v,VSIP_TMZY,i); for(j = 0; j < 3; j++){ for(k = 0; k < 4; k++){ a = vsip_mget_si(mview,k,j); a -= data_r[k][j][i]; chk += a * a; } } vsip_mdestroy_si(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TMYX\n"); fflush(stdout); for(k = 0; k < 4; k++){ mview = vsip_tmatrixview_si(v,VSIP_TMYX,k); for(j = 0; j < 3; j++){ for(i = 0; i < 4; i++){ a = vsip_mget_si(mview,j,i); a -= data_r[k][j][i]; chk += a * a; } } vsip_mdestroy_si(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TMZX\n"); fflush(stdout); for(j = 0; j < 3; j++){ mview = vsip_tmatrixview_si(v,VSIP_TMZX,j); for(k = 0; k < 4; k++){ for(i = 0; i < 4; i++){ a = vsip_mget_si(mview,k,i); a -= data_r[k][j][i]; chk += a * a; } } vsip_mdestroy_si(mview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test tvectview_si\n"); printf("TVX \n"); fflush(stdout); for(k=0; k<4; k++){ for(j=0; j<3; j++){ vview = vsip_tvectview_si(v,VSIP_TVX,k,j); for(i=0; i<4; i++){ a = vsip_vget_si(vview,i); a -= data_r[k][j][i]; chk += a * a; } } vsip_vdestroy_si(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test tvectview_si\n"); printf("TVY \n"); fflush(stdout); for(k=0; k<4; k++){ for(i=0; i<4; i++){ vview = vsip_tvectview_si(v,VSIP_TVY,k,i); for(j=0; j<3; j++){ a = vsip_vget_si(vview,j); a -= data_r[k][j][i]; chk += a * a ; } } vsip_vdestroy_si(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("TVZ \n"); fflush(stdout); for(j=0; j<3; j++){ for(i=0; i<4; i++){ vview = vsip_tvectview_si(v,VSIP_TVZ,j,i); for(k=0; k<4; k++){ a = vsip_vget_si(vview,k); a -= data_r[k][j][i]; chk += a * a; } } vsip_vdestroy_si(vview); } (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("test ttransview_si\n"); fflush(stdout); printf("NOP\n"); fflush(stdout); tview = vsip_ttransview_si(v,VSIP_TTRANS_NOP); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_si(tview,k,j,i); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_si(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YX\n"); fflush(stdout); tview = vsip_ttransview_si(v,VSIP_TTRANS_YX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_si(tview,k,i,j); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_si(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("ZY\n"); fflush(stdout); tview = vsip_ttransview_si(v,VSIP_TTRANS_ZY); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_si(tview,j,k,i); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_si(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("ZX\n"); fflush(stdout); tview = vsip_ttransview_si(v,VSIP_TTRANS_ZX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_si(tview,i,j,k); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_si(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YXZY\n"); fflush(stdout); tview = vsip_ttransview_si(v,VSIP_TTRANS_YXZY); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_si(tview,i,k,j); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_si(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; printf("YXZX\n"); fflush(stdout); tview = vsip_ttransview_si(v,VSIP_TTRANS_YXZX); for(k=0; k<4; k++){ for(j=0; j<3; j++){ for(i=0; i<4; i++){ a = vsip_tget_si(tview,j,i,k); a -= data_r[k][j][i]; chk += a * a; } } } vsip_tdestroy_si(tview); (chk > .0001) ? printf("error\n") : printf("correct\n"); fflush(stdout); chk = 0; vsip_tdestroy_si(v); vsip_tdestroy_si(tview_b); vsip_talldestroy_si(tview_a); } return; } <file_sep>/* Created RJudd */ /********************************************************************** // TASP VSIPL Documentation and Code includes no warranty, / // express or implied, including the warranties of merchantability / // and fitness for a particular purpose. No person or organization / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_minterp_spline_d.c,v 2.1 2008/09/14 20:48:40 judd Exp $ */ #include"vsip.h" #include"vsip_vviewattributes_d.h" #include"vsip_mviewattributes_d.h" #include"vsip_splineattributes_d.h" #define GETROW(_a,_i,_row) {\ _row->block = _a->block; \ _row->stride = _a->row_stride; \ _row->length = _a->row_length; \ _row->offset = _a->offset + _i * _a->col_stride;\ } #define GETCOL(_a,_i,_col) {\ _col->block = _a->block; \ _col->stride = _a->col_stride; \ _col->length = _a->col_length; \ _col->offset = _a->offset + _i * _a->row_stride;\ } #define VINTERP_SPLINE( _t0, _y0, _spl, _xf0, _yf0) { \ vsip_length N = _t0->length; \ vsip_length M = _xf0->length; \ vsip_stride t_st = _t0->stride * _t0->block->rstride, \ y_st = _y0->stride * _y0->block->rstride, \ xf_st = _xf0->stride * _xf0->block->rstride, \ yf_st = _yf0->stride * _yf0->block->rstride; \ vsip_index i; \ vsip_stride j; \ vsip_scalar_d *t = _t0->block->array + _t0->offset * _t0->block->rstride; \ vsip_scalar_d *_y = _y0->block->array + _y0->offset * _y0->block->rstride; \ vsip_scalar_d *xf = _xf0->block->array + _xf0->offset * _xf0->block->rstride; \ vsip_scalar_d *_yf = _yf0->block->array + _yf0->offset * _yf0->block->rstride; \ vsip_scalar_d *z = _spl->z, *h=_spl->h, *b = _spl->b, *u = _spl->u, *v = _spl->v; \ for(i=0; i<N-1; i++){ \ h[i] = t[(i+1) * t_st] - t[i * t_st]; \ b[i] = (_y[(i+1) * y_st] - _y[i * y_st])/h[i]; \ } \ u[1] = 2.0 * (h[0] + h[1]); \ v[1] = 6.0 * (b[1] - b[0]); \ for(i=2; i<N-1; i++){ \ u[i] = 2.0 * (h[i] + h[i-1]) - h[i-1] * h[i-1] / u[i-1];\ v[i] = 6.0 * (b[i] - b[i-1]) - h[i-1] * v[i-1] / u[i-1];\ } \ z[N-1] = 0.0; \ for(i=N-2; i>0; i--) \ z[i] = (v[i] - h[i] * z[i+1])/u[i]; \ z[0] = 0.0; \ for(i=0; i<M; i++){ \ register vsip_scalar_d yj,zj,zj1; \ register vsip_scalar_d d,h,b,p,x; \ x = xf[i * xf_st]; \ j = N-2; \ while((x < (d = t[j * t_st])) && (j >= 0)) j--; \ yj = _y[j * y_st]; \ zj=z[j]; zj1=z[j+1]; \ d = x - d; \ if(j < 0) j = 0; \ if(d < 0) break; \ h = t[(j+1) * t_st] - t[j * t_st];\ b = (_y[(j+1) * y_st] - yj)/h - h * (zj1 + 2.0 * zj)/6.0;\ p = ((0.5 * zj +d * (zj1 - zj)/(6.0 * h)) * d + b) * d;\ _yf[i * yf_st] = yj + p;\ } } void vsip_minterp_spline_d( const vsip_vview_d *ax, const vsip_mview_d *ay, vsip_spline_d *spl, vsip_major major, const vsip_vview_d *bx, const vsip_mview_d *by){ vsip_index i; vsip_vview_d *y,yy; vsip_vview_d *yf,yyf; y = &yy; yf = &yyf; if(major == VSIP_ROW) { vsip_length M = ay->col_length; for(i=0; i<M; i++){ GETROW(ay,i,y); GETROW(by,i,yf); VINTERP_SPLINE(ax,y,spl,bx,yf); } } else { /* must be by column */ vsip_length M = ay->row_length; for(i=0; i<M; i++){ GETCOL(ay,i,y); GETCOL(by,i,yf); VINTERP_SPLINE(ax,y,spl,bx,yf); } } return; } <file_sep>import Foundation import vsip public func oddNumber(_ n: Int) -> Bool { let b = n % 2 return b == 1 } public func VU_vfreqswapIP_d(b: OpaquePointer){ let N = vsip_vgetlength_d(b); if oddNumber(Int(N)) { let a1 = vsip_vsubview_d(b,vsip_index((N/2)+1),vsip_length(N/2)) let a2 = vsip_vsubview_d(b,vsip_index(0), vsip_length((N/2)+1)) let a3 = vsip_vcreate_d(vsip_length((N/2)+1), VSIP_MEM_NONE); vsip_vcopy_d_d(a2,a3); vsip_vputlength_d(a2,(vsip_length)(N/2)); vsip_vcopy_d_d(a1,a2); vsip_vputlength_d(a2,(vsip_length)(N/2) + 1); vsip_vputoffset_d(a2,(vsip_offset)(N/2)); vsip_vcopy_d_d(a3,a2); vsip_vdestroy_d(a1); vsip_vdestroy_d(a2); vsip_valldestroy_d(a3); } else { /* even */ let a1 = vsip_vsubview_d(b,vsip_index(N/2),vsip_length(N/2)) vsip_vputlength_d(b,(vsip_length)(N/2)); vsip_vswap_d(b,a1); vsip_vdestroy_d(a1); vsip_vputlength_d(b,N); } return; } <file_sep>#include"numpyArrayCopies.h" void vcopyToNParray_d(vsip_vview_d *v, PyObject* array){ vsip_vcopyto_user_d(v,(vsip_scalar_d*)PyArray_DATA((PyArrayObject*)array)); } void vcopyToNParray_f(vsip_vview_f *v, PyObject* array){ vsip_vcopyto_user_f(v,(vsip_scalar_f*)PyArray_DATA((PyArrayObject*)array)); } void cvcopyToNParray_d(vsip_cvview_d *v, PyObject* array){ vsip_cvcopyto_user_d(v,(vsip_scalar_d*)PyArray_DATA((PyArrayObject*)array),NULL); } void cvcopyToNParray_f(vsip_cvview_f *v, PyObject* array){ vsip_cvcopyto_user_f(v,(vsip_scalar_f*)PyArray_DATA((PyArrayObject*)array),NULL); } void mcopyToNParray_d(vsip_mview_d *v, vsip_major major, PyObject* array){ vsip_mcopyto_user_d(v,major,(vsip_scalar_d*)PyArray_DATA((PyArrayObject*)array)); } void mcopyToNParray_f(vsip_mview_f *v, vsip_major major, PyObject* array){ vsip_mcopyto_user_f(v,major,(vsip_scalar_f*)PyArray_DATA((PyArrayObject*)array)); } void cmcopyToNParray_d(vsip_cmview_d *v, vsip_major major, PyObject* array){ vsip_cmcopyto_user_d(v,major,(vsip_scalar_d*)PyArray_DATA((PyArrayObject*)array),NULL); } void cmcopyToNParray_f(vsip_cmview_f *v, vsip_major major, PyObject* array){ vsip_cmcopyto_user_f(v,major,(vsip_scalar_f*)PyArray_DATA((PyArrayObject*)array),NULL); } void vcopyFromNParray_d(vsip_vview_d *v, PyObject* array){ vsip_vcopyfrom_user_d((vsip_scalar_d*)PyArray_DATA((PyArrayObject*)array),v); } void vcopyFromNParray_f(vsip_vview_f *v, PyObject* array){ vsip_vcopyfrom_user_f((vsip_scalar_f*)PyArray_DATA((PyArrayObject*)array),v); } void cvcopyFromNParray_d(vsip_cvview_d *v, PyObject* array){ vsip_cvcopyfrom_user_d((vsip_scalar_d*)PyArray_DATA((PyArrayObject*)array),NULL,v); } void cvcopyFromNParray_f(vsip_cvview_f *v, PyObject* array){ vsip_cvcopyfrom_user_f((vsip_scalar_f*)PyArray_DATA((PyArrayObject*)array),NULL,v); } void mcopyFromNParray_d(vsip_mview_d *v, vsip_major major, PyObject* array){ vsip_mcopyfrom_user_d((vsip_scalar_d*)PyArray_DATA((PyArrayObject*)array),major,v); } void mcopyFromNParray_f(vsip_mview_f *v, vsip_major major, PyObject* array){ vsip_mcopyfrom_user_f((vsip_scalar_f*)PyArray_DATA((PyArrayObject*)array),major,v); } void cmcopyFromNParray_d(vsip_cmview_d *v, vsip_major major, PyObject* array){ vsip_cmcopyfrom_user_d((vsip_scalar_d*)PyArray_DATA((PyArrayObject*)array),NULL,major,v); } void cmcopyFromNParray_f(vsip_cmview_f *v, vsip_major major, PyObject* array){ vsip_cmcopyfrom_user_f((vsip_scalar_f*)PyArray_DATA((PyArrayObject*)array),NULL,major,v); } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: chol_d.h,v 2.0 2003/02/22 15:23:07 judd Exp $ */ #include"VU_mprintm_d.include" static void chol_d(void){ printf("********\nTEST chol_d\n"); { vsip_index i,j; vsip_block_d *ablock = vsip_blockcreate_d(200,VSIP_MEM_NONE); vsip_mview_d *R = vsip_mcreate_d(4,4,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *RH = vsip_mcreate_d(4,4,VSIP_ROW,VSIP_MEM_NONE); /* vsip_mview_d *A = vsip_mcreate_d(4,4,VSIP_ROW,VSIP_MEM_NONE); */ vsip_mview_d *A = vsip_mbind_d(ablock,99,-11,4,-2,4); /* vsip_mview_d *B = vsip_mcreate_d(4,3,VSIP_COL,VSIP_MEM_NONE); */ vsip_mview_d *B = vsip_mbind_d(ablock,100,20,4,2,3); vsip_mview_d *ans = vsip_mcreate_d(4,3,VSIP_ROW,VSIP_MEM_NONE); vsip_chol_d *chol = vsip_chold_create_d(VSIP_TR_UPP,4); vsip_scalar_d chk; vsip_scalar_d data_R[4][4] = { {1.0, -2.0, 3.0, 1.0}, {0.0, 2.0, 4.0, -1.0}, {0.0, 0.0, 4.0, 3.0}, {0.0, 0.0, 0.0, 6.0} }; vsip_scalar_d data_Br[4][3] = { { 1.0, 2.0, 3.0}, { 0.0, 1.0, 2.0}, { 3.0, 0.0, 1.0}, { 3.0, 4.0, 5.0}}; vsip_scalar_d data_ans[4][3] = { { 4.6250, 13.9062, 21.0000}, { 1.3333, 4.1667, 6.3333}, { -0.3750, -1.3438, -2.0000}, { 0.1667, 0.4583, 0.6667}}; for(i=0; i<4; i++) for(j=0; j<4; j++) vsip_mput_d(R,i,j,data_R[i][j]); for(i=0; i<4; i++) { for(j=0; j<3; j++){ vsip_mput_d(B,i,j,data_Br[i][j]); vsip_mput_d(ans,i,j,data_ans[i][j]); } } vsip_mtrans_d(R,RH); vsip_mprod_d(RH,R,A); printf("R = \n");VU_mprintm_d("4.2",R); printf("RH = \n");VU_mprintm_d("4.2",RH); printf("A = R * RH\n");VU_mprintm_d("4.2",A); printf("B \n");VU_mprintm_d("4.2",B); vsip_chold_d(chol,A); vsip_cholsol_d(chol,B); printf("Solve using cholesky AX = B\n X = \n");VU_mprintm_d("4.2",B); vsip_chold_destroy_d(chol); printf("right answer \n ans = \n");VU_mprintm_d("4.2",ans); vsip_msub_d(ans,B,B); chk = vsip_msumsqval_d(B); if(chk > .001) printf("error\n"); else printf("correct\n"); { vsip_lu_d *lu = vsip_lud_create_d(4); vsip_mview_d *Bans = vsip_mcreate_d(4,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mprod_d(RH,R,A); for(i=0; i<4; i++) for(j=0; j<3; j++) vsip_mput_d(B,i,j,data_Br[i][j]); vsip_lud_d(lu,A); vsip_lusol_d(lu,VSIP_MAT_NTRANS,B); printf("Solve using LUD AX = B\n X = \n");VU_mprintm_d("4.2",B); vsip_lud_destroy_d(lu); vsip_mprod_d(RH,R,A); vsip_mprod_d(A,B,Bans); printf("Bans = A X\n");VU_mprintm_d("4.2",Bans); vsip_msub_d(ans,B,B); chk = vsip_msumsqval_d(B); if(chk > .001) printf("error\n"); else printf("correct\n"); vsip_malldestroy_d(Bans); } vsip_malldestroy_d(R); vsip_malldestroy_d(RH); vsip_mdestroy_d(B); vsip_malldestroy_d(A); } } <file_sep>/* Created RJudd September 16, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cblockbind_d.c,v 2.2 2009/05/20 17:11:15 judd Exp $ */ #include"vsip.h" #include"vsip_cblockattributes_d.h" #include"vsip_blockattributes_d.h" vsip_cblock_d* (vsip_cblockbind_d)( vsip_scalar_d* const Rp, vsip_scalar_d* const Ip, vsip_length N, vsip_memory_hint h) { vsip_cblock_d* b = (vsip_cblock_d*)malloc(sizeof(vsip_cblock_d)); if(b != (vsip_cblock_d*)NULL) b->hint = h; #if defined(VSIP_DEFAULT_SPLIT) #include"VI_cblockbind_d_ds.h" #elif defined(VSIP_ALWAYS_SPLIT) #include"VI_cblockbind_d_as.h" #elif defined(VSIP_ALWAYS_INTERLEAVED) #include"VI_cblockbind_d_ai.h" #else #include"VI_cblockbind_d_di.h" #endif return b; } <file_sep>import pyJvsip as pv def localmax(A): """ Note A is a vector of type real float % k = localmax(x) % finds location of local maxima """ sptd=['vview_d','vview_f'] assert A.type in sptd, 'local max only works with real vectors of type float' x=A N = x.length b1=x[:N-1].lle(x[1:N]); b2=x[:N-1].lgt(x[1:N]) k = b1[0:N-2].bband(b2[1:N-1]).indexbool k+=1 if x[0] > x[1]: t=pv.create(k.type,k.length+1) t[:k.length]=k t[k.length]=0 k=t.copy if x[N-1]>x[N-2]: t=pv.create(k.type,k.length+1) t[:k.length]=k t[k.length]=N-1 k=t.copy k.sortip() return k <file_sep>// // Matrix.swift // vsip // // Created by <NAME> on 4/22/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import vsip public class Matrix : View { fileprivate var tryVsip: OpaquePointer? public var vsip: OpaquePointer { get { return tryVsip! } } // matrix bind // matrix create // Matrix bind returns vsip object (may be null on malloc failure) private func mBind(_ offset : Int, columnStride : Int, columnLength : Int, rowStride : Int, rowLength : Int) -> OpaquePointer? { let blk = self.block.vsip let t = self.block.type switch t{ case .f: return vsip_mbind_f(blk, vsip_offset(offset), vsip_stride(columnStride), vsip_length(columnLength), vsip_stride(rowStride), vsip_length(rowLength)) case .d: return vsip_mbind_d(blk, vsip_offset(offset), vsip_stride(columnStride), vsip_length(columnLength), vsip_stride(rowStride), vsip_length(rowLength)) case .cf: return vsip_cmbind_f(blk, vsip_offset(offset), vsip_stride(columnStride), vsip_length(columnLength), vsip_stride(rowStride), vsip_length(rowLength)) case .cd: return vsip_cmbind_d(blk, vsip_offset(offset), vsip_stride(columnStride), vsip_length(columnLength), vsip_stride(rowStride), vsip_length(rowLength)) case .i: return vsip_mbind_i(blk, vsip_offset(offset), vsip_stride(columnStride), vsip_length(columnLength), vsip_stride(rowStride), vsip_length(rowLength)) case .li: return vsip_mbind_li(blk, vsip_offset(offset), vsip_stride(columnStride), vsip_length(columnLength), vsip_stride(rowStride), vsip_length(rowLength)) case .si: return vsip_mbind_si(blk, vsip_offset(offset), vsip_stride(columnStride), vsip_length(columnLength), vsip_stride(rowStride), vsip_length(rowLength)) case .uc: return vsip_mbind_uc(blk, vsip_offset(offset), vsip_stride(columnStride), vsip_length(columnLength), vsip_stride(rowStride), vsip_length(rowLength)) case .bl: return vsip_mbind_bl(blk, vsip_offset(offset), vsip_stride(columnStride), vsip_length(columnLength), vsip_stride(rowStride), vsip_length(rowLength)) default: print("Not supported.") return nil } } public init(block: Block, offset: Int, columnStride: Int, columnLength: Int, rowStride: Int, rowLength: Int){ super.init(block: block, shape: .m) if let m = self.mBind(offset, columnStride: columnStride, columnLength: columnLength, rowStride: rowStride, rowLength: rowLength){ self.tryVsip = m } else { preconditionFailure("Failed to bind to a vsip matrix") } } public convenience init(columnLength :Int, rowLength: Int, type : Block.Types, major : vsip_major){ let N = rowLength * columnLength let blk = Block(length: N, type: type) if major == VSIP_COL { self.init(block: blk, offset: 0, columnStride: 1, columnLength: columnLength, rowStride: Int(columnLength), rowLength: rowLength) } else { self.init(block: blk, offset: 0, columnStride: Int(rowLength), columnLength: columnLength, rowStride: 1, rowLength: rowLength) } } // create view to hold derived subview public init(block: Block, cView: OpaquePointer){ super.init(block: block, shape: .m) self.tryVsip = cView } deinit{ let t = self.block.type let id = self.myId.int32Value switch t { case .f: vsip_mdestroy_f(self.vsip) if _isDebugAssertConfiguration(){ print("deinit mdestroy_f \(id)") } case .d: vsip_mdestroy_d(self.vsip) if _isDebugAssertConfiguration(){ print("deinit mdestroy_d \(id)") } case .cf: vsip_cmdestroy_f(self.vsip) if _isDebugAssertConfiguration(){ print("deinit cmdestroy_f \(id)") } case .cd: vsip_cmdestroy_d(self.vsip) if _isDebugAssertConfiguration(){ print("cmdestroy_d id \(id)") } case .i: vsip_mdestroy_i(self.vsip) if _isDebugAssertConfiguration(){ print("mdestroy_i id \(id)") } case .li: vsip_mdestroy_li(self.vsip) if _isDebugAssertConfiguration(){ print("mdestroy_li id \(id)") } case .si: vsip_mdestroy_si(self.vsip) if _isDebugAssertConfiguration(){ print("mdestroy_si id \(id)") } case .uc: vsip_mdestroy_uc(self.vsip) if _isDebugAssertConfiguration(){ print("mdestroy_uc id \(id)") } case .bl: vsip_mdestroy_bl(self.vsip) if _isDebugAssertConfiguration(){ print("mdestroy_bl id \(id)") } default: break } } // MARK: Attributes public var offset: Int { get{ switch self.type { case .f : return Int(vsip_mgetoffset_f(self.vsip)) case .d : return Int(vsip_mgetoffset_d(self.vsip)) case .cf : return Int(vsip_cmgetoffset_f(self.vsip)) case .cd : return Int(vsip_cmgetoffset_d(self.vsip)) case .si : return Int(vsip_mgetoffset_si(self.vsip)) case .i : return Int(vsip_mgetoffset_i(self.vsip)) case .li : return Int(vsip_mgetoffset_li(self.vsip)) case .uc : return Int(vsip_mgetoffset_uc(self.vsip)) case .bl : return Int(vsip_mgetoffset_bl(self.vsip)) default: return 0 } } set(offset) { switch self.type { case .f : vsip_mputoffset_f(self.vsip, vsip_offset(offset)) case .d : vsip_mputoffset_d(self.vsip, vsip_offset(offset)) case .cf : vsip_cmputoffset_f(self.vsip, vsip_offset(offset)) case .cd : vsip_cmputoffset_d(self.vsip, vsip_offset(offset)) case .si : vsip_mputoffset_si(self.vsip, vsip_offset(offset)) case .i : vsip_mputoffset_i(self.vsip, vsip_offset(offset)) case .li : vsip_mputoffset_li(self.vsip, vsip_offset(offset)) case .uc : vsip_mputoffset_uc(self.vsip, vsip_offset(offset)) case .bl : vsip_mputoffset_bl(self.vsip, vsip_offset(offset)) default: break } } } public var rowStride: Int{ get{ switch self.type { case .f : return Int(vsip_mgetrowstride_f(self.vsip)) case .d : return Int(vsip_mgetrowstride_d(self.vsip)) case .cf : return Int(vsip_cmgetrowstride_f(self.vsip)) case .cd : return Int(vsip_cmgetrowstride_d(self.vsip)) case .i : return Int(vsip_mgetrowstride_i(self.vsip)) case .si : return Int(vsip_mgetrowstride_si(self.vsip)) case .li : return Int(vsip_mgetrowstride_li(self.vsip)) default : return 0 } } set(stride){ switch self.type{ case .f : vsip_mputrowstride_f(self.vsip,vsip_stride(stride)) case .d : vsip_mputrowstride_d(self.vsip,vsip_stride(stride)) case .cf : vsip_cmputrowstride_f(self.vsip,vsip_stride(stride)) case .cd : vsip_cmputrowstride_d(self.vsip,vsip_stride(stride)) case .i : vsip_mputrowstride_i(self.vsip,vsip_stride(stride)) case .si : vsip_mputrowstride_si(self.vsip,vsip_stride(stride)) case .li : vsip_mputrowstride_li(self.vsip,vsip_stride(stride)) default : break } } } public var columnStride: Int{ get{ switch self.type { case .f : return Int(vsip_mgetcolstride_f(self.vsip)) case .d : return Int(vsip_mgetcolstride_d(self.vsip)) case .cf : return Int(vsip_cmgetcolstride_f(self.vsip)) case .cd : return Int(vsip_cmgetcolstride_d(self.vsip)) case .i : return Int(vsip_mgetcolstride_i(self.vsip)) case .si : return Int(vsip_mgetcolstride_si(self.vsip)) case .li : return Int(vsip_mgetcolstride_li(self.vsip)) default : return 0 } } set(stride){ switch self.type{ case .f : vsip_mputcolstride_f(self.vsip,vsip_stride(stride)) case .d : vsip_mputcolstride_d(self.vsip,vsip_stride(stride)) case .cf : vsip_cmputcolstride_f(self.vsip,vsip_stride(stride)) case .cd : vsip_cmputcolstride_d(self.vsip,vsip_stride(stride)) case .i : vsip_mputcolstride_i(self.vsip,vsip_stride(stride)) case .si : vsip_mputcolstride_si(self.vsip,vsip_stride(stride)) case .li : vsip_mputcolstride_li(self.vsip,vsip_stride(stride)) default : break } } } public var rowLength: Int { get{ switch self.type { case .f : return Int(vsip_mgetrowlength_f(self.vsip)) case .d : return Int(vsip_mgetrowlength_d(self.vsip)) case .cf : return Int(vsip_cmgetrowlength_f(self.vsip)) case .cd : return Int(vsip_cmgetrowlength_d(self.vsip)) case .i : return Int(vsip_mgetrowlength_i(self.vsip)) case .si : return Int(vsip_mgetrowlength_si(self.vsip)) case .li : return Int(vsip_mgetrowlength_li(self.vsip)) default : return 0 } } set(length){ switch self.type{ case .f : vsip_mputrowlength_f(self.vsip,vsip_length(length)) case .d : vsip_mputrowlength_d(self.vsip,vsip_length(length)) case .cf : vsip_cmputrowlength_f(self.vsip,vsip_length(length)) case .cd : vsip_cmputrowlength_d(self.vsip,vsip_length(length)) case .i : vsip_mputrowlength_i(self.vsip,vsip_length(length)) case .si : vsip_mputrowlength_si(self.vsip,vsip_length(length)) case .li : vsip_mputrowlength_li(self.vsip,vsip_length(length)) default : break } } } public var columnLength: Int{ get{ switch self.type { case .f : return Int(vsip_mgetcollength_f(self.vsip)) case .d : return Int(vsip_mgetcollength_d(self.vsip)) case .cf : return Int(vsip_cmgetcollength_f(self.vsip)) case .cd : return Int(vsip_cmgetcollength_d(self.vsip)) case .i : return Int(vsip_mgetcollength_i(self.vsip)) case .si : return Int(vsip_mgetcollength_si(self.vsip)) case .li : return Int(vsip_mgetcollength_li(self.vsip)) default : return 0 } } set(length){ switch self.type{ case .f : vsip_mputcollength_f(self.vsip,vsip_length(length)) case .d : vsip_mputcollength_d(self.vsip,vsip_length(length)) case .cf : vsip_cmputcollength_f(self.vsip,vsip_length(length)) case .cd : vsip_cmputcollength_d(self.vsip,vsip_length(length)) case .i : vsip_mputcollength_i(self.vsip,vsip_length(length)) case .si : vsip_mputcollength_si(self.vsip,vsip_length(length)) case .li : vsip_mputcollength_li(self.vsip,vsip_length(length)) default : break } } } public var real: Matrix { get{ let ans = super.real(self.vsip) // C VSIP real view let blk = ans.0 let v = ans.1 return Matrix(block: blk, cView: v) } } public var imag: Matrix{ get{ let ans = super.imag(self.vsip) // C VSIP imag view let blk = ans.0! let v = ans.1! return Matrix(block: blk, cView: v) } } subscript(rowIndex: Int, columnIndex: Int) -> (Block.Types?, NSNumber?, NSNumber?){ get{ return super.get(self.vsip, rowIndex: vsip_index(rowIndex), columnIndex: vsip_index(columnIndex)) } set(value){ super.put(self.vsip, rowIndex: vsip_index(rowIndex), columnIndex: vsip_index(columnIndex), value: value) } } subscript() -> (Block.Types?, NSNumber?, NSNumber?){ get{ return self[0,0] } set(value){ self.fill(value) } } // MARK: Data Generators public func fill(_ value: (Block.Types?, NSNumber?, NSNumber?)){ switch self.type{ case .d: vsip_mfill_d(value.1!.doubleValue,self.vsip) case .f: vsip_mfill_f(value.1!.floatValue,self.vsip) case .cd: vsip_cmfill_d(vsip_cmplx_d(value.1!.doubleValue,value.2!.doubleValue),self.vsip) case .cf: vsip_cmfill_f(vsip_cmplx_f(value.1!.floatValue,value.2!.floatValue),self.vsip) case .i: vsip_mfill_i(value.1!.int32Value,self.vsip) case .li: vsip_mfill_li(value.1!.intValue,self.vsip) case .si: vsip_mfill_si(value.1!.int16Value,self.vsip) case .uc: vsip_mfill_uc(value.1!.uint8Value,self.vsip) default: break } } public func fill(_ value: NSNumber){ switch self.type{ case .d: vsip_mfill_d(value.doubleValue,self.vsip) case .f: vsip_mfill_f(value.floatValue,self.vsip) case .cd: vsip_cmfill_d(vsip_cmplx_d(value.doubleValue,0.0),self.vsip) case .cf: vsip_cmfill_f(vsip_cmplx_f(value.floatValue,0.0),self.vsip) case .i: vsip_mfill_i(value.int32Value,self.vsip) case .li: vsip_mfill_li(value.intValue,self.vsip) case .si: vsip_mfill_si(value.int16Value,self.vsip) case .uc: vsip_mfill_uc(value.uint8Value,self.vsip) default: break } } public func fill(_ value: vsip_cscalar_d){ self.fill((Block.Types.cd, NSNumber(value: value.r), NSNumber(value: value.i))) } public func fill(_ value: vsip_cscalar_f){ self.fill((Block.Types.cd, NSNumber(value: value.r), NSNumber(value: value.i))) } public func randn(_ seed: vsip_index, portable: Bool) -> Matrix{ let state = Vsip.Rand(seed: seed, portable: portable) state.randn(self) return self } public func randu(_ seed: vsip_index, portable: Bool) -> Matrix{ let state = Vsip.Rand(seed: seed, portable: portable) state.randu(self) return self } // MARK: Views, Sub-Views, Copies, Clones and convenience creaters. // create empty Matrix of same type and view size. New data space created, created as row major public var empty: Matrix{ return Matrix(columnLength: self.columnLength, rowLength: self.rowLength, type: self.type, major: VSIP_ROW) } public func empty(_ type: Block.Types) -> Matrix{ return Matrix(columnLength: self.columnLength, rowLength: self.rowLength, type: type, major: VSIP_ROW) } // copy is new data space, view of same size, copy of data public var copy: Matrix { let view = self.empty switch view.type{ case .f: vsip_mcopy_f_f(self.vsip,view.vsip) case .d: vsip_mcopy_d_d(self.vsip, view.vsip) case .cf: vsip_cmcopy_f_f(self.vsip,view.vsip) case .cd: vsip_cmcopy_d_d(self.vsip, view.vsip) case .i: vsip_mcopy_i_i(self.vsip,view.vsip) default: break } return view } public func copy(_ output: Matrix) -> Matrix{ let t = (self.type, output.type) switch t{ case (.f,.f): vsip_mcopy_f_f(self.vsip,output.vsip) case (.f,.cf): let r = output.real;let i = output.real vsip_mcopy_f_f(self.vsip,r.vsip) vsip_mfill_f(0.0,i.vsip) case (.d,.d): vsip_mcopy_d_d(self.vsip,output.vsip) case (.d,.cd): let r = output.real;let i = output.real vsip_mcopy_d_d(self.vsip,r.vsip) vsip_mfill_d(0.0,i.vsip) case (.d,.f): vsip_mcopy_d_f(self.vsip,output.vsip) case (.f,.d): vsip_mcopy_f_d(self.vsip,output.vsip) case (.i,.f): vsip_mcopy_i_f(self.vsip,output.vsip) case (.i,.i): vsip_mcopy_i_i(self.vsip, output.vsip) case (.si,.f): vsip_mcopy_si_f(self.vsip, output.vsip) default: break } return output } // clone is same data space just new view public var clone: Matrix { return Matrix(block: self.block, offset: self.offset, columnStride: self.columnStride, columnLength: self.columnLength, rowStride: self.rowStride, rowLength: self.rowLength) } // transview is new view of same data space as a transpose. public var transview: Matrix { return Matrix(block: self.block, offset: self.offset, columnStride: self.rowStride, columnLength: self.rowLength, rowStride: self.columnStride, rowLength: self.columnLength) } private func diagview(diagIndex: Int) -> Vector { let blk = self.block switch self.type { case .f: if let v = vsip_mdiagview_f(self.vsip, vsip_stride(diagIndex)) { return Vector(block: blk, cView: v) } else { break } case .d: if let v = vsip_mdiagview_d(self.vsip, vsip_stride(diagIndex)){ return Vector(block: blk, cView: v) } else { break } case .cf: if let v = vsip_cmdiagview_f(self.vsip, vsip_stride(diagIndex)){ return Vector(block: blk, cView: v) } else { break } case .cd: if let v = vsip_cmdiagview_d(self.vsip, vsip_stride(diagIndex)){ return Vector(block: blk, cView: v) } else { break } case .i: if let v = vsip_mdiagview_i(self.vsip, vsip_stride(diagIndex)){ return Vector(block: blk, cView: v) } else { break } case .li: if let v = vsip_mdiagview_li(self.vsip, vsip_stride(diagIndex)){ return Vector(block: blk, cView: v) } else { break } case .si: if let v = vsip_mdiagview_si(self.vsip, vsip_stride(diagIndex)){ return Vector(block: blk, cView: v) } else { break } case .uc: if let v = vsip_mdiagview_uc(self.vsip, vsip_stride(diagIndex)){ return Vector(block: blk, cView: v) } else { break } case .bl: if let v = vsip_mdiagview_bl(self.vsip, vsip_stride(diagIndex)){ return Vector(block: blk, cView: v) } else { break } default: print("diagview not available for this view") } preconditionFailure("Failed to return valid vsip diagview") } public var diagview: Vector { return self.diagview(diagIndex: 0) } // MARK: Print public func mString(_ format: String) -> String { let fmt = formatFmt(format) var retval = "" let m = self.columnLength - 1 let n = self.rowLength - 1 for i in 0...m{ retval += (i == 0) ? "[" : " " for j in 0...n{ retval += super.scalarString(fmt, value: self[i,j]) if j < n { retval += ", " } } retval += (i == m) ? "]\n" : ";\n" } return retval } public func mPrint(_ format: String){ let m = mString(format) print(m) } } <file_sep>/* Created RJudd March 18, 2012 */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"vsip.h" #include"VI_mrowview_d.h" #include"VI_mcolview_d.h" #include"VI_cmrowview_d.h" #include"VI_cmcolview_d.h" static void vcmplx_d(const vsip_vview_d* a, const vsip_vview_d* b, const vsip_cvview_d* r) { vsip_length n = r->length; vsip_stride crst = r->block->cstride; vsip_scalar_d *ap = (vsip_scalar_d*) (a->block->array) + a->offset * a->block->rstride, *bp = (vsip_scalar_d*) (b->block->array) + b->offset * b->block->rstride, *rpr = (vsip_scalar_d*) ((r->block->R->array) + crst * r->offset), *rpi = (vsip_scalar_d*) ((r->block->I->array) + crst * r->offset); vsip_scalar_d temp; vsip_stride ast = a->stride * a->block->rstride, bst = b->stride * b->block->rstride, rst = crst * r->stride; while(n-- > 0){ temp = *ap; *rpi = *bp; *rpr = temp; ap += ast; bp += bst; rpr += rst; rpi += rst; } } void vsip_mcmplx_d(const vsip_mview_d* a, const vsip_mview_d* b, const vsip_cmview_d* r){ vsip_index i; vsip_vview_d av; vsip_vview_d bv; vsip_cvview_d rv; if(a->row_stride < a->col_stride){ for(i=0; i < a->col_length; i++){ VI_mrowview_d(a,i,&av); VI_mrowview_d(b,i,&bv);VI_cmrowview_d(r,i,&rv); vcmplx_d(&av,&bv,&rv); } } else { for(i=0; i < a->col_length; i++){ VI_mcolview_d(a,i,&av); VI_mcolview_d(b,i,&bv);VI_cmcolview_d(r,i,&rv); vcmplx_d(&av,&bv,&rv); } } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_stride_si.h,v 2.1 2007/04/18 17:05:56 judd Exp $ */ static void get_put_stride_si(void){ printf("********\nTEST get_put_stride_si\n"); { vsip_offset ivo = 3; vsip_stride ivs = 2; vsip_length ivl = 3; vsip_stride jvs = 3; vsip_stride irs = 1, ics = 3; vsip_length irl = 2, icl = 3; vsip_stride jrs = 5, jcs = 2; vsip_stride ixs = 2, iys = 4, izs = 14; vsip_length ixl = 2, iyl = 3, izl = 4; vsip_stride jxs = 4, jys = 14, jzs = 2; vsip_block_si *b = vsip_blockcreate_si(80,VSIP_MEM_NONE); vsip_vview_si *v = vsip_vbind_si(b,ivo,ivs,ivl); vsip_mview_si *m = vsip_mbind_si(b,ivo,ics,icl,irs,irl); vsip_tview_si *t = vsip_tbind_si(b,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_stride s; printf("test vgetstride_si\n"); fflush(stdout); { s = vsip_vgetstride_si(v); (s == ivs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputstride_si\n"); fflush(stdout); { vsip_vputstride_si(v,jvs); s = vsip_vgetstride_si(v); (s == jvs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /*************************************************************************/ printf("test mgetrowstride_si\n"); fflush(stdout); { s = vsip_mgetrowstride_si(m); (s == irs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputrowstride_si\n"); fflush(stdout); { vsip_mputrowstride_si(m,jrs); s = vsip_mgetrowstride_si(m); (s == jrs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test mgetcolstride_si\n"); fflush(stdout); { s = vsip_mgetcolstride_si(m); (s == ics) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputcolstride_si\n"); fflush(stdout); { vsip_mputcolstride_si(m,jcs); s = vsip_mgetcolstride_si(m); (s == jcs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /*************************************************************************/ printf("test tgetxstride_si\n"); fflush(stdout); { s = vsip_tgetxstride_si(t); (s == ixs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputxstride_si\n"); fflush(stdout); { vsip_tputxstride_si(t,jxs); s = vsip_tgetxstride_si(t); (s == jxs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test tgetystride_si\n"); fflush(stdout); { s = vsip_tgetystride_si(t); (s == iys) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputystride_si\n"); fflush(stdout); { vsip_tputystride_si(t,jys); s = vsip_tgetystride_si(t); (s == jys) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } printf("test tgetzstride_si\n"); fflush(stdout); { s = vsip_tgetzstride_si(t); (s == izs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputzstride_si\n"); fflush(stdout); { vsip_tputzstride_si(t,jzs); s = vsip_tgetzstride_si(t); (s == jzs) ? printf("stride correct\n") : printf("stride error \n"); fflush(stdout); } vsip_vdestroy_si(v); vsip_mdestroy_si(m); vsip_talldestroy_si(t); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mcumsum_si.c,v 2.1 2004/04/03 14:19:04 judd Exp $ */ #include"vsip.h" #include"vsip_mviewattributes_si.h" #include"VI_mcolview_si.h" #include"VI_mrowview_si.h" #include"VI_vcumsum_si.h" void vsip_mcumsum_si( const vsip_mview_si *a, vsip_major major, const vsip_mview_si *r) { { vsip_vview_si *va,vaa; vsip_vview_si *vr,vrr; vsip_index i; vsip_length m = a->col_length; vsip_length n = a->row_length; va = &vaa; vr = &vrr; if(major == VSIP_ROW){ for(i=0; i<m; i++){ VI_mrowview_si(a,i,va); VI_mrowview_si(r,i,vr); VI_vcumsum_si(va,vr); } } else { /* must be VSIP_COL */ for(i=0; i<n; i++){ VI_mcolview_si(a,i,va); VI_mcolview_si(r,i,vr); VI_vcumsum_si(va,vr); } } } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D881 */ #ifndef _vsip_cfirattributes_d_h #define _vsip_cfirattributes_d_h 1 #include"VI.h" struct vsip_cfirattributes_d{ vsip_cvview_d *h; vsip_cvview_d *s; vsip_length N; vsip_length M; vsip_length p; vsip_length D; int ntimes; vsip_symmetry symm; vsip_alg_hint hint; vsip_obj_state state; }; #endif /* _vsip_cfirattributes_d_h */ <file_sep>vsip_mview_d * VU_strass_d(vsip_mview_d *A, vsip_mview_d *B, vsip_mview_d *C){ vsip_length n=vsip_mgetrowlength_d(A); if((n % 2) | (n < 129)){ vsip_mprod_d(A,B,C); } else { vsip_mview_d *A00=vsip_mcloneview_d(A); vsip_mview_d *Aij=vsip_mcloneview_d(A); vsip_mview_d *Ai0=vsip_mcloneview_d(A); vsip_mview_d *A0j=vsip_mcloneview_d(A); vsip_mview_d *B00=vsip_mcloneview_d(B); vsip_mview_d *Bij=vsip_mcloneview_d(B); vsip_mview_d *Bi0=vsip_mcloneview_d(B); vsip_mview_d *B0j=vsip_mcloneview_d(B); vsip_mview_d *C00=vsip_mcloneview_d(C); vsip_mview_d *Cij=vsip_mcloneview_d(C); vsip_mview_d *Ci0=vsip_mcloneview_d(C); vsip_mview_d *C0j=vsip_mcloneview_d(C); vsip_length m=n/2; vsip_index i=(vsip_index) m, j=i; vsip_mview_d *P1=vsip_mcreate_d(m,m,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *P2=vsip_mcreate_d(m,m,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *P3=vsip_mcreate_d(m,m,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *P4=vsip_mcreate_d(m,m,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *P5=vsip_mcreate_d(m,m,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *P6=vsip_mcreate_d(m,m,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *P7=vsip_mcreate_d(m,m,VSIP_ROW,VSIP_MEM_NONE); VU_MGETSUB_D(A,A00,0,0,1,1,m,m);VU_MGETSUB_D(A,A0j,0,j,1,1,m,m); VU_MGETSUB_D(A,Ai0,i,0,1,1,m,m);VU_MGETSUB_D(A,Aij,i,j,1,1,m,m); VU_MGETSUB_D(B,B00,0,0,1,1,m,m);VU_MGETSUB_D(B,B0j,0,j,1,1,m,m); VU_MGETSUB_D(B,Bi0,i,0,1,1,m,m);VU_MGETSUB_D(B,Bij,i,j,1,1,m,m); VU_MGETSUB_D(C,C00,0,0,1,1,m,m);VU_MGETSUB_D(C,C0j,0,j,1,1,m,m); VU_MGETSUB_D(C,Ci0,i,0,1,1,m,m);VU_MGETSUB_D(C,Cij,i,j,1,1,m,m); vsip_madd_d(A00,Aij,C00); vsip_madd_d(B00,Bij,Cij); VU_strass_d(C00,Cij,P1); vsip_madd_d(Ai0,Aij,C00); VU_strass_d(C00,B00,P2); vsip_msub_d(B0j,Bij,C00); VU_strass_d(A00,C00,P3); vsip_msub_d(Bi0,Bij,C00); VU_strass_d(Aij,C00,P4); vsip_madd_d(A00,A0j,C00); VU_strass_d(C00,Bij,P5); vsip_msub_d(Ai0,A00,C00); vsip_madd_d(B00,B0j,Cij); VU_strass_d(C00,Cij,P6); vsip_msub_d(A0j,Aij,C00); vsip_madd_d(Bi0,Bij,Cij); VU_strass_d(C00,Cij,P7); vsip_madd_d(P1,P4,C00);vsip_msub_d(C00,P5,C00); vsip_madd_d(C00,P7,C00); vsip_madd_d(P3,P5,C0j); vsip_madd_d(P2,P4,Ci0); vsip_madd_d(P1,P3,Cij); vsip_msub_d(Cij,P2,Cij); vsip_madd_d(Cij,P6,Cij); vsip_mdestroy_d(C00); vsip_mdestroy_d(Cij); vsip_mdestroy_d(Ci0); vsip_mdestroy_d(C0j); vsip_mdestroy_d(A00); vsip_mdestroy_d(Ai0); vsip_mdestroy_d(A0j);vsip_mdestroy_d(Aij); vsip_mdestroy_d(B00); vsip_mdestroy_d(Bi0); vsip_mdestroy_d(B0j);vsip_mdestroy_d(Bij); } return C; <file_sep>// // main.cpp // test2 // // Created by <NAME> on 4/26/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #include <iostream> #include <string> #include <cassert> extern "C"{ #include <vsip.h> } using namespace std; int main(int argc, const char * argv[]) { // insert code here... assert(!vsip_init((void*)0)); vsip_vview_f *aView = vsip_vcreate_f(100,VSIP_MEM_NONE); vsip_vfill_f(1.2,aView); cout << vsip_vget_f(aView, 10) << endl; vsip_vramp_f(0,.1,aView); for(int i=5; i<10; i++) cout << to_string(vsip_vget_f(aView, i)) << endl; vsip_valldestroy_f(aView); vsip_finalize((void*)0); return 0; } <file_sep>/* Created RJudd March 18, 2012 */ /********************************************************************* // This code includes / // no warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose. / // No person or entity / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ #include"vsip.h" #include"vsip_rcfirattributes_d.h" #include"VI_valldestroy_d.h" #include"VI_cvalldestroy_d.h" int vsip_rcfir_destroy_d( vsip_rcfir_d* filt) { if(filt != NULL){ VI_valldestroy_d(filt->h); VI_cvalldestroy_d(filt->s); free((void*) filt); } return 0; } <file_sep>/* Created RJudd March 12, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cvouter_f.c,v 2.1 2004/05/16 05:01:48 judd Exp $ */ /* April 20, 1998 1,2 to row,col */ /* Modified RJudd Feb 14, 1999 */ /* to fix cmbind */ /* Removed Development Mode RJudd Sept 00 */ #include"vsip.h" #include"vsip_cvviewattributes_f.h" #include"vsip_cmviewattributes_f.h" void (vsip_cvouter_f)( vsip_cscalar_f alpha, const vsip_cvview_f* a, const vsip_cvview_f* b, const vsip_cmview_f* R) { /* R_ij = a_i * conj(b_j) */ if((a->block == b->block) && (a->offset == b->offset) && (alpha.i == 0)){ /* covariance matrix with real multiplier */ vsip_length n = a->length; vsip_stride cRst = R->block->cstride, cast = a->block->cstride; vsip_scalar_f *a_pr = (vsip_scalar_f*)(a->block->R->array + cast * a->offset), *a_pi = (vsip_scalar_f*)(a->block->I->array + cast * a->offset); vsip_length i,j; vsip_stride stRu = cRst * R->row_stride, /* upper stride (above diagonal) */ stRl = cRst * R->col_stride, /* lower stride (below diagonal) */ sta = cast * a->stride; /* stride of a (and b) */ vsip_offset Ro = cRst * R->offset, Rdiag = cRst * (R->col_stride + R->row_stride); vsip_scalar_f *R_pr = (vsip_scalar_f*)(R->block->R->array + Ro), *R_pi = (vsip_scalar_f*)(R->block->I->array + Ro); for(i=0; i<n; i++){ /* prep for next loop */ vsip_scalar_f *R_plr = R_pr + stRl, /* pointer to lower real */ *R_pli = R_pi + stRl, /* pointer to lower imaginary */ *R_pur = R_pr + stRu, /* pointer to upper real */ *R_pui = R_pi + stRu; /* pointer to upper imaginary */ vsip_scalar_f atmp_r = *a_pr * alpha.r; vsip_scalar_f atmp_i = *a_pi * alpha.r; vsip_scalar_f *b_pr = a_pr + sta, *b_pi = a_pi + sta; /* do diagonal member */ *(R_pr) = (atmp_r * *a_pr + atmp_i * *a_pi); *(R_pi) = 0; R_pr += Rdiag; R_pi += Rdiag; for(j=i+1; j<n; j++){ /* do other members, along row for upper, column for lower */ vsip_scalar_f tmp = (atmp_r * *b_pr + atmp_i * *b_pi); *R_plr = tmp; *R_pur = tmp; tmp = (atmp_i * *b_pr - atmp_r * *b_pi); *R_pli = -tmp; *R_pui = tmp; R_plr += stRl; R_pli += stRl; R_pur += stRu; R_pui += stRu; b_pr += sta; b_pi += sta; } a_pr += sta; a_pi += sta; } } else { vsip_length n = a->length, m = b->length; vsip_stride cRst = R->block->cstride, cast = a->block->cstride, cbst = b->block->cstride; vsip_scalar_f *a_pr = (vsip_scalar_f*)(a->block->R->array + cast * a->offset), *a_pi = (vsip_scalar_f*)(a->block->I->array + cast * a->offset); vsip_length i,j; vsip_stride stR = cRst * R->row_stride, sta = cast * a->stride, stb = cbst * b->stride; vsip_offset Ro = cRst * R->offset, Rco = cRst * R->col_stride, bo = cbst * b->offset; for(i=0; i<n; i++){ vsip_scalar_f *R_pr = (vsip_scalar_f*)(R->block->R->array + Ro + i * Rco), *R_pi = (vsip_scalar_f*)(R->block->I->array + Ro + i * Rco), *b_pr = (vsip_scalar_f*)(b->block->R->array + bo), *b_pi = (vsip_scalar_f*)(b->block->I->array + bo); vsip_cscalar_f temp = vsip_cmul_f(alpha,vsip_cmplx_f(*a_pr,*a_pi)); for(j=0; j<m; j++){ *R_pr = (temp.r * *b_pr + temp.i * *b_pi); *R_pi = (temp.i * *b_pr - temp.r * *b_pi); R_pr += stR; b_pr += stb; R_pi += stR; b_pi += stb; } a_pr += sta; a_pi += sta; } } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mmul_d.h,v 2.0 2003/02/22 15:23:26 judd Exp $ */ #include"VU_mprintm_d.include" static void mmul_d(void){ printf("\n******\nTEST mmul_d\n"); { vsip_scalar_d data1[]= {1, 2, 3, 4, 5, 6, 7, 8, 9}; vsip_scalar_d data2[]= {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9}; vsip_scalar_d ans[] = {1.1, 8.8, 23.1, 8.8, 27.5, 52.8, 23.1, 52.8, 89.1}; vsip_mview_d *m1 = vsip_mbind_d( vsip_blockbind_d(data1,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_mview_d *m2 = vsip_mbind_d( vsip_blockbind_d(data2,9,VSIP_MEM_NONE),0,1,3,3,3); vsip_mview_d *ma = vsip_mbind_d( vsip_blockbind_d(ans,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_mview_d *m3 = vsip_mcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); /* vsip_mview_d *m2T = vsip_mtransview_d(m2); */ vsip_blockadmit_d(vsip_mgetblock_d(m1),VSIP_TRUE); vsip_blockadmit_d(vsip_mgetblock_d(m2),VSIP_TRUE); vsip_blockadmit_d(vsip_mgetblock_d(ma),VSIP_TRUE); printf("input matrix m1\n");VU_mprintm_d("6.4",m1); printf("input matrix m2\n");VU_mprintm_d("6.4",m2); vsip_mmul_d(m1,m2,m3); printf("output matrix vsip_mmul_d(m1,m2,m3)\n");VU_mprintm_d("6.4",m3); printf("\nanswer should be\n"); VU_mprintm_d("6.4",ma); vsip_msub_d(ma,m3,m3); if(fabs(vsip_msumval_d(m3)) > .0001){ printf("error\n"); }else{ printf("correct\n"); } vsip_malldestroy_d(m1); vsip_malldestroy_d(m2); vsip_malldestroy_d(m3); vsip_malldestroy_d(ma); } /* VU_mprintm_d("6.4",m3); */ /* VU_mprintm_d("6.4",m1); */ /* VU_mprintm_d("6.4",m2T); */ /* vsip_mmul_d(m1,m2T,m3); */ /* VU_mprintm_d("6.4",m3); */ return; } <file_sep>## Created RJudd ## use gnu's make if possible MAKE=make ## Any ansi C compiler here CC=gcc ## Options are compiler dependent but I think these are fairly standard CFLAGS=-O3 -Wall -std=c89 -pedantic ## Archiver AR=ar ## Archiver options AR_OPTIONS=rcvs ARLIB=libvsip.a SRC=c_VSIP_src MKDIR := mkdir -p INCLUDE:=include LIB:=lib vsip: (cd $(SRC); $(MAKE) MAKE='$(MAKE)' CC='$(CC)' CFLAGS='$(CFLAGS)'; \ AR='$(AR)' AR_OPTIONS='$(AR_OPTIONS)' ARLIB='$(ARLIB)';) if test -d $(LIB); then echo '$(LIB) exists'; else $(MKDIR) $(LIB); fi if test -d $(INCLUDE); then echo '$(INCLUDE) exists'; else $(MKDIR) $(INCLUDE); fi if test $(SRC)/$(ARLIB); then cp $(SRC)/$(ARLIB) $(LIB)/$(ARLIB); fi cp $(SRC)/vsip.h $(INCLUDE)/vsip.h clean: (cd $(SRC); $(MAKE) clean) cleanall: (cd $(SRC); $(MAKE) cleanall) sterile: (cd $(SRC); $(MAKE) cleanall) rm -rf $(INCLUDE) rm -rf $(LIB) <file_sep>/* Created R Judd */ /* Copyright (c) 2006 <NAME> */ /* MIT style license, see Copyright notice in top level directory */ /* $Id: covsol_f.h,v 1.2 2006/05/16 16:45:18 judd Exp $ */ #include"VU_mprintm_f.include" static int covsol_f(void) { vsip_mview_f *A = vsip_mcreate_f(10,6,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *BX = vsip_mcreate_f(6,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *B = vsip_mcreate_f(6,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *X = vsip_mcreate_f(6,3,VSIP_ROW,VSIP_MEM_NONE); vsip_vview_f *ad = vsip_mdiagview_f(A,0); vsip_vview_f *ac = vsip_mcolview_f(A,0); vsip_vview_f *bxr = vsip_mrowview_f(BX,0); vsip_mview_f *ATA = vsip_mcreate_f(6,6,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *AT = vsip_mtransview_f(A); int i; vsip_chol_f *chol = vsip_chold_create_f(VSIP_TR_LOW,6); vsip_block_f *ablock = vsip_blockcreate_f(500,VSIP_MEM_NONE); vsip_mview_f *A1 = vsip_mbind_f(ablock,200,-3,10,-31,6); vsip_mview_f *BX1 = vsip_mbind_f(ablock,203,8,6,2,3); vsip_mfill_f(0.0,A); vsip_mfill_f(0.0,BX); vsip_mfill_f(0.0,ATA); printf("********\nTEST covsol_f\n"); printf("\n Test vsip_covsol_f\n"); /* need to make up some data */ for(i=0; i<6; i++){ vsip_vputoffset_f(ac,i); vsip_vputoffset_f(bxr,i*3); vsip_vramp_f(.1,(vsip_scalar_f)i/3.0,bxr); vsip_vramp_f(-1.3,1.1,ac); } vsip_vramp_f(3,1.2,ad); vsip_mprod_f(AT,A,ATA); vsip_mcopy_f_f(BX,B); vsip_mcopy_f_f(BX,BX1); vsip_mcopy_f_f(A,A1); /* check input data */ printf("Input Data \n"); printf("A = ");VU_mprintm_f("4.2",A); printf("\nAT * A = ");VU_mprintm_f("4.2",ATA); printf("\nB = ");VU_mprintm_f("4.2",B); /* slove using Cholesky and ATA matrix */ printf("\nSolve using cholesky and ATA matrix \n (AT * A) X = B \nfor X"); vsip_chold_f(chol,ATA); vsip_cholsol_f(chol,BX); vsip_mcopy_f_f(BX,X); printf("\nX = ");VU_mprintm_f("7.5",X); /* check */ printf("\ncheck"); vsip_mprod_f(AT,A,ATA); vsip_mprod_f(ATA,X,BX); printf("\nATA * X ="); VU_mprintm_f("4.2",BX); vsip_msub_f(B,BX,X); { float check = (float) vsip_msumval_f(X); if(fabs(check) < .0001) printf("check = %f\ncorrect\n",check); else printf("check = %f\nerror\n",check); } /* slove using covsol and A matrix*/ vsip_mcopy_f_f(B,BX); /* restore BX */ printf("\nSolve\n (AT * A) X = B \nfor X"); vsip_covsol_f(A,BX); vsip_mcopy_f_f(BX,X); printf("\nX = ");VU_mprintm_f("7.5",X); vsip_mprod_f(ATA,X,BX); printf("\nATA * X ="); VU_mprintm_f("4.2",BX); vsip_msub_f(B,BX,X); { float check = (float) vsip_msumval_f(X); if(fabs(check) < .0001) printf("check = %f\ncorrect\n",check); else printf("check = %f\nerror\n",check); } /* slove using covsol and A1,BX1 inputs */ printf("\nSolve nonstandard stride _f \n (AT * A) X = B \nfor X"); vsip_covsol_f(A1,BX1); vsip_mcopy_f_f(BX1,X); printf("\nX = ");VU_mprintm_f("7.5",X); vsip_mprod_f(ATA,X,BX); printf("\nATA * X ="); VU_mprintm_f("4.2",BX); vsip_msub_f(B,BX,X); { float check = (float) vsip_msumval_f(X); if(fabs(check) < .0001) printf("check = %f\ncorrect\n",check); else printf("check = %f\nerror\n",check); } vsip_mdestroy_f(A1); vsip_mdestroy_f(BX1); vsip_blockdestroy_f(ablock); vsip_vdestroy_f(ad); vsip_vdestroy_f(ac); vsip_vdestroy_f(bxr); vsip_mdestroy_f(AT); vsip_malldestroy_f(A); vsip_malldestroy_f(BX); vsip_malldestroy_f(X); vsip_malldestroy_f(B); vsip_malldestroy_f(ATA); vsip_chold_destroy_f(chol); return 0; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cmfill_d.h,v 2.0 2003/02/22 15:23:21 judd Exp $ */ #include"VU_cmprintm_d.include" static void cmfill_d(void){ printf("\n******\nTEST cmfill_d\n"); { vsip_cscalar_d alpha = vsip_cmplx_d(5.5,-1.5); vsip_scalar_d ans_r[] = { 5.5, 5.5, 5.5, 5.5, 5.5, 5.5, 5.5, 5.5}; vsip_scalar_d ans_i[] = { -1.5, -1.5, -1.5, -1.5, -1.5, -1.5, -1.5, -1.5}; vsip_cmview_d *ans = vsip_cmbind_d( vsip_cblockbind_d(ans_r,ans_i,8,VSIP_MEM_NONE),0,2,4,1,2); vsip_cmview_d *b = vsip_cmcreate_d(4,2,VSIP_COL,VSIP_MEM_NONE); vsip_cmview_d *chk = vsip_cmcreate_d(4,2,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *chk_r = vsip_mrealview_d(chk); vsip_cblockadmit_d(vsip_cmgetblock_d(ans),VSIP_TRUE); printf("alpha = %f %+fi\n",vsip_real_d(alpha),vsip_imag_d(alpha)); printf("vsip_cmfill_d(alpha,b)\n"); vsip_cmfill_d(alpha,b); printf("b =\n");VU_cmprintm_d("8.6",b); printf("\nright answer =\n"); VU_cmprintm_d("6.4",ans); vsip_cmsub_d(ans,b,chk); vsip_cmmag_d(chk,chk_r); vsip_mclip_d(chk_r,0,2 * .0001,0,1,chk_r); if(fabs(vsip_msumval_d(chk_r)) > .5) printf("error\n"); else printf("correct\n"); vsip_cmalldestroy_d(b); vsip_cmalldestroy_d(ans); vsip_mdestroy_d(chk_r); vsip_cmalldestroy_d(chk); } return; } <file_sep>/* Created RJudd January 4, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vpolar_d.c,v 2.0 2003/02/22 15:19:17 judd Exp $ */ /* Modified RJudd June 28, 1998 */ /* to add complex block support */ /* Modified RJudd January 3, 1998 */ /* to incorporate rstride */ /* Removed Tisdale error checking Sept 00 */ #include"vsip.h" #include"vsip_vviewattributes_d.h" #include"vsip_cvviewattributes_d.h" void vsip_vpolar_d( const vsip_cvview_d* a, const vsip_vview_d* r, const vsip_vview_d* t) { vsip_length n = r->length; vsip_stride cast = a->block->cstride, rrst = r->block->rstride, trst = t->block->rstride; vsip_scalar_d *apr = (vsip_scalar_d*) ((a->block->R->array) + cast * a->offset), *rp = (vsip_scalar_d*) ((r->block->array) + rrst * r->offset), *tp = (vsip_scalar_d*) ((t->block->array) + trst * t->offset); vsip_scalar_d *api = (vsip_scalar_d*) ((a->block->I->array) + cast * a->offset); vsip_scalar_d tmp; vsip_stride ast = (cast * a->stride), rst = rrst * r->stride, tst = trst * t->stride; while(n-- > 0){ tmp = (vsip_scalar_d)atan2(*api,*apr); *rp = (vsip_scalar_d)sqrt(*apr * *apr + *api * *api); *tp = tmp; apr += ast; api += ast; rp += rst; tp += tst; } } <file_sep>import pyJvsip as pv from math import pi as M_PI from math import cos as cos def view_store(M,fname): #VU_mprintgram assert 'pyJvsip' in repr(M),'First input argument must be a pyJvsip view' assert M.type in ['vview_f','mview_f','vview_d','mview_d'], 'View type not supported' assert isinstance(fname,str), 'File name is a string' if 'mview' in M.type: RL=M.rowlength; CL=M.collength of=open(fname,'w') of.write('%s\n'%M.type) of.write('%ld %ld\n'%(CL,RL)) for row in range(CL): for col in range(RL): of.write('%ld %ld %e\n'%(row,col,M[row,col])) of.close() else: L=M.length of=open(fname,'w') of.write('%s'%M.type) of.write('%ld'%L) for i in range(L): of.write('%ld %e'%(i,M[i])) of.close() return def view_read(fname): from pyJvsip import create as create fd=open(fname,'r') t=fd.readline().split()[0] assert t in ['vview_f','mview_f','vview_d','mview_d'], 'Type <:%s:> not supported'%t if 'mview' in t: sz=fd.readline().split() M=pv.create(t,int(sz[0]),int(sz[1])) for lin in fd: a=lin.split() r=int(a[0]);c=int(a[1]);x=float(a[2]) M[r,c]=x else: sz=fd.readline().split() M=create(t,int(sz)) for lin in fd: a=lin.split() i=int(a[0]);x=float(a[2]) M[i]=x fd.close() return M def center(gram): assert gram.rowstride == 1 assert gram.colstride == gram.rowlength if gram.collength & 1: #odd for i in range(gram.rowlength): pv.freqswap(gram.colview(i)) else: #even number of columns; use trick lngth = int(gram.collength*gram.rowlength/2) gramvec=gram.block.vector pv.swap(gramvec[lngth:],gramvec[:lngth]) return gram # scale gram to db, min 0 max 255 */ def scale(gram_data): f={'cmview_d':'mview_d','cmview_f':'mview_f'} assert gram_data.type in ['cmview_d','cmview_f'], 'gram_data must be complex float matrix' M=gram_data.collength; N=gram_data.rowlength; t=f[gram_data.type] gram=pv.create(t,M,N,'ROW') pv.cmagsq(gram_data,gram) gram += (1.0-gram.minval) gram.log10 gram *= 256.0/gram.maxval return center(gram) def noiseGen(t,alpha,Mp,Nn,Ns): """ Usage: data = noiseGen(t,alpha,Mp,Nn,Ns) where: data is a matrix of type t and size Mp by Ns) alpha is a linear array constant Mp is the number of sensors in the linear array Nn is the size of the simulated noise vector Ns is the size of the output noise field for each sensor Note the noise field is returned in data """ # program parameters from math import pi as M_PI kaiser=9 Nfilter=10 # Kernel length for noise filter Nnoise=64 # number of Simulated Noise Directions cnst1 = M_PI/Nnoise offset0 = int(alpha * Mp + 1) nv = pv.create('vview_d',2 * Nn) noise=pv.create('mview_d',Mp,Nn) kernel = pv.create('vview_d',Nfilter).kaiser(kaiser) fir = pv.FIR('fir_d',kernel,'NONE',2 * Nn,2,'YES') data = pv.create('mview_d',Mp,Ns).fill(0.0) state = pv.Rand('PRNG',15) for j in range(Nnoise): noise_j=noise.rowview(j) state.randn(nv) fir.flt(nv,noise_j) noise_j *= 12.0/float(Nnoise) #view_store(noise,'noiseData'); noise.putrowlength(Ns) for i in range(Mp): data_v = data.rowview(i) for j in range(Nnoise): noise_j=noise.rowview(j) noise_j.putoffset(offset0 +(int)( i * alpha * cos(j * cnst1))) pv.add(noise_j,data_v,data_v) #view_store(data,'Data'); return data def narrowBandGen(data,alpha,targets,Fs): """ Usage: data = narrowBandGen(data,alpha,targets,Fs) Where: data is an array of size number of sensors by samples Matrix data contains simulated noise field for array alpha is the array constant targets is a list of tuples containing simulated narrow band target information Fs is the sample rate (Hz) """ from math import pi as M_PI f={'mview_d':'vview_d','mview_f':'vview_f'} tp=data.type N=data.rowlength M=data.collength t =pv.create(f[tp],N).ramp(0,1) tt = pv.create(f[tp],N) Xim = pv.create(tp,M,M+1,'ROW') m = pv.create(f[tp],M).ramp(0,1) Xi = pv.create(f[tp],M + 1).ramp(0,M_PI/M).cos pv.outer(alpha,m,Xi,Xim) for i in range(M): data_v = data.rowview(i) for j in range(len(targets)): tgt=targets[j]; w0=float(2.0 * M_PI * tgt[0]/Fs); Theta=int(tgt[1]) sc=tgt[2] Xim_val = Xim[i,Theta] pv.ma(t,w0,-w0 * Xim_val,tt) tt.cos tt *= sc data_v += tt return data <file_sep>#include"VU_mprintm_d.include" /* Created RJudd */ /* */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mvprod4_d.h,v 2.1 2006/04/27 01:40:55 judd Exp $ */ #include"VU_mprintm_d.include" #include"VU_vprintm_d.include" static void mvprod4_d(void){ printf("********\nTEST mvprod4_d\n"); { vsip_scalar_d datav[] = {1,2,3,4}; vsip_scalar_d datam[] = { 1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4}; vsip_scalar_d ans_data[] = {10,20,30,40}; vsip_block_d *blockv = vsip_blockbind_d(datav,4,VSIP_MEM_NONE); vsip_block_d *blockm = vsip_blockbind_d(datam,16,VSIP_MEM_NONE); vsip_block_d *block_ans = vsip_blockbind_d(ans_data,4,VSIP_MEM_NONE); vsip_block_d *block = vsip_blockcreate_d(70,VSIP_MEM_NONE); vsip_vview_d *v = vsip_vbind_d(blockv,0,1,4); vsip_mview_d *m = vsip_mbind_d(blockm,0,4,4,1,4); vsip_vview_d *ans = vsip_vbind_d(block_ans,0,1,4); vsip_vview_d *b = vsip_vbind_d(block,5,-1,4); vsip_mview_d *a = vsip_mbind_d(block,50,-2,4,-8,4); vsip_vview_d *c = vsip_vbind_d(block,49,-2,4); vsip_vview_d *chk = vsip_vcreate_d(4,VSIP_MEM_NONE); vsip_blockadmit_d(blockv,VSIP_TRUE); vsip_blockadmit_d(blockm,VSIP_TRUE); vsip_blockadmit_d(block_ans,VSIP_TRUE); vsip_vcopy_d_d(v,b); vsip_mcopy_d_d(m,a); vsip_mvprod4_d(a,b,c); printf("vsip_mvprod4_d(a,b,c)\n"); printf("a\n"); VU_mprintm_d("6.4",a); printf("b\n"); VU_vprintm_d("6.4",b); printf("c\n"); VU_vprintm_d("6.4",c); printf("right answer\n"); VU_vprintm_d("6.4",ans); vsip_vsub_d(c,ans,chk); vsip_vmag_d(chk,chk); vsip_vclip_d(chk,.0001,.0001,0,1,chk); if(vsip_vsumval_d(chk) > .1) printf("error\n"); else printf("correct\n"); vsip_valldestroy_d(v); vsip_malldestroy_d(m); vsip_valldestroy_d(ans); vsip_vdestroy_d(b); vsip_mdestroy_d(a); vsip_valldestroy_d(c); vsip_valldestroy_d(chk); } return; } <file_sep>/* Created RJudd For Core January 10, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vcreate_hanning_d.c,v 2.1 2003/04/22 02:19:59 judd Exp $ */ /* Removed Tisdale error checking Sept 00 */ #include"vsip.h" #include"vsip_vviewattributes_d.h" #include"vsip_scalars.h" #include"VI_vcreate_d.h" #define twoPI 6.2831853071796 vsip_vview_d* (vsip_vcreate_hanning_d)( vsip_length N, vsip_memory_hint h) { vsip_vview_d *a; a = VI_vcreate_d(N,h); if(a == NULL) return (vsip_vview_d*)NULL; { /*define variables*/ register unsigned int n = 0; vsip_scalar_d *ap = (a->block->array) + a->offset, temp = twoPI/(N+1); /*end define*/ /* Note this is always unit stride */ while(n++ < N ){ *ap++ = 0.5 * (1 - (vsip_scalar_d)VSIP_COS_D(temp * (vsip_scalar_d) n)); } } return a; } <file_sep># run some matrices to see if the SVD works import pyJvsip as pv from decompositionUtilities import * fmt='%.5f' def checkBack(A,U,S,VH): chk=(A-U[:,0:S.length].prod(S.mmul(VH.copy.COL))).normFro print('%.7f'%chk) if chk < A.normFro/(A.rowlength * 1E10): print('SVD Decomposition appears to agree with input matrix') elif chk < A.normFro/(A.rowlength*1E5): print('SVD Decomposition appears to agree witin 5 decimal places') else: print('SVD Decomposition does not agree with input matrix') print('\nTEST') A=pv.create('cmview_d',9,7).fill(0.0) A.block.vector.realview.randn(3) A.block.vector.imagview.randn(7) U,S,VH = svd(A) checkBack(A,U,S,VH) print('Singular values are');S.mprint(fmt) print('for matrix of type ' + A.type);A.mprint(fmt) print('%.7f, %.7f'%(A.normFro,S.normFro)) print('Frobenius norm difference %.10e'%abs(A.normFro - S.normFro)) print('\nTEST') A=pv.create('cmview_f',7,7).fill(0.0) A.block.vector.realview.randn(3) A.block.vector.imagview.randn(7) A[:,0]=A[:,4]; A[:,1] = 3 * A[:,4] U,S,VH = svd(A) checkBack(A,U,S,VH) print('Singular values are');S.mprint(fmt) print('for matrix of type ' + A.type);A.mprint(fmt) print('%.7f, %.7f'%(A.normFro,S.normFro)) print('Frobenius norm difference %.10e'%abs(A.normFro - S.normFro)) print('\nTEST') A=pv.create('cmview_d',9,7).fill(0.0) A.diagview(0).randn(5) A.diagview(1).randn(7) A[2,2]=0.0; A[4,4]=0.0 U,S,VH = svd(A) checkBack(A,U,S,VH) print('Singular values are');S.mprint(fmt) print('for matrix of type ' + A.type);A.mprint(fmt) print('%.7f, %.7f'%(A.normFro,S.normFro)) print('Frobenius norm difference %.10e'%abs(A.normFro - S.normFro)) print('\nTEST') A=pv.create('mview_d',5,5).fill(0.0) A.block.vector.randn(19) U,S,VH=svd(A) checkBack(A,U,S,VH) print('Singular values are');S.mprint(fmt) print('for matrix of type ' + A.type);A.mprint(fmt) print('%.7f, %.7f'%(A.normFro,S.normFro)) print('Frobenius norm difference %.10e'%abs(A.normFro - S.normFro)) <file_sep>/* Created <NAME> March 12, 1998 */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cmprodh_f.c,v 2.0 2003/02/22 15:18:43 judd Exp $ */ /* April 20, 1998 RJudd 1,2 to row,col*/ /* vsip_cmprodh_f.c used cmprodj */ /* vsip_cmprodj_f.c used cmprod */ /* Remove Development Mode RJudd Sept 00 */ #include"vsip.h" #include"VI.h" #include"vsip_cmviewattributes_f.h" #include"vsip_cvviewattributes_f.h" void (vsip_cmprodh_f)( const vsip_cmview_f* A, const vsip_cmview_f* B, const vsip_cmview_f* R) { { vsip_length M = A->col_length, N = B->col_length; vsip_stride cRst = R->block->cstride; vsip_cscalar_f tmp; vsip_length i,j; vsip_cvview_f aa,bb,rr,*a,*b,*r; a = &aa; b = &bb; r = &rr; /* row view */ a->block = A->block; a->offset = A->offset; a->stride = A->row_stride; a->length = A->row_length; /* row view */ b->block = B->block; b->offset = B->offset; b->stride = B->row_stride; b->length = B->row_length; /* row view */ r->block = R->block; r->offset = R->offset; r->stride = R->row_stride; r->length = R->row_length; a->markings = vsip_valid_structure_object; b->markings = vsip_valid_structure_object; r->markings = vsip_valid_structure_object; for(i = 0; i < M; i++){ vsip_scalar_f *r_pr =(vsip_scalar_f*) (r->block->R->array + cRst * r->offset); vsip_scalar_f *r_pi =(vsip_scalar_f*) (r->block->I->array + cRst * r->offset); vsip_stride str = cRst * r->stride; b->offset = B->offset; for(j =0; j < N; j++){ tmp = vsip_cvjdot_f(a,b); *r_pr = tmp.r; *r_pi =tmp.i; r_pr += str; r_pi += str; b->offset += B->col_stride; } a->offset += A->col_stride; r->offset += R->col_stride; } } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_scalars.h,v 2.3 2006/10/20 16:25:38 judd Exp $ */ /* The purpose of this file is to provide an abstraction * layer for the math library used internal to vsipl funtions. * The default is the defined math library for ANSI C89, but * by changing the names of the underylying functions supporting the * macros in this file then a differnt math libary may be used even * if the function names are not the same as ANSI. This is primarily * to support both float and double precision functions. By default * only double is supported native to the math library. */ #ifndef __VSIP_SCALARS_H #define __VSIP_SCALARS_H #define VSIP_SINH_F(x) ((vsip_scalar_f) sinh(x)) #define VSIP_SINH_D(x) ((vsip_scalar_d) sinh(x)) #define VSIP_SIN_F(x) ((vsip_scalar_f) sin(x)) #define VSIP_SIN_D(x) ((vsip_scalar_d) sin(x)) #define VSIP_ASIN_F(x) ((vsip_scalar_f) asin(x)) #define VSIP_ASIN_D(x) ((vsip_scalar_d) asin(x)) #define VSIP_COSH_F(x) ((vsip_scalar_f) cosh(x)) #define VSIP_COSH_D(x) ((vsip_scalar_d) cosh(x)) #define VSIP_COS_F(x) ((vsip_scalar_f) cos(x)) #define VSIP_COS_D(x) ((vsip_scalar_d) cos(x)) #define VSIP_ACOS_F(x) ((vsip_scalar_f) acos(x)) #define VSIP_ACOS_D(x) ((vsip_scalar_d) acos(x)) #define VSIP_EXP10_F(x) ((vsip_scalar_f) pow(10.0 , (x))) #define VSIP_EXP10_D(x) ((vsip_scalar_d) pow(10.0 , (x))) #define VSIP_EXP_F(x) ((vsip_scalar_f) exp(x)) #define VSIP_EXP_D(x) ((vsip_scalar_d) exp(x)) #define VSIP_FLOOR_F(x) ((vsip_scalar_f) floor(x)) #define VSIP_FLOOR_D(x) ((vsip_scalar_d) floor(x)) #define VSIP_CEIL_F(x) ((vsip_scalar_f) ceil(x)) #define VSIP_CEIL_D(x) ((vsip_scalar_d) ceil(x)) #endif <file_sep>// // View.h // cppJvsip // // Created by <NAME> on 4/27/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #include <iostream> #include <cstring> #include "Block.h" #ifndef __cppJvsip__View__ #define __cppJvsip__View__ namespace jvsip{ class View{ string s; //shape Block *obj; void *vsipView; int count; View ramp(vsip_scalar_f s, vsip_scalar_f inc){ string typ=precision(); if(typ=="f") vsip::ramp(s, inc, (vsip_vview_f*)this->vsip()); else if(typ== "d") ramp((vsip_scalar_d) s, (vsip_scalar_d) inc); else if(typ=="i") ramp((vsip_scalar_i) s, (vsip_scalar_i) inc); else if(typ=="vi") ramp((vsip_scalar_vi) s, (vsip_scalar_vi) inc); return *this; } View ramp(vsip_scalar_d s, vsip_scalar_d inc){ string typ=precision(); if(typ=="d") vsip::ramp(s, inc, (vsip_vview_d*)this->vsip()); else if(typ== "f") ramp((vsip_scalar_f) s, (vsip_scalar_f) inc); else if(typ=="i") ramp((vsip_scalar_i) s, (vsip_scalar_i) inc); else if(typ=="vi") ramp((vsip_scalar_vi) s, (vsip_scalar_vi) inc); return *this; } View ramp(vsip_scalar_i s, vsip_scalar_i inc){ string typ=precision(); if(typ=="i") vsip::ramp(s, inc, (vsip_vview_i*)this->vsip()); else if(typ== "d") ramp((vsip_scalar_d) s, (vsip_scalar_d) inc); else if(typ=="f") ramp((vsip_scalar_f) s, (vsip_scalar_f) inc); else if(typ=="vi") ramp((vsip_scalar_vi) s, (vsip_scalar_vi) inc); return *this; } View ramp(vsip_scalar_vi s, vsip_scalar_vi inc){ string typ=precision(); if(typ=="f") vsip::ramp(s, inc, (vsip_vview_f*)this->vsip()); else if(typ== "d") ramp((vsip_scalar_d) s, (vsip_scalar_d) inc); else if(typ=="i") ramp((vsip_scalar_i) s, (vsip_scalar_i) inc); else if(typ=="vi") ramp((vsip_scalar_vi) s, (vsip_scalar_vi) inc); return *this; } public: //constructors View(Block blk,Scalar o, Scalar s, Scalar l) : s("vector") , count(0){ obj=&blk; std::string t=blk.type(); if(t== "f") {vsipView=(void*)vsip::create((vsip_block_f*)obj->vsip(),o.offset(),s.stride(),l.length());} else if (t== "d") { vsipView=(void*)vsip::create((vsip_block_d*)obj->vsip(),o.offset(),s.stride(),l.length());} else if (t== "cf"){ vsipView=(void*)vsip::create((vsip_cblock_f*)obj->vsip(),o.offset(),s.stride(),l.length());} else if (t== "cd"){ vsipView=(void*)vsip::create((vsip_cblock_d*)obj->vsip(),o.offset(),s.stride(),l.length());} else if (t== "i") { vsipView=(void*)vsip::create((vsip_block_i*)obj->vsip(),o.offset(),s.stride(),l.length());} else if (t== "vi"){ vsipView=(void*)vsip::create((vsip_block_vi*)obj->vsip(),o.offset(),s.stride(),l.length());} else{std::cout << "View precision case not found" << std::endl;exit(-1);} } View(Block blk,Scalar o, Scalar cs, Scalar cl, Scalar rs, Scalar rl) : s("matrix") , count(0){ obj=&blk; std::string t=blk.type(); if (t== "f") { vsipView=(void*)vsip::create((vsip_block_f*)obj->vsip(),o.offset(),cs.stride(),cl.length(),rs.stride(),rl.length()); } else if (t== "d") { vsipView=(void*)vsip::create((vsip_block_d*)obj->vsip(),o.offset(),cs.stride(),cl.length(),rs.stride(),rl.length()); } else if (t== "cf"){ vsipView=(void*)vsip::create((vsip_cblock_f*)obj->vsip(),o.offset(),cs.stride(),cl.length(),rs.stride(),rl.length()); } else if (t== "cd"){ vsipView=(void*)vsip::create((vsip_cblock_d*)obj->vsip(),o.offset(),cs.stride(),cl.length(),rs.stride(),rl.length()); } else if (t== "i") { vsipView=(void*)vsip::create((vsip_block_i*)obj->vsip(),o.offset(),cs.stride(),cl.length(),rs.stride(),rl.length()); }else{std::cout << "View precision case not found" << std::endl;exit(-1);} } //copy constructor View(const View& other) : s(other.s), obj(other.obj){ count++; vsipView=(other.vsipView); } ~View(){ string p=obj->p; if(count == 0){ if(s=="vector"){ if (p=="f"){destroy((vsip_vview_f*)vsipView); std::cout << "delete view f" << std::endl;} else if(p=="d"){destroy((vsip_vview_d*)vsipView); std::cout << "delete view d" << std::endl;} else if(p=="cf"){destroy((vsip_cvview_f*)vsipView); std::cout << "delete view cf" << std::endl;} else if(p=="cd"){destroy((vsip_cvview_d*)vsipView); std::cout << "delete view cd" << std::endl;} else if(p=="i") {destroy((vsip_vview_i*)vsipView); std::cout << "delete view i" << std::endl;} else if(p=="vi"){destroy((vsip_vview_d*)vsipView); std::cout << "delete view vi" << std::endl;} else exit(-1); } else { // must be matrix if(p=="f"){destroy((vsip_mview_f*)vsipView); std::cout << "delete view f" << std::endl;} else if(p=="d"){destroy((vsip_mview_d*)vsipView); std::cout << "delete view d" << std::endl;} else if(p=="cf"){destroy((vsip_cmview_f*)vsipView); std::cout << "delete view cf" << std::endl;} else if(p=="cd"){destroy((vsip_cmview_d*)vsipView); std::cout << "delete view cd" << std::endl;} else if(p=="i"){destroy((vsip_mview_i*)vsipView); std::cout << "delete view i" << std::endl;} else exit(-1); } }else count--; } void* vsip() const {return vsipView;} string type() const {return obj->t;} string precision()const {return obj->precision();} string shape() const {return s;} View ramp(Scalar s, Scalar inc){ string typ = precision(); if(typ=="f") return this->ramp(s.scalar_f(), inc.scalar_f()); else if(typ== "d") return ramp(s.scalar_d(), inc.scalar_d()); else if(typ=="i") return ramp(s.scalar_i(), inc.scalar_i()); else if(typ=="vi") return ramp(s.scalar_vi(), inc.scalar_vi()); else return *this; } Scalar operator[](Scalar i){ string typ = precision(); if(typ=="f"){ return Scalar(vsip_vget_f((vsip_vview_f*)vsip(), i.scalar_vi())); } else if(typ== "d"){ return Scalar(vsip_vget_d((vsip_vview_d*)vsip(), i.scalar_vi())); }else if(typ== "cf"){ return Scalar(vsip_cvget_f((vsip_cvview_f*)vsip(), i.scalar_vi())); }else if(typ== "cd"){ return Scalar(vsip_cvget_d((vsip_cvview_d*)vsip(), i.scalar_vi())); }else if(typ=="i"){ return Scalar(vsip_vget_i((vsip_vview_i*)vsip(), i.scalar_vi())); }else if(typ=="vi"){ return Scalar(vsip_vget_vi((vsip_vview_vi*)vsip(), i.scalar_vi())); }else{ return Scalar(0); } } Scalar offset(){ string typ = precision(); string shp = shape(); if(typ=="f" && shp == "vector"){ return Scalar(vsip_vgetoffset_f((vsip_vview_f*)vsip())); } else if(typ =="f" && shp == "matrix"){ return Scalar(vsip_mgetoffset_f((vsip_mview_f*)vsip())); } else if(typ=="cf"&& shp == "vector"){ return Scalar(vsip_cvgetoffset_f((vsip_cvview_f*)vsip())); } else if(typ=="cd"&& shp == "vector"){ return Scalar(vsip_cvgetoffset_d((vsip_cvview_d*)vsip())); } else if(typ== "d"&& shp == "vector"){ return Scalar(vsip_vgetoffset_d((vsip_vview_d*)vsip())); } else if(typ=="i"&& shp == "vector"){ return Scalar(vsip_vgetoffset_i((vsip_vview_i*)vsip())); } else if(typ=="vi"&& shp == "vector"){ return Scalar(vsip_vgetoffset_vi((vsip_vview_vi*)vsip())); } else{ return Scalar(0); } } void offset(Scalar o){ string typ = precision(); string shp = shape(); if(typ=="f" && shp == "vector"){ vsip_vputoffset_f((vsip_vview_f*)vsip(),o.offset()); } else if(typ =="f" && shp == "matrix"){ vsip_mputoffset_f((vsip_mview_f*)vsip(),o.offset()); } else if(typ=="cf"&& shp == "vector"){ vsip_cvputoffset_f((vsip_cvview_f*)vsip(),o.offset()); } else if(typ =="cf" && shp == "matrix"){ vsip_cmputoffset_f((vsip_cmview_f*)vsip(),o.offset()); } else if(typ=="cd"&& shp == "vector"){ vsip_cvputoffset_d((vsip_cvview_d*)vsip(),o.offset()); } else if(typ== "d"&& shp == "vector"){ vsip_vputoffset_d((vsip_vview_d*)vsip(),o.offset()); } else if(typ=="i"&& shp == "vector"){ vsip_vputoffset_i((vsip_vview_i*)vsip(),o.offset()); } else if(typ=="vi"&& shp == "vector"){ vsip_vputoffset_vi((vsip_vview_vi*)vsip(),o.offset()); } } Scalar length(){ string typ = precision(); if(typ=="f"){ return Scalar(vsip_vgetlength_f((vsip_vview_f*)vsip())); } else if(typ=="cf"){ return Scalar(vsip_cvgetlength_f((vsip_cvview_f*)vsip())); }else if(typ=="cd"){ return Scalar(vsip_cvgetlength_d((vsip_cvview_d*)vsip())); } else if(typ== "d"){ return Scalar(vsip_vgetlength_d((vsip_vview_d*)vsip())); }else if(typ=="i"){ return Scalar(vsip_vgetlength_i((vsip_vview_i*)vsip())); }else if(typ=="vi"){ return Scalar(vsip_vgetlength_vi((vsip_vview_vi*)vsip())); }else{ return Scalar(0); } } void length(Scalar l){ string typ = precision(); if(typ=="f"){ vsip_vputlength_f((vsip_vview_f*)vsip(),l.length()); } else if(typ=="cf"){ vsip_cvputlength_f((vsip_cvview_f*)vsip(),l.length()); }else if(typ=="cd"){ vsip_cvputlength_d((vsip_cvview_d*)vsip(),l.length()); } else if(typ== "d"){ vsip_vputlength_d((vsip_vview_d*)vsip(),l.length()); }else if(typ=="i"){ vsip_vputlength_i((vsip_vview_i*)vsip(),l.length()); }else if(typ=="vi"){ vsip_vputlength_vi((vsip_vview_vi*)vsip(),l.length()); } } Scalar stride(){ string typ = precision(); if(typ=="f"){ return Scalar(vsip_vgetstride_f((vsip_vview_f*)vsip())); } else if(typ=="cf"){ return Scalar(vsip_cvgetstride_f((vsip_cvview_f*)vsip())); }else if(typ=="cd"){ return Scalar(vsip_cvgetstride_d((vsip_cvview_d*)vsip())); } else if(typ== "d"){ return Scalar(vsip_vgetstride_d((vsip_vview_d*)vsip())); }else if(typ=="i"){ return Scalar(vsip_vgetstride_i((vsip_vview_i*)vsip())); }else if(typ=="vi"){ return Scalar(vsip_vgetstride_vi((vsip_vview_vi*)vsip())); }else{ return Scalar(0); } } void stride(Scalar l){ string typ = precision(); if(typ=="f"){ vsip_vputstride_f((vsip_vview_f*)vsip(),l.stride()); } else if(typ=="cf"){ vsip_cvputstride_f((vsip_cvview_f*)vsip(),l.stride()); }else if(typ=="cd"){ vsip_cvputstride_d((vsip_cvview_d*)vsip(),l.stride()); } else if(typ== "d"){ vsip_vputstride_d((vsip_vview_d*)vsip(),l.stride()); }else if(typ=="i"){ vsip_vputstride_i((vsip_vview_i*)vsip(),l.stride()); }else if(typ=="vi"){ vsip_vputstride_vi((vsip_vview_vi*)vsip(),l.stride()); } } View fill(Scalar s){ string typ = precision(); if(typ=="f"){ vsip_vfill_f(s.scalar_f(),(vsip_vview_f*)vsip()); } else if(typ== "d"){ vsip::fill(s.scalar_d(),(vsip_vview_d*)vsip()); } else if(typ=="i"){ vsip::fill(s.scalar_i(),(vsip_vview_i*)vsip()); }else if(typ=="vi"){ vsip::fill(s.scalar_vi(),(vsip_vview_vi*)vsip()); } return *this; } }; } #endif /* defined(__cppJvsip__View__) */ <file_sep>//: This is a conversion of the example20 contained in the c_VSIP_example example directory. //: The C code is also kept in the Resources directory. import Cocoa import vsip let N_data = vsip_length(4096) let dec1 = 1 let dec3 = 3 let _ = vsip_init(nil) var N_length = 0 var kernel: OpaquePointer?, fir: OpaquePointer?, r_state: OpaquePointer?, conv: OpaquePointer? if let t = vsip_vcreate_kaiser_d(128,15.0,VSIP_MEM_NONE) { kernel = t } if let t = vsip_randcreate(11,1,1,VSIP_NPRNG) { r_state = t } var data: OpaquePointer?, noise: OpaquePointer?, avg: OpaquePointer? if let t = vsip_vcreate_d(N_data,VSIP_MEM_NONE){ data = t } if let t = vsip_vcreate_d(N_data, VSIP_MEM_NONE){ noise = t } if let t = vsip_vcreate_d(N_data,VSIP_MEM_NONE){ avg = t } vsip_vputlength_d(data,vsip_length((Int(N_data) - 1)/dec1) + 1) vsip_vputlength_d(avg,vsip_length((Int(N_data) - 1)/dec1) + 1) if let t = vsip_conv1d_create_d(kernel,VSIP_NONSYM,N_data,Int32(dec1),VSIP_SUPPORT_SAME,0,vsip_alg_hint(rawValue: 0)){ conv = t } if let t = vsip_fir_create_d(kernel,VSIP_NONSYM, N_data,vsip_length(dec1),VSIP_STATE_SAVE,0,vsip_alg_hint(rawValue: 0)){ fir = t } vsip_vfill_d(0.0,avg) for _ in 0..<10 { vsip_vrandn_d(r_state,noise); vsip_convolve1d_d(conv,noise,data); VU_vfrdB_d(data!,1e-13); vsip_vsma_d(data!,0.1,avg,avg); } var N_len = vsip_vgetlength_d(avg); if let x = vsip_vcreate_d( N_len,VSIP_MEM_NONE){ vsip_vramp_d(-0.5,1.0/Double(N_len-1),x); VU_vfprintxyg_d("%8.6f %8.6f\n",x,avg!,"/Users/judd/local/src/jvsip/AppleXcode/example20.playground/Resources/conv_dec1"); for i in 0..<vsip_vgetlength_d(avg) { vsip_vget_d(avg,vsip_index(i)) } vsip_vdestroy_d(x); } vsip_vfill_d(0,avg); for _ in 0..<10 { vsip_vrandn_d(r_state,noise); vsip_firflt_d(fir,noise,data); VU_vfrdB_d(data!,1e-13); vsip_vsma_d(data,0.1,avg,avg); } N_len = vsip_vgetlength_d(avg); if let x = vsip_vcreate_d(N_len,VSIP_MEM_NONE){ vsip_vramp_d(-0.5,1.0/Double(N_len-1),x); VU_vfprintxyg_d("%8.6f %8.6f\n",x,avg!,"/Users/judd/local/src/jvsip/AppleXcode/example20.playground/Resources/fir_dec1"); vsip_vdestroy_d(x); for i in 0..<vsip_vgetlength_d(avg) { vsip_vget_d(avg,vsip_index(i)) } } vsip_conv1d_destroy_d(conv); vsip_fir_destroy_d(fir); conv = vsip_conv1d_create_d(kernel,VSIP_NONSYM, N_data,Int32(dec3),VSIP_SUPPORT_SAME,0,vsip_alg_hint(rawValue: 0)) fir = vsip_fir_create_d( kernel,VSIP_NONSYM, N_data,vsip_length(dec3),VSIP_STATE_SAVE,0,vsip_alg_hint(rawValue: 0)); vsip_vputlength_d(data,vsip_length((Int(N_data) - 1 ) / dec3 ) + 1 ) vsip_vputlength_d(avg,vsip_length((Int(N_data) - 1 ) / dec3 ) + 1 ) vsip_vfill_d(0,avg); for _ in 0..<10 { vsip_vrandn_d(r_state,noise); vsip_convolve1d_d(conv,noise,data); VU_vfrdB_d(data!,1e-13); vsip_vsma_d(data,0.1,avg,avg); } N_len = vsip_vgetlength_d(avg); if let x = vsip_vcreate_d( N_len,VSIP_MEM_NONE){ vsip_vramp_d(-0.5,1.0/(vsip_scalar_d)(N_len - 1),x); VU_vfprintxyg_d("%8.6f %8.6f\n",x, avg!,"/Users/judd/local/src/jvsip/AppleXcode/example20.playground/Resources/conv_dec3"); vsip_vdestroy_d(x); for i in 0..<vsip_vgetlength_d(avg) { vsip_vget_d(avg,vsip_index(i)) } } vsip_vfill_d(0,avg); for _ in 0..<10 { vsip_vrandn_d(r_state,noise); vsip_firflt_d(fir,noise,data); VU_vfrdB_d(data!,1e-13); vsip_vsma_d(data,0.1,avg,avg); } N_len = vsip_vgetlength_d(avg); if let x = vsip_vcreate_d(N_len,VSIP_MEM_NONE){ vsip_vramp_d(-0.5,1.0/Double(N_len-1),x); VU_vfprintxyg_d("%8.6f %8.6f\n", x, avg!,"/Users/judd/local/src/jvsip/AppleXcode/example20.playground/Resources/fir_dec3"); vsip_vdestroy_d(x); for i in 0..<vsip_vgetlength_d(avg) { vsip_vget_d(avg,vsip_index(i)) } } N_len = vsip_vgetlength_d(kernel); if let x = vsip_vcreate_d(N_len,VSIP_MEM_NONE){ vsip_vramp_d(0,1,x); VU_vfprintxyg_d("%8.6f %8.6f\n", x,kernel!,"/Users/judd/local/src/jvsip/AppleXcode/example20.playground/Resources/kaiser_window"); vsip_vramp_d(-0.5,1.0/(vsip_scalar_d)(N_len-1),x); VU_vfrdB_d(kernel!,1e-20); VU_vfprintxyg_d("%8.6f %8.6f\n",x,kernel!,"/Users/judd/local/src/jvsip/AppleXcode/example20.playground/Resources/Freq_Resp_Kaiser"); vsip_vdestroy_d(x); for i in 0..<vsip_vgetlength_d(avg) { vsip_vget_d(avg,vsip_index(i)) } } vsip_randdestroy(r_state); vsip_valldestroy_d(kernel); vsip_conv1d_destroy_d(conv);vsip_fir_destroy_d(fir); vsip_valldestroy_d(data); vsip_valldestroy_d(noise); vsip_valldestroy_d(avg); vsip_finalize(nil); <file_sep># -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <markdowncell> # ## Introduction # In this notebook we introduce the basics of blocks and views. The reader should first be familiar with the C VSIPL specification introduction chapter so they are familiar with how blocks and views work. Under the covers pyJvsip blocks and views are based on C VSIPL blocks and views. # <codecell> import pyJvsip as pv f='%.2f' # <markdowncell> # ### Block # Creating a block requires a block type and the number of elements in the block. The memory flag is not used in pyJvsip. The pyJvsip Block object has a method to return the number of elements in the block. This method is not supported by the C VSIPL block object. # # Memory flag defaults to VSIP_MEM_NONE. Note that C VSIPL does not support hints like memory flag or algorithm except the API is supported, so pyJvsip will frequently default these to some value. # <codecell> aFloatBlock=pv.Block('block_f',100) aDoubleBlock=pv.Block('block_d',100) aComplexDoubleBlock=pv.Block('block_d',100) aIntBlock=pv.Block('block_i',100) # <codecell> aFloatBlock.length # <markdowncell> # ### View # A pyJvsip view is always associated with a block. All views are created with a block bind method. # # The number of arguments to bind are used to determine if a matrix or vector view are created. # A vector view is bind(offset,stride, length) # A matrix view is bind(offset, columnStride, columnLength, rowStride, rowLength) # <codecell> aFloatVectorView=aFloatBlock.bind(0,2,10) aFloatVectorView.ramp(1,1) aFloatVectorView.mprint(f) # <codecell> aDoubleMatrixView=aDoubleBlock.bind(0,5,6,1,5) # <codecell> for i in range(aDoubleMatrixView.collength): aDoubleMatrixView.rowview(i).ramp(i,1) aDoubleMatrixView.mprint(f) # <markdowncell> # A vector view has a block property so the block a view is associated with can always be recovered and used to make another view on the same block. # <codecell> aNewVector = aFloatVectorView.block.bind(0,1,10) aNewVector.mprint(f) # <markdowncell> # Above note we created the block and placed a view on it with stride two and then put a ramp in the view. Here we have created a new view on the same data space with stride one. But we did not initialize this vector so it has coresponding values from the first vector pluss mystery values from our uninitialized block. # # Sometimes you want a vector on an entire block; perhaps to initialize the block values. For convenience pyJvsip supplies a block method to do this for you. # <codecell> aFloatVectorView.block.vector.fill(0.0) aFloatVectorView.ramp(1,1) aFloatVectorView.mprint(f) aNewVector.mprint(f) # <markdowncell> # Note above we didn't care about the vector on the whole block so we didn't create a reference to it. pyJvsip uses python's garbage collection methods to destroy pyJvsip objects which have no reference. We can see now the block has been initialized so our second vector has a zero in every other spot. # <markdowncell> # ## Create Function # # The pyJvsip module has a create function which may be used to create pyJvsip objects including blocks and views. Most of the time you will use this function. When a view is created with this function it creates the needed block under the covers for you. # <codecell> aVector=pv.create('vview_d',10) aVector.ramp(1,1) aVector.mprint(f) # <markdowncell> # Be default when creating a matrix view the view is created as row major. # <codecell> aMatrix = pv.create('cmview_d',4,5) aMatrix.block.vector.ramp(1,1) aMatrix.imagview.block.vector.ramp(-1,-1) aMatrix.mprint('%.1f') # <markdowncell> # We can also add a major argument if we want a column major matrix # <codecell> aMatrix = pv.create('cmview_d',4,5,'COL') aMatrix.block.vector.ramp(1,1) aMatrix.imagview.block.vector.ramp(-1,-1) aMatrix.mprint('%.1f') # <markdowncell> # There are other ways to create views using subviews. Note a subview is a first class view and there is no material difference between a subview and it's parent. See the VSIPL spec for more information on the relationship of a parent complex view and it's child real and imag views. A few examples. Of course you can always recover the block and do a blockbind if you want a view of the same depth. To get a real or imaginary view of complex aparent you must always use the realview and imagview method. # <codecell> aMatrix.diagview(0).mprint(f) aMatrix.realview.mprint(f) aMatrix.rowview(2).mprint(f) aMatrix.colview(1)[1:].mprint(f) aMatrix[1:,2:].mprint(f) # <markdowncell> # The last two methods demonstrate slicing. Currently pyJvsip matrix and vector views support some slicing methods but only for positive index values. # <codecell> aVector=pv.create('vview_i',100).ramp(1,1) # <codecell> aVector.mprint('%d') # <codecell> aVector[10:20:2].mprint('%d') aNewVector=aVector[4:30:3].copy aNewVector.mprint('%d') # <markdowncell> # Note the copy method above creates a new block and vector on the block. # You can also use a slice to copy data between vectors. # <codecell> aNewVector[:]=aVector[:aNewVector.length] aNewVector.mprint('%d') aNewVector[::2]=aVector[aNewVector.length:2 * aNewVector.length:2] aNewVector.mprint('%d') # <codecell> <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cvget_put_f.h,v 2.0 2003/02/22 15:23:33 judd Exp $ */ static void cvget_put_f(void){ printf("********\nTEST cvget_put_f\n"); { vsip_scalar_f datar_a[] = { 0, 1, 1, 0, 1, 0}; vsip_scalar_f datai_a[] = { 1, -1, -1, 1, -1, 1}; vsip_scalar_f ansr[] = { 0, 1, 1, 0, 1, 0}; vsip_scalar_f ansi[] = { 1, -1, -1, 1, -1, 1}; vsip_cblock_f *block_a = vsip_cblockbind_f(datar_a,datai_a,6,VSIP_MEM_NONE); vsip_cvview_f *a = vsip_cvbind_f(block_a,0,1,6); vsip_cblock_f *block_b = vsip_cblockcreate_f(50,VSIP_MEM_NONE); vsip_cvview_f *b = vsip_cvbind_f(block_b, 35,-2,6); vsip_index i; vsip_cblockadmit_f(block_a,VSIP_TRUE); /* copy <a> into <b> */ for(i=0; i<6; i++) vsip_cvput_f(b,i,vsip_cvget_f(a,i)); /* check <a> against ans */ printf("check unit stride compact view\n"); for(i=0; i<6; i++){ vsip_cscalar_f chk = vsip_cvget_f(a,i); chk.r = chk.r - ansr[i]; chk.i = chk.i - ansi[i]; chk.r = chk.r * chk.r + chk.i * chk.i; (chk.r < 0.0001) ? printf("correct\n") : printf("error\n"); fflush(stdout); } printf("check general stride view\n"); for(i=0; i<6; i++){ vsip_cscalar_f chk = vsip_cvget_f(b,i); chk.r = chk.r - ansr[i]; chk.i = chk.i - ansi[i]; chk.r = chk.r * chk.r + chk.i * chk.i; (chk.r < 0.0001) ? printf("correct\n") : printf("error\n"); fflush(stdout); } vsip_cvalldestroy_f(a); vsip_cvalldestroy_f(b); } return; } <file_sep>/* Created RJudd */ /* */ #include"VU_mprintm_f.include" static void mfreqswap_f(void){ printf("*********\nTEST vfreqswap_f\n"); { vsip_length M=6,N=5; vsip_mview_f *a = vsip_mcreate_f(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_vview_f *v = vsip_vbind_f(vsip_mgetblock_f(a),0,1,M*N); vsip_mview_f *ans = vsip_mcreate_f(M,N,VSIP_ROW,VSIP_MEM_NONE); vsip_scalar_f dta[]={ 18.0, 19.0, 20.0, 16.0, 17.0, 23.0, 24.0, 25.0, 21.0, 22.0, 28.0, 29.0, 30.0, 26.0, 27.0, 3.0, 4.0, 5.0, 1.0, 2.0, 8.0, 9.0, 10.0, 6.0, 7.0, 13.0, 14.0, 15.0, 11.0, 12.0}; vsip_mcopyfrom_user_f(dta,VSIP_ROW,ans); vsip_vramp_f (1,1,v); printf("input matrix\n"); VU_mprintm_f("3.1",a); vsip_mfreqswap_f(a); printf("output matrix\n"); VU_mprintm_f("3.1",a); { vsip_msub_f(a,ans,ans); if(fabs(vsip_mmaxval_f(ans,NULL)) > .00001){ printf("error\n"); }else{ printf("correct\n"); } } vsip_vdestroy_f(v); vsip_malldestroy_f(a); vsip_malldestroy_f(ans); } } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: cblock_admit_release_f.h,v 2.0 2003/02/22 15:23:32 judd Exp $ */ #include"VU_cvprintm_f.include" static void cblock_admit_release_f(void){ printf("********\nTEST cblock_admit_release_f\n"); { int i; vsip_scalar_f *ptr1,*ptr2; vsip_scalar_f *ptr1s,*ptr2s; vsip_scalar_f data_r[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; vsip_scalar_f data_i[10] = { 0, -1, -2, -3, -4, -5, -6, -7, -8, -9}; vsip_scalar_f datarb_r[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; vsip_scalar_f datarb_i[10] = { 0, -1, -2, -3, -4, -5, -6, -7, -8, -9}; vsip_scalar_f data_ri[20] = { 0,0, 1,-1, 2,-2, 3,-3, 4,-4, 5,-5, 6,-6, 7,-7, 8,-8, 9,-9}; vsip_scalar_f datarb_ri[20] = { 0,0, 1,-1, 2,-2, 3,-3, 4,-4, 5,-5, 6,-6, 7,-7, 8,-8, 9,-9}; vsip_cblock_f *b_r_i = vsip_cblockbind_f(data_r,data_i,10,VSIP_MEM_NONE); vsip_cvview_f *v_r_i = vsip_cvbind_f(b_r_i,0,1,10); vsip_cblock_f *b_ri = vsip_cblockbind_f(data_ri,(vsip_scalar_f*)NULL,10,VSIP_MEM_NONE); vsip_cvview_f *v_ri = vsip_cvbind_f(b_ri,0,1,10); vsip_cscalar_f chk_i= vsip_cmplx_f(0,0); vsip_cscalar_f chk_s= vsip_cmplx_f(0,0); int chk = 0; vsip_cblockadmit_f(b_r_i,VSIP_TRUE); vsip_cblockadmit_f(b_ri,VSIP_TRUE); vsip_rscvmul_f(2.0,v_r_i,v_r_i); vsip_rscvmul_f(2.0,v_ri,v_ri); /* VU_cvprintm_f("2.0",v_r_i); VU_cvprintm_f("2.0",v_ri); */ for(i=0; i<10; i++){ chk_i = vsip_cvget_f(v_ri,(vsip_index)i); chk_s = vsip_cvget_f(v_r_i,(vsip_index)i); if( (chk_i.r != chk_s.r) || (chk_i.i != chk_s.i)) chk++; } printf("check admit\n"); if(chk != 0) printf("error\n"); else printf("correct\n"); fflush(stdout); chk = 0; vsip_cblockrelease_f(b_r_i,VSIP_TRUE,&ptr1s,&ptr2s); vsip_cblockrelease_f(b_ri,VSIP_TRUE,&ptr1,&ptr2); printf("check release\n"); for(i=0; i< 10; i++){ if((ptr1[2*i] != ptr1s[i]) || (ptr1[2*i+1] != ptr2s[i])) chk++; /* printf("%2.0f, %2.0f; %2.0f, %2.0f\n",ptr1[2*i],ptr1[2*i+1], ptr1s[i],ptr2s[i]); */ } if(chk != 0) printf("error\n"); else printf("correct\n"); fflush(stdout); chk = 0; vsip_cblockrebind_f(b_ri,datarb_r,datarb_i,&ptr1,&ptr2); vsip_cblockrebind_f(b_r_i,datarb_ri,(vsip_scalar_f*)NULL,&ptr1s,&ptr2s); printf("check rebind\n"); printf("check correct pointer returned\n"); for(i=0; i< 10; i++){ if((ptr1[2*i] != ptr1s[i]) || (ptr1[2*i+1] != ptr2s[i])) chk++; } if(chk != 0) printf("error\n"); else printf("correct\n"); fflush(stdout); chk = 0; vsip_cblockadmit_f(b_r_i,VSIP_TRUE); vsip_cblockadmit_f(b_ri,VSIP_TRUE); vsip_rscvmul_f(2.0,v_r_i,v_r_i); vsip_rscvmul_f(2.0,v_ri,v_ri); for(i=0; i<10; i++){ chk_i = vsip_cvget_f(v_ri,(vsip_index)i); chk_s = vsip_cvget_f(v_r_i,(vsip_index)i); if( (chk_i.r != chk_s.r) || (chk_i.i != chk_s.i)) chk++; } printf("check admit\n"); if(chk != 0) printf("error\n"); else printf("correct\n"); fflush(stdout); chk = 0; fflush(stdout); vsip_cblockrelease_f(b_ri,VSIP_TRUE,&ptr1s,&ptr2s); vsip_cblockrelease_f(b_r_i,VSIP_TRUE,&ptr1,&ptr2); printf("check release\n"); for(i=0; i< 10; i++){ if((ptr1[2*i] != ptr1s[i]) || (ptr1[2*i+1] != ptr2s[i])) chk++; } if(chk != 0) printf("error\n"); else printf("correct\n"); fflush(stdout); vsip_cvalldestroy_f(v_r_i); vsip_cvalldestroy_f(v_ri); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: mrsqrt_f.h,v 2.0 2003/02/22 15:23:26 judd Exp $ */ #include"VU_mprintm_f.include" static void mrsqrt_f(void){ printf("\n*********\nTEST mrsqrt_f\n"); { vsip_mview_f *M = vsip_mcreate_f(4,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_f *m1 = vsip_msubview_f(M,0,0,2,3); vsip_mview_f *m2 = vsip_msubview_f(M,2,0,2,3); vsip_mview_f *chk = vsip_mcreate_f(2,3,VSIP_COL,VSIP_MEM_NONE); vsip_scalar_f data[6]; vsip_block_f *block = vsip_blockbind_f(data,6,VSIP_MEM_NONE); vsip_mview_f *ans = vsip_mbind_f(block,0,1,2,2,3); vsip_vview_f *vans = vsip_vbind_f(block,0,1,6); vsip_blockadmit_f(block,VSIP_FALSE); vsip_vramp_f(1,.5,vans); vsip_mcopy_f_f(ans,m1); vsip_blockrelease_f(block,VSIP_TRUE); data[0] = (vsip_scalar_f)1.0/sqrt(data[0]); data[1] = (vsip_scalar_f)1.0/sqrt(data[1]); data[2] = (vsip_scalar_f)1.0/sqrt(data[2]); data[3] = (vsip_scalar_f)1.0/sqrt(data[3]); data[4] = (vsip_scalar_f)1.0/sqrt(data[4]); data[5] = (vsip_scalar_f)1.0/sqrt(data[5]); vsip_blockadmit_f(block,VSIP_TRUE); vsip_mrsqrt_f(m1,m2); printf("mrsqrt_f(a,b)"); printf("matrix a\n"); VU_mprintm_f("8.6",m1); printf("matrix b\n"); VU_mprintm_f("8.6",m2); printf("right answer\n"); VU_mprintm_f("8.4",ans); vsip_msub_f(m2,ans,chk); vsip_mclip_f(chk,0.0001,0.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); printf("in place\n"); vsip_mrsqrt_f(m1,m1); vsip_msub_f(m1,ans,chk); vsip_mclip_f(chk,0.0001,0.0001,0,1,chk); if(vsip_msumval_f(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_mdestroy_f(ans); vsip_valldestroy_f(vans); vsip_mdestroy_f(m2); vsip_mdestroy_f(m1); vsip_malldestroy_f(M); vsip_malldestroy_f(chk); } } <file_sep>import pyJvsip as pv def svdSort(L,d,R): """ Usage: L,d,R = svdSort(L,d,R) Where: matrix A = L.prod(D).prod(R) and D is a diagonal matrix represented by vector d. Sorts d so that the values go from largest to smallest and updates L and R so that A = L.prod(D).prod(R) after sort. """ index = d.sort('BYVALUE','DESCENDING') L[:,:d.length].permute(index.copy,'COL') R.permute(index,'ROW') return (L,d,R) <file_sep>/* Created by RJudd August 2, 2002 */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_ccfftip_f.h,v 2.2 2007/04/16 16:23:59 judd Exp $ */ #ifndef VI_CCFFTIP_F_H #define VI_CCFFTIP_F_H 1 /******************************************************************/ /* init fft to x */ static void init_fft_f(void *tx,void* tfft){ vsip_cvview_f *x = (vsip_cvview_f*) tx; vsip_fft_f* fft = (vsip_fft_f*) tfft; fft->x = x; fft->stage =0; return; } /* VI_sort_copy_f.c */ /*========================================================*/ static void VI_sort_copy_f(void* tfft){ vsip_fft_f* fft = (vsip_fft_f*)tfft; vsip_scalar_vi *x = fft->index; vsip_cvview_f *a = fft->x; vsip_cvview_f *r = fft->temp; vsip_length n = fft->N; vsip_stride cast = a->block->cstride; vsip_stride ast = cast * a->stride; vsip_stride rst = r->block->cstride; vsip_scalar_f *apr = (vsip_scalar_f*) ((a->block->R->array) + cast * a->offset), *rpr = (vsip_scalar_f*) r->block->R->array ; vsip_scalar_f *api = (vsip_scalar_f*) ((a->block->I->array) + cast * a->offset), *rpi = (vsip_scalar_f*) r->block->I->array; vsip_scalar_f *apr2 = apr, *rpr2 = rpr; vsip_scalar_f *api2 = api, *rpi2 = rpi; vsip_stride xinc = 0; while(n-- >0){ xinc = *x * ast; *rpr = *(apr + xinc); *rpi = *(api + xinc); rpr += rst; rpi += rst; x++; } n = fft->N; while(n-- >0){ *apr2 = *rpr2; *api2 = *rpi2; apr2 += ast; api2 += ast; rpr2 += rst; rpi2 += rst; } return; } static void VI_ccfftip_f(const vsip_fft_f* fft, const vsip_cvview_f *x) { void* fft_v = (void*) fft; void* x_v = (void*) x; init_fft_f(x_v,fft_v); if(fft->dft == 1){ VI_dft_f(fft_v); }else{ VI_p0pF_f(fft_v); VI_sort_copy_f(fft_v); } if (fft->scale != 1) vsip_rscvmul_f(fft->scale,x,x); return; } #endif <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_attrib_si.h,v 2.0 2003/02/22 15:23:33 judd Exp $ */ static void get_put_attrib_si(void){ printf("********\nTEST get_put_attrib_si\n"); { vsip_offset ivo = 3; vsip_stride ivs = 2; vsip_length ivl = 3; vsip_offset jvo = 2; vsip_stride jvs = 3; vsip_length jvl = 5; vsip_stride irs = 1, ics = 3; vsip_length irl = 2, icl = 3; vsip_stride jrs = 5, jcs = 2; vsip_length jrl = 5, jcl = 2; vsip_stride ixs = 2, iys = 4, izs = 14; vsip_length ixl = 2, iyl = 3, izl = 4; vsip_stride jxs = 4, jys = 14, jzs = 2; vsip_length jxl = 3, jyl = 4, jzl = 2; vsip_block_si *b = vsip_blockcreate_si(80,VSIP_MEM_NONE); vsip_vview_si *v = vsip_vbind_si(b,ivo,ivs,ivl); vsip_mview_si *m = vsip_mbind_si(b,ivo,ics,icl,irs,irl); vsip_tview_si *t = vsip_tbind_si(b,ivo,izs,izl,iys,iyl,ixs,ixl); vsip_vattr_si attr; vsip_mattr_si mattr; vsip_tattr_si tattr; printf("test vgetattrib_si\n"); fflush(stdout); { vsip_vgetattrib_si(v,&attr); (attr.offset == ivo) ? printf("offset correct\n") : printf("offset error \n"); (attr.stride == ivs) ? printf("stride correct\n") : printf("stride error \n"); (attr.length == ivl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputattrib_si\n"); fflush(stdout); { attr.offset = jvo; attr.stride = jvs; attr.length = jvl; vsip_vputattrib_si(v,&attr); vsip_vgetattrib_si(v,&attr); (attr.offset == jvo) ? printf("offset correct\n") : printf("offset error \n"); (attr.stride == jvs) ? printf("stride correct\n") : printf("stride error \n"); (attr.length == jvl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /**************************************************************************/ printf("test mgetattrib_si\n"); fflush(stdout); { vsip_mgetattrib_si(m,&mattr); (mattr.offset == ivo) ? printf("offset correct\n") : printf("offset error \n"); (mattr.col_stride == ics) ? printf("col_stride correct\n") : printf("col_stride error \n"); (mattr.row_stride == irs) ? printf("row_stride correct\n") : printf("row_stride error \n"); (mattr.col_length == icl) ? printf("col_length correct\n") : printf("col_length error \n"); (mattr.row_length == irl) ? printf("row_length correct\n") : printf("row_length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputattrib_si\n"); fflush(stdout); { mattr.offset = jvo; mattr.col_stride = jcs; mattr.col_length = jcl; mattr.row_stride = jrs; mattr.row_length = jrl; vsip_mputattrib_si(m,&mattr); vsip_mgetattrib_si(m,&mattr); (mattr.offset == jvo) ? printf("offset correct\n") : printf("offset error \n"); (mattr.col_stride == jcs) ? printf("col_stride correct\n") : printf("col_stride error \n"); (mattr.col_length == jcl) ? printf("col_length correct\n") : printf("col_length error \n"); (mattr.row_stride == jrs) ? printf("row_stride correct\n") : printf("row_stride error \n"); (mattr.row_length == jrl) ? printf("row_length correct\n") : printf("row_length error \n"); fflush(stdout); } /**************************************************************************/ printf("test tgetattrib_si\n"); fflush(stdout); { vsip_tgetattrib_si(t,&tattr); (tattr.offset == ivo) ? printf("offset correct\n") : printf("offset error \n"); (tattr.z_stride == izs) ? printf("z_stride correct\n") : printf("z_stride error \n"); (tattr.z_length == izl) ? printf("z_length correct\n") : printf("z_length error \n"); (tattr.y_stride == iys) ? printf("y_stride correct\n") : printf("y_stride error \n"); (tattr.y_length == iyl) ? printf("y_length correct\n") : printf("y_length error \n"); (tattr.x_stride == ixs) ? printf("x_stride correct\n") : printf("x_stride error \n"); (tattr.x_length == ixl) ? printf("x_length correct\n") : printf("x_length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test tputattrib_si\n"); fflush(stdout); { tattr.offset = jvo; tattr.z_stride = jzs; tattr.z_length = jzl; tattr.y_stride = jys; tattr.y_length = jyl; tattr.x_stride = jxs; tattr.x_length = jxl; vsip_tputattrib_si(t,&tattr); vsip_tgetattrib_si(t,&tattr); (tattr.offset == jvo) ? printf("offset correct\n") : printf("offset error \n"); (tattr.z_stride == jzs) ? printf("z_stride correct\n") : printf("z_stride error \n"); (tattr.z_length == jzl) ? printf("z_length correct\n") : printf("z_length error \n"); (tattr.y_stride == jys) ? printf("y_stride correct\n") : printf("y_stride error \n"); (tattr.y_length == jyl) ? printf("y_length correct\n") : printf("y_length error \n"); (tattr.x_stride == jxs) ? printf("x_stride correct\n") : printf("x_stride error \n"); (tattr.x_length == jxl) ? printf("x_length correct\n") : printf("x_length error \n"); fflush(stdout); } vsip_vdestroy_si(v); vsip_mdestroy_si(m); vsip_talldestroy_si(t); } return; } <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: minvclip_d.h,v 2.0 2003/02/22 15:23:24 judd Exp $ */ #include"VU_mprintm_d.include" static void minvclip_d(void){ printf("\n******\nTEST madd_d\n"); { vsip_scalar_d data1[]= {.1, .2, .3, 4, 5, 6, 7, 8, 9}; vsip_scalar_d ans[] = {0.1, 0.2, 0.0, 1, 1, 1, 7.0, 8.0, 9.0}; vsip_mview_d *a = vsip_mbind_d( vsip_blockbind_d(data1,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_mview_d *b = vsip_mcreate_d(3,3,VSIP_COL,VSIP_MEM_NONE); vsip_mview_d *mans = vsip_mbind_d( vsip_blockbind_d(ans,9,VSIP_MEM_NONE),0,3,3,1,3); vsip_mview_d *chk = vsip_mcreate_d(3,3,VSIP_ROW,VSIP_MEM_NONE); vsip_scalar_d min = .25; vsip_scalar_d mid = 1.0; vsip_scalar_d max = 6.5; vsip_scalar_d minval = 0.0; vsip_scalar_d maxval = 1.0; vsip_blockadmit_d(vsip_mgetblock_d(a),VSIP_TRUE); vsip_blockadmit_d(vsip_mgetblock_d(mans),VSIP_TRUE); printf("call vsip_minvclip_d(a,min,mid,max,minval,maxval,b)\n"); printf("min = %f\n",min); printf("mid = %f\n",mid); printf("max = %f\n",max); printf("min to mid value = %f\n",minval); printf("mid to max value = %f\n",maxval); printf("a =\n");VU_mprintm_d("8.6",a); vsip_minvclip_d(a,min,mid,max,minval,maxval,b); printf("b =\n");VU_mprintm_d("8.6",b); printf("\nright answer =\n"); VU_mprintm_d("6.4",mans); vsip_msub_d(mans,b,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,0,.0001,0,1,chk); if(fabs(vsip_msumval_d(chk)) > .5) printf("error\n"); else printf("correct\n"); printf(" a,b inplace\n"); vsip_minvclip_d(a,min,mid,max,minval,maxval,a); printf("a =\n");VU_mprintm_d("8.6",a); vsip_msub_d(mans,a,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,0,.0001,0,1,chk); if(fabs(vsip_msumval_d(chk)) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_d(a); vsip_malldestroy_d(b); vsip_malldestroy_d(mans); vsip_malldestroy_d(chk); } return; } <file_sep>import ctypes lib=ctypes.CDLL("./_vsip.so") # Memory hints are only supported at the interface for C JVSIP. Here I don't expose them to the user interface. memory_hint = { "VSIP_MEM_NONE":ctypes.c_int(0), "VSIP_MEM_RDONLY":ctypes.c_int(1), "VSIP_MEM_CONST":ctypes.c_int(2), "VSIP_MEM_SHARED":ctypes.c_int(3), "VSIP_MEM_SHARED_RDONLY":ctypes.c_int(4), "VSIP_MEM_SHARED_CONST":ctypes.c_int(5)} class vattr(ctypes.Structure): _fields_=[ ('offset',ctypes.c_ulong), ('stride',ctypes.c_long), ('length',ctypes.c_ulong), ('block', ctypes.c_void_p) ] class cmplx(ctypes.Structure): _fields_=[('r',ctypes.c_float),('i',ctypes.c_float)] def vsipInit(): lib.vsip_init.restype=ctypes.c_int return lib.vsip_init(ctypes.c_void_p(0)) def vsipFinalize(): lib.vsip_finalize.restype=ctypes.c_int return lib.vsip_finalize(ctypes.c_void_p(0)) class JVSIP (object): jinit = 0 def __init__(self): if JVSIP.jinit: self.vsipInit=0; JVSIP.jinit +=1; else: self.vsipInit = vsipInit() assert self.vsipInit == 0,'VSIP failed to initialize' JVSIP.jinit = 1; def __del__(self): JVSIP.jinit -= 1 if JVSIP.jinit == 0: vsipFinalize() def _tType(a): if isinstance(a,complex): return 'cscalar' elif isinstance(a,int) or isinstance(a,long) or isinstance(a,float): return 'scalar' elif 'View' in repr(a): return a.type else: return repr(a) def _nlength(b,e,s): #begin(start),end(stop),step(step)=>b,e,s; Slice Length d=int(e)-int(b) chk=d%int(s) if chk is 0: return d//int(s) else: return (d//int(s)) + 1 def _blockcreate(t,l): assert isinstance(l,int),'Length parameter to blockcreate is an integer' assert isinstance(t,str),'Type parameter to blockcreate ia a string' f={'block_f':lib.vsip_blockcreate_f,'cblock_f':lib.vsip_cblockcreate_f, 'block_i':lib.vsip_blockcreate_i,'block_vi':lib.vsip_blockcreate_vi} assert f.has_key(t),'Block type string <:%s:> not recognized'%t f[t].restype=ctypes.c_void_p return f[t](ctypes.c_ulong(l),memory_hint["VSIP_MEM_NONE"]) def _blockdestroy(t,aVsipBlock): assert isinstance(t,str),'Type parameter to blockdestroy is a string' f={'block_f':lib.vsip_blockdestroy_f,'cblock_f':lib.vsip_cblockdestroy_f, 'block_i':lib.vsip_blockdestroy_i,'block_vi':lib.vsip_blockdestroy_vi} assert f.has_key(t),'Block type string <:%s:> not recognized'%t f[t](ctypes.c_void_p(aVsipBlock)) def _bind(t,block,offset,stride,length): def vbind_f(block,offset,stride,length): lib.vsip_vbind_f.restype=ctypes.c_void_p return lib.vsip_vbind_f(ctypes.c_void_p(block),ctypes.c_ulong(offset),ctypes.c_long(stride),ctypes.c_ulong(length)) def cvbind_f(block,offset,stride,length): lib.vsip_vbind_f.restype=ctypes.c_void_p return lib.vsip_vbind_f(ctypes.c_void_p(block),ctypes.c_ulong(offset),ctypes.c_long(stride),ctypes.c_ulong(length)) def vbind_i(block,offset,stride,length): lib.vsip_vbind_f.restype=ctypes.c_void_p return lib.vsip_vbind_f(ctypes.c_void_p(block),ctypes.c_ulong(offset),ctypes.c_long(stride),ctypes.c_ulong(length)) def vbind_vi(block,offset,stride,length): lib.vsip_vbind_f.restype=ctypes.c_void_p return lib.vsip_vbind_f(ctypes.c_void_p(block),ctypes.c_ulong(offset),ctypes.c_long(stride),ctypes.c_ulong(length)) f={'vview_f':vbind_f,'cvview_f':cvbind_f,'vview_i':vbind_i,'vview_vi':vbind_vi} assert f.has_key(t),'Type <:%s:> not found for bind.'%t return f[t](block,offset,stride,length) def _viewDestroy(t,aVSipView): assert isinstance(t,str),'Type parameter to viewDestroy must be a string' f={'vview_f':lib.vsip_vdestroy_f,'cvview_f':lib.vsip_cvdestroy_f, 'vview_i':lib.vsip_vdestroy_i,'vview_vi':lib.vsip_vdestroy_vi} assert f.has_key(t),'Type paramter <:%s:> not recognized for viewDestroy.'%t f[t].restype = ctypes.c_void_p f[t](ctypes.c_void_p(aVSipView)) def _getattrib(view): f={'vview_f':lib.vsip_vgetattrib_f,'cvview_f':lib.vsip_cvgetattrib_f,\ 'vview_i':lib.vsip_vgetattrib_i,'vview_vi':lib.vsip_vgetattrib_vi} attr=vattr(0,0,0,0) f[view.type](ctypes.c_void_p(view.vsip),ctypes.pointer(attr)) return attr def _putattrib(view,attr): f={'vview_f':lib.vsip_vputattrib_f,'cvview_f':lib.vsip_cvputattrib_f, 'vview_i':lib.vsip_vputattrib_i,'vview_vi':lib.vsip_vputattrib_vi} f[view.type](ctypes.c_void_p(view.vsip),ctypes.pointer(attr)) def _get(view,index): def vget_f(view,index): lib.vsip_vget_f.restype = ctypes.c_float return lib.vsip_vget_f(ctypes.c_void_p(view.vsip),ctypes.c_ulong(index)) def cvget_f(view,index): r = view.realview.get(index) i = view.imagview.get(index) return complex(r,i) def vget_i(view,index): lib.vsip_vget_i.restype = ctypes.c_int return lib.vsip_vget_i(ctypes.c_void_p(view.vsip),ctypes.c_ulong(index)) def vget_vi(view,index): lib.vsip_vget_vi.restype = ctypes.c_ulong return lib.vsip_vget_vi(ctypes.c_void_p(view.vsip),ctypes.c_ulong(index)) f={'vview_f':vget_f,'cvview_f':cvget_f,'vview_i':vget_i,'vview_vi':vget_vi} return f[view.type](view,index) def _put(view,index,val): def vput_f(view,index,val): lib.vsip_vput_f(ctypes.c_void_p(view.vsip),ctypes.c_ulong(index),ctypes.c_float(val)) def cvput_f(view,index,val): view.realview.put(index,val.real) view.imagview.put(index,val.imag) def vput_i(view,index,val): lib.vsip_vput_i(ctypes.c_void_p(view.vsip),ctypes.c_ulong(index),ctypes.c_int(val)) def vput_vi(view,index,val): lib.vsip_vput_vi(ctypes.c_void_p(view.vsip),ctypes.c_ulong(index),ctypes.c_ulong(val)) f={'vview_f':vput_f,'cvview_f':cvput_f,'vview_i':vput_i,'vview_vi':vput_vi} f[view.type](view,index,val) def _realview(view): lib.vsip_vrealview_f.restype=ctypes.c_void_p return lib.vsip_vrealview_f(ctypes.c_void_p(view)) def _imagview(view): lib.vsip_vimagview_f.restype=ctypes.c_void_p return lib.vsip_vimagview_f(ctypes.c_void_p(view)) def _fill(view,val): def vfill_f(alpha,view): lib.vsip_vfill_f(ctypes.c_float(alpha),ctypes.c_void_p(view)) def vfill_i(alpha,view): lib.vsip_vfill_i(ctypes.c_int(alpha),ctypes.c_void_p(view)) def vfill_vi(alpha,view): lib.vsip_vfill_vi(ctypes.c_ulong(alpha),ctypes.c_void(view)) f={'vview_f':vfill_f,'vview_i':vfill_i,'vview_vi':vfill_vi} f[view.type](val,view.vsip) def _add(a,b,c): """ The add function includes view+view adds and scalar+view adds. """ def vadd_f(a,b,c): lib.vsip_vadd_f(ctypes.c_void_p(a.vsip),ctypes.c_void_p(b.vsip),ctypes.c_void_p(c.vsip)) def svadd_f(a,b,c): lib.vsip_svadd_f(ctypes.c_float(a),ctypes.c_void_p(b.vsip),ctypes.c_void_p(c.vsip)) def vadd_i(a,b,c): lib.vsip_vadd_i(ctypes.c_void_p(a.vsip),ctypes.c_void_p(b.vsip),ctypes.c_void_p(c.vsip)) def svadd_i(a,b,c): lib.vsip_svadd_i(ctypes.c_int(a),ctypes.c_void_p(b.vsip),ctypes.c_void_p(c.vsip)) def vadd_vi(a,b,c): lib.vsip_vadd_vi(ctypes.c_void_p(a.vsip),ctypes.c_void_p(b.vsip),ctypes.c_void_p(c.vsip)) def svadd_vi(a,b,c): lib.vsip_svadd_vi(ctypes.c_ulong(a),ctypes.c_void_p(b.vsip),ctypes.c_void_p(c.vsip)) def cvadd_f(a,b,c): lib.vsip_cvadd_f(ctypes.c_void_p(a.vsip),ctypes.c_void_p(b.vsip),ctypes.c_void_p(c.vsip)) def rscvadd_f(a,b,c): svadd_f(a,b.realview,c.realview) def csvadd_f(a,b,c): svadd_f(a.real,b.realview,c.realview) svadd_f(a.imag,b.imagview,c.imagview) f={'vview_fvview_fvview_f':vadd_f,'vview_ivview_ivview_i':vadd_i, 'vview_vivview_vivview_vi':vadd_vi, 'scalarvview_fvview_f':svadd_f, 'scalarvview_ivview_i':svadd_i, 'scalarcvview_fcvview_f':rscvadd_f, 'scalarvview_vivview_vi':svadd_vi,'cscalarcvview_fcvview_f':csvadd_f} if isinstance(a,int) or isinstance(a,long) or isinstance(a,float): t='scalar'+b.type+c.type elif isinstance(a,complex): t='cscalar'+b.type+c.type else: t=a.type+b.type+c.type assert f.has_key(t), 'Type <:%s:> not recognized for add'%t f[t](a,b,c) return c def _sub(a,b,c): f={ 'cvview_fvview_fcvview_f':lib.vsip_crvsub_f, 'cscalarcvview_fcvview_f':lib.vsip_csvsub_f, 'cvview_fcvview_fcvview_f':lib.vsip_cvsub_f, 'vview_fcvview_fcvview_f':lib.vsip_rcvsub_f, 'scalarcvview_fcvview_f':lib.vsip_rscvsub_f, 'scalarvview_fvview_f':lib.vsip_svsub_f, 'vview_fvview_fvview_f':lib.vsip_vsub_f, 'scalarvview_ivview_i':lib.vsip_svsub_i, 'vview_ivview_ivview_i':lib.vsip_vsub_i, 'scalarvview_vivview_vi':lib.vsip_svsub_vi} t=_tType(a)+_tType(b)+_tType(c) assert f.has_key(t), 'Type <:%s:> not recognized for sub'%t if 'cscalar' in t: _sub(a.real,b.realview,c.realview) _sub(a.imag,b.imagview,c.imagview) elif 'scalar' in t: if '_f' in t: f[t](ctypes.c_float(a),ctypes.c_void_p(b.vsip),ctypes.c_void_p(c.vsip)) else: f[t](ctypes.c_int(a),ctypes.c_void_p(b.vsip),ctypes.c_void_p(c.vsip)) else: f[t](ctypes.c_void_p(a.vsip),ctypes.c_void_p(b.vsip),ctypes.c_void_p(c.vsip)) return c def _mul(a,b,c): """ The mul function includes view+view muls and scalar+view muls. """ def csvmul_f(a,b,c): t=c.empty rscvmul_f(a.r,b,t) svmul_f( a.i,b.realview,c.imagview) svmul_f(-a.i,b.imagview,c.realview) c+=t def cvmul_f(a,b,c): lib.vsip_cvmul_f(ctypes.c_void_p(a.vsip),ctypes.c_void_p(b.vsip),ctypes.c_void_p(c.vsip)) def rcvmul_f(a,b,c): lib.vsip_rcvmul_f(ctypes.c_void_p(a.vsip),ctypes.c_void_p(b.vsip),ctypes.c_void_p(c.vsip)) def rscvmul_f(a,b,c): lib.vsip_rscvmul_f(ctypes.float(a),ctypes.c_void_p(b.vsip),ctypes.c_void_p(c.vsip)) def svmul_f(a,b,c): lib.vsip_svmul_f(ctypes.c_float(a),ctypes.c_void_p(b.vsip),ctypes.c_void_p(c.vsip)) def vmul_f(a,b,c): lib.vsip_vmul_f(ctypes.c_void_p(a.vsip),ctypes.c_void_p(b.vsip),ctypes.c_void_p(c.vsip)) def vmul_i(a,b,c): lib.vsip_vmul_i(ctypes.c_void_p(a.vsip),ctypes.c_void_p(b.vsip),ctypes.c_void_p(c.vsip)) f={ 'cscalarcvview_fcvview_f':csvmul_f,'cvview_fcvview_fcvview_f':cvmul_f, 'vview_fcvview_fcvview_f':rcvmul_f,'scalarcvview_fcvview_f':rscvmul_f, 'scalarvview_fvview_f':svmul_f,'vview_fvview_fvview_f':vmul_f, 'vview_ivview_ivview_i':vmul_i} if isinstance(a,int) or isinstance(a,long) or isinstance(a,float): t='scalar'+b.type+c.type elif isinstance(a,complex): t='cscalar'+b.type+c.type else: t=a.type+b.type+c.type assert f.has_key(t), 'Type <:%s:> not recognized for mul'%t f[t](a,b,c) return c class Block (object): tBlock = ['block_f','cblock_f','block_vi','block_i'] derivedTypes = ['real_f','imag_f'] vectorTypes=['vview_f','cvview_f','vview_i','vview_vi'] windowTypes=['blackman_f','cheby_f','kaiser_f','hanning_f'] complexTypes=['cvview_f'] blkSel={'vview_f':'block_f','vview_d':'block_d','cvview_f':'cblock_f',\ 'cvview_d':'cblock_d', 'vview_si':'block_si','vview_i':'block_i',\ 'vview_uc':'block_uc', 'vview_mi':'block_mi', 'vview_vi':'block_vi',\ 'vview_bl':'block_bl','mview_f':'block_f','mview_d':'block_d',\ 'cmview_f':'cblock_f','cmview_d':'cblock_d','mview_si':'block_si',\ 'mview_i':'block_i','mview_uc':'block_uc','mview_bl':'block_bl'} #Block specific class below def __init__(self,block_type,*args): other = Block.derivedTypes assert isinstance(block_type,str),'The type argument should be a string' keyError='Block type <:%s:> not support by Block class'%block_type assert block_type in Block.tBlock or block_type in other or block_type in Block.windowTypes,'Block type not recognized' self.__jvsip = JVSIP() if block_type in Block.tBlock: #Regular block constructor self.__vsipBlock = _blockcreate(block_type,int(args[0])) self.__length = int(args[0]) self.__type = block_type elif block_type in other: #Derived block constructor for real, imag views self.__vsipBlock = args[0] self.__length = int(args[1]) self.__type = block_type else: #must be window assert block_type in Block.windowTypes,'Should not be here. Block type not a window type' # window functions selector f={'blackman_d':'vsip_vcreate_blackman_d(args[0],0)',\ 'blackman_f':'vsip_vcreate_blackman_f(args[0],0)',\ 'cheby_d':'vsip_vcreate_cheby_d(args[0],args[1],0)',\ 'cheby_f':'vsip_vcreate_cheby_f(args[0],args[1],0)',\ 'kaiser_d':'vsip_vcreate_kaiser_d(args[0],args[1],0)',\ 'kaiser_f':'vsip_vcreate_kaiser_f(args[0],args[1],0)',\ 'hanning_d':'vsip_vcreate_hanning_d(args[0],0)',\ 'hanning_f':'vsip_vcreate_hanning_f(args[0],0)'} # block type selector bt={'blackman_d':'block_d','blackman_f':'block_f','cheby_d':'block_d',\ 'cheby_f':'block_f','kaiser_d':'block_d','kaiser_f':'block_f',\ 'hanning_d':'block_d','hanning_f':'block_f'} # get block selector gb={'block_d':vsip_vgetblock_d,'block_f':vsip_vgetblock_f} v=eval(f[block_type]) # create vsip window vector b=bt[block_type] # get block type for window created blk = gb[b](v) # get pointer to vectors C VSIPL block # construct pyJvsip block self.__vsipBlock=blk self.__type=b self.__length=args[0] self.w = self.__View(v,self) #create a pyJvsip view object with window in it. def __del__(self): t = self.__type if t in Block.tBlock: _blockdestroy(t,self.vsip) del(self.__jvsip) @classmethod def otherBlock(cls,blk,arg): """ This method is used internal to the pyCtypesJvsip module. It is not intended to be used in user code. otherBlock creates a new block of type blk (or the proper type if blk is derived). """ #bSel is a block selector to select the proper type block if the input type is derived bSel={'imag_f':'block_f','real_f':'block_f'} if isinstance(arg,tuple):#create derived block return cls(blk,arg[0],arg[1]) elif bSel.has_key(blk):#create new block starting with derived block return cls(bSel[blk],arg) else:#create new block return cls(blk,arg) @property def vsip(self): return self.__vsipBlock @property def type(self): return self.__type @property def length(self): return self.__length def __len__(self): return self.length @property def vector(self): return self.bind(0,1,self.length) def bind(self,*args): # big rewrite to support matrix f={ 'block_fvector':'vview_f', 'cblock_fvector':'cvview_f', 'block_ivector':'vview_i', 'block_vivector':'vview_vi'} assert len(args) == 3,'Only vector views are supported for pyCtypesJvsip demo' t = self.type+'vector' assert f.has_key(t),'Block bind method has no type <:%s:>.'%t viewType=f[t] offset = int(args[0]);stride=int(args[1]);length=int(args[2]) assert self.length > offset + stride*(length-1),'View exceeds block size' vsipView = _bind(viewType,self.vsip,offset,stride,length) return self.__View(viewType,vsipView,self) class __View(object): tView=['vview_f','cvview_f','vview_i','vview_vi'] def __init__(self,viewType,vsipView,block): self.__jvsip = JVSIP() self.__vsipView = vsipView self.__pyBlock = block self.__type = viewType self.__parent = 0 def __del__(self): t=self.type _viewDestroy(t,self.vsip) del(self.__jvsip) @classmethod def __realview(cls,V): db={'cvview_f':'real_f'} rv={'cvview_f': _realview} assert db.has_key(V.type),'View of type <:%s:> not supported for realview.'%V.type t=db[V.type] #type of derived block v=rv[V.type](V.vsip) #get real vsip view attr=vattr(0,0,0,0) lib.vsip_vgetattrib_f(ctypes.c_void_p(v),ctypes.pointer(attr)) b=attr.block B=V.block l=B.length newB = B.otherBlock(t,(b,l))# create new pyJvsip derived block return cls('vview_f',v,newB)#create new pyJvsip real view with associated derived block @classmethod def __imagview(cls,V): db={'cvview_f':'imag_f'} rv={'cvview_f': _imagview} assert db.has_key(V.type),'View of type <:%s:> not supported for imagview.'%V.type t=db[V.type] #type of derived block v=rv[V.type](V.vsip) #get real vsip view attr=vattr(0,0,0,0) lib.vsip_vgetattrib_f(ctypes.c_void_p(v),ctypes.pointer(attr)) b=attr.block B=V.block l=B.length newB = B.otherBlock(t,(b,l))# create new pyJvsip derived block return cls('vview_f',v,newB)#create new pyJvsip real view with associated derived block @classmethod def __newView(cls,t,v,b): return cls(t,v,b) @property def realview(self): v=self.__realview(self) v.__parent=self return v @property def imagview(self): v = self.__imagview(self) v.__parent=self return v @property def block(self): return self.__pyBlock @property def type(self): return self.__type @property def vsip(self): return self.__vsipView @property def length(self): return self.attrib.length def __len__(self): return self.length @property def offset(self): return self.attrib.offset @property def stride(self): return self.attrib.stride def putlength(self,length): attr=self.attrib attr.length = length self.putattrib(self,attr) def putoffset(self,offset): attr=self.attrib attr.length = length self.putattrib(self,attr) def putstride(self,stride): attr=self.attrib attr.stride = stride self.putattrib(self,attr) @property def attrib(self): return _getattrib(self) def putattrib(self,attr): _putattrib(self,attr) return self def get(self,indx): return _get(self,indx) def put(self,indx,val): _put(self,indx,val) return self def fill(self,val): if 'cvview_f' in self.type: r=self.realview;i=self.imagview _fill(self.realview,val.real) _fill(self.imagview,val.imag) else: _fill(self,val) return self @property def empty(self): tSel= {'block_f':'block_f','cblock_f':'cblock_f','block_i':'block_i',\ 'block_vi':'block_vi','imag_f':'block_f','real_f':'block_f'} return Block(tSel[self.block.type],self.length).vector def ramp(self,start,increment): def vramp_f(start,step,view): lib.vsip_vramp_f(ctypes.c_float(start),ctypes.c_float(step),ctypes.c_void_p(view.vsip)) def cvramp_f(start,step,view): view.imagview.fill(0.0) view.realview.ramp(start,step) def vramp_i(start,step,view): lib.vsip_vramp_i(ctypes.c_int(start),ctypes.c_int(step),ctypes.c_void_p(view.vsip)) def vramp_vi(start,step,view): lib.vsip_vramp_vi(ctypes.c_ulong(start),ctypes.c_ulong(step),ctypes.c_void_p(view.vsip)) f={'vview_f':vramp_f, 'cvview_f':cvramp_f, 'vview_i':vramp_i, 'vview_vi':vramp_vi} assert f.has_key(self.type) extended = ['cvview_f'] t=self.type assert f.has_key(t),'Type <:%s:> not support for ramp'%self.type f[t](start,increment,self) return self @property def cloneview(self): f={'vview_f':lib.vsip_vcloneview_f, 'cvview_f':lib.vsip_cvcloneview_f, 'vview_i':lib.vsip_vcloneview_i, 'vview_vi':lib.vsip_vcloneview_vi} f[self.type].restype=ctypes.c_void_p v = f[self.type](ctypes.c_void_p(self.vsip)) b=self.block return self.__newView(self.type,v,b) def __getitem__(self,index): assert isinstance(index,int) or isinstance(index,long) or isinstance(index,slice),\ 'Parameter must be a slice or an integer index for __getitem__' if isinstance(index,slice): v=self.cloneview attr=v.attrib b=index.start e=index.stop s=index.step if e > attr.length: e = attr.length if b == None: b=0 if e == None: e=attr.length if s == None: s=1 assert b >=0 and e >= 0 and s >= 0 and e >= b,'Only positive slice values are supported for pyCtypesJvsip __getitem__' attr.length = _nlength(b,e,s) attr.offset += b * attr.stride attr.stride *= s assert (attr.length -1) * attr.stride + attr.offset < self.block.length, 'Implementation Error. View exceeds Block. Should not be here' v.putattrib(attr) return v else: return self.get(index) def __setitem__(self,index,val): assert isinstance(index,int) or isinstance(index,long),'Put item is only supported for single index at this time' self.put(index,val) return self def __iadd__(self,other): # self += other return _add(other,self,self) def __add__(self,other): # new = self + other return _add(other,self,self.empty) def __radd__(self,other): # new = other + self return _add(other,self,self.empty) def __imul__(self,other):# *=other _mul(other,self,self) return self def __mul__(self,other): return _mul(other,self,self.empty) def __rmul__(self,other): # other * self return _mul(other,self,self.empty) def __isub__(self,other): # -=other if '__View' in repr(other): _sub(self,other,self) else: _add(-other,self,self) return self def __sub__(self,other):#self - other retval=self.empty if '__View' in repr(other): return _sub(self,other,retval) else: return _add(-other,self,retval) def __rsub__(self,other): #other - self retval=self.empty return _sub(other,self,retval) <file_sep>/* Created RJudd August 30, 2002 */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_chold_d.c,v 2.3 2004/09/22 02:25:39 judd Exp $ */ #include"vsip.h" #include"vsip_mviewattributes_d.h" #include"vsip_vviewattributes_d.h" #include"vsip_choldattributes_d.h" static int VI_cholesky_low_d( const vsip_mview_d *A) { int retval = 0; vsip_index j,k; vsip_length n = A->col_length; double scale = 1; vsip_scalar_d re_scale = 1; vsip_scalar_d *aptr_re; vsip_scalar_d *bptr_re; vsip_stride col_str = A->col_stride * A->block->rstride; vsip_offset off_a_col = (A->offset + A->col_stride) * A->block->rstride; vsip_stride A_diag_str = (A->col_stride + A->row_stride) * A->block->rstride; vsip_offset off_A_diag = A->block->rstride * A->offset; vsip_length m0 = n; vsip_length m; vsip_offset off_b0 = off_A_diag; vsip_offset off_b; vsip_offset off_a0 = off_A_diag; vsip_offset off_a; vsip_offset off_as; for(k=0; k<n; k++){ vsip_scalar_d *a_kk_r = A->block->array + off_A_diag; off_A_diag += A_diag_str; if(*a_kk_r <= 0){ retval++; return retval; } else { scale = (double) *a_kk_r; scale = sqrt(scale); } re_scale = (vsip_scalar_d) scale; *a_kk_r = re_scale; aptr_re = A->block->array + off_a_col; off_a_col += A_diag_str; m0--; m = m0; while(m-- > 0){ *aptr_re /= re_scale; aptr_re += col_str; } off_b = off_b0; off_b0 += A_diag_str; off_as = off_a0; off_a = off_a0; off_a0 += A_diag_str; for(j=k+1; j<n; j++){ off_b += col_str; bptr_re = A->block->array + off_b; off_as += col_str; re_scale = - *(A->block->array + off_as); off_a += A_diag_str; aptr_re = A->block->array + off_a; m = n - j; while(m-- >0){ *aptr_re += *bptr_re * re_scale; aptr_re += col_str; bptr_re += col_str; } } } return retval; } static int VI_cholesky_upp_d( const vsip_mview_d *A) { int retval = 0; vsip_length n = A->row_length; vsip_length m0 = n - 1; vsip_length m = m0; vsip_length m_in =0; vsip_index j,k; double scale; vsip_offset a_kk_off = A->block->rstride * A->offset; vsip_scalar_d *a_kk_r = A->block->array + a_kk_off; vsip_stride A_diag_str = A->block->rstride * (A->row_stride + A->col_stride); vsip_scalar_d re_scale; vsip_scalar_d *a_re_ptr, *a_re_ptr0; vsip_scalar_d *b_re_ptr, *b_re_ptr0; vsip_stride a_str = A->block->rstride * A->row_stride; vsip_stride b_str = a_str; for(k=0; k<n; k++){ /* for the diagonal a_kk must have zero imaginary */ if(*a_kk_r <= 0){ retval++; return retval; } else { scale = (double) *a_kk_r; scale = sqrt(scale); } *a_kk_r = (vsip_scalar_d) scale; a_re_ptr = a_kk_r + a_str; while(m-- > 0){ *a_re_ptr /= (vsip_scalar_d)scale; a_re_ptr += a_str; } m0--; m=m0; a_re_ptr0 = a_kk_r + A_diag_str; b_re_ptr0 = a_kk_r + b_str; for(j=k+1; j<n; j++){ m_in = n-j; a_re_ptr = a_re_ptr0; b_re_ptr = b_re_ptr0; re_scale = - *(b_re_ptr); while(m_in-- >0){ *a_re_ptr += *b_re_ptr * re_scale; a_re_ptr += a_str; b_re_ptr += b_str; } a_re_ptr0 += A_diag_str; b_re_ptr0 += b_str; } a_kk_r += A_diag_str; } return retval; } int vsip_chold_d( vsip_chol_d* chol, const vsip_mview_d *A) { int retval = 0; chol->matrix = A; if(chol->uplo == VSIP_TR_LOW){ retval = VI_cholesky_low_d(A); } else { /* must be vsip_tr_upp */ retval = VI_cholesky_upp_d(A); } return retval; } <file_sep>// // qrd.swift // // // Created by <NAME> on 11/11/17. // import Foundation import vsip // MARK: - QRD public class QRD{ fileprivate struct Attrib { let m: Int let n: Int let op: vsip_qrd_qopt } var type: Scalar.Types { return (jVsip?.type)! } fileprivate(set) var amSet = false fileprivate let attrib: Attrib var columnLength: Int { get{ return attrib.m } } var rowLength: Int { get { return attrib.n } } var qrdNoSaveQ: Bool{ get { return attrib.op == VSIP_QRD_NOSAVEQ } } var qrdSaveQ: Bool{ get { return attrib.op == VSIP_QRD_SAVEQ } } var qrdSaveQ1: Bool{ get { return attrib.op == VSIP_QRD_SAVEQ1 } } fileprivate class qr { var tryVsip : OpaquePointer? var vsip: OpaquePointer { get { return tryVsip! } } let jInit : JVSIP var type : Scalar.Types? init(){ jInit = JVSIP() } } fileprivate class qr_f: qr { init(m: Int, n: Int, qopt: vsip_qrd_qopt){ super.init() type = .f if let qrd = vsip_qrd_create_f(vsip_length(m),vsip_length(n),qopt){ self.tryVsip = qrd } else { preconditionFailure("Failed to create vsip qrd object") } } deinit{ /* if _isDebugAssertConfiguration(){ print("vsip_qrd_destroy_f \(jInit.myId.int32Value)") }*/ vsip_qrd_destroy_f(self.vsip) } } fileprivate class qr_d: qr { init(m: Int, n: Int, qopt: vsip_qrd_qopt){ super.init() type = .d if let qrd = vsip_qrd_create_d(vsip_length(m),vsip_length(n),qopt){ self.tryVsip = qrd } else { preconditionFailure("Failed to create vsip qrd object") } } deinit{ /* if _isDebugAssertConfiguration(){ print("vsip_qrd_destroy_d \(jInit.myId.int32Value)") }*/ vsip_qrd_destroy_d(self.vsip) } } fileprivate class cqr_f: qr { init(m: Int, n: Int, qopt: vsip_qrd_qopt){ super.init() type = .cf if let qrd = vsip_cqrd_create_f(vsip_length(m),vsip_length(n),qopt){ self.tryVsip = qrd } else { preconditionFailure("Failed to create vsip qrd object") } } deinit{ /*if _isDebugAssertConfiguration(){ print("vsip_cqrd_destroy_f \(jInit.myId.int32Value)") }*/ vsip_cqrd_destroy_f(self.vsip) } } fileprivate class cqr_d: qr { init(m: Int, n: Int, qopt: vsip_qrd_qopt){ super.init() type = .cd if let qrd = vsip_cqrd_create_d(vsip_length(m),vsip_length(n),qopt){ self.tryVsip = qrd } else { preconditionFailure("Failed to create vsip qrd object") } } deinit{ /*if _isDebugAssertConfiguration(){ print("vsip_cqrd_destroy_d \(jInit.myId.int32Value)") }*/ vsip_cqrd_destroy_d(self.vsip) } } fileprivate let jVsip : qr? fileprivate var vsip: OpaquePointer { get { return (jVsip?.vsip)! } } public init(type: Scalar.Types, columnLength: Int, rowLength: Int, qopt: vsip_qrd_qopt) { attrib = Attrib(m: columnLength, n: rowLength, op: qopt) self.amSet = false switch type { case .f: jVsip = qr_f(m: columnLength, n: rowLength, qopt: qopt) case .d: jVsip = qr_d(m: columnLength, n: rowLength, qopt: qopt) case .cf: jVsip = cqr_f(m: columnLength, n: rowLength, qopt: qopt) case .cd: jVsip = cqr_d(m: columnLength, n: rowLength, qopt: qopt) default: self.jVsip = nil assert(false, "QRD not supported for this type") } } public func decompose(_ aMatrix: Matrix) -> Scalar { let t = (aMatrix.type, self.type) switch t { case(.f,.f): return Scalar(vsip_qrd_f(self.vsip, aMatrix.vsip)) case(.d,.d): return Scalar(vsip_qrd_d(self.vsip, aMatrix.vsip)) case(.cf,.cf): return Scalar(vsip_cqrd_f(self.vsip, aMatrix.vsip)) case(.cd,.cd): return Scalar(vsip_cqrd_d(self.vsip, aMatrix.vsip)) default: preconditionFailure("Types \(t) not supported for qrd decompostion") } } public func prodq(matrixOperator op: vsip_mat_op, matrixSide side: vsip_mat_side, matrix: Matrix) { let t = (self.type, op, side, matrix.type) switch t{ case (.f, VSIP_MAT_NTRANS, VSIP_MAT_LSIDE, .f): vsip_qrdprodq_f(self.vsip, op, side, matrix.vsip) case (.d, VSIP_MAT_NTRANS, VSIP_MAT_LSIDE, .d): vsip_qrdprodq_d(self.vsip, op, side, matrix.vsip) case (.cf, VSIP_MAT_NTRANS, VSIP_MAT_LSIDE, .cf): vsip_cqrdprodq_f(self.vsip, op, side, matrix.vsip) case (.cd, VSIP_MAT_NTRANS, VSIP_MAT_LSIDE, .cd): vsip_cqrdprodq_d(self.vsip, op, side, matrix.vsip) case (.f, VSIP_MAT_TRANS, VSIP_MAT_LSIDE, .f): vsip_qrdprodq_f(self.vsip, op, side, matrix.vsip) case (.d, VSIP_MAT_TRANS, VSIP_MAT_LSIDE, .d): vsip_qrdprodq_d(self.vsip, op, side, matrix.vsip) case (.cf, VSIP_MAT_HERM, VSIP_MAT_LSIDE, .cf): vsip_cqrdprodq_f(self.vsip, op, side, matrix.vsip) case (.cd, VSIP_MAT_HERM, VSIP_MAT_LSIDE, .cd): vsip_cqrdprodq_d(self.vsip, op, side, matrix.vsip) case (.f, VSIP_MAT_NTRANS, VSIP_MAT_RSIDE, .f): vsip_qrdprodq_f(self.vsip, op, side, matrix.vsip) case (.d, VSIP_MAT_NTRANS, VSIP_MAT_RSIDE, .d): vsip_qrdprodq_d(self.vsip, op, side, matrix.vsip) case (.cf, VSIP_MAT_NTRANS, VSIP_MAT_RSIDE, .cf): vsip_cqrdprodq_f(self.vsip, op, side, matrix.vsip) case (.cd, VSIP_MAT_NTRANS, VSIP_MAT_RSIDE, .cd): vsip_cqrdprodq_d(self.vsip, op, side, matrix.vsip) case (.f, VSIP_MAT_TRANS, VSIP_MAT_RSIDE, .f): vsip_qrdprodq_f(self.vsip, op, side, matrix.vsip) case (.d, VSIP_MAT_TRANS, VSIP_MAT_RSIDE, .d): vsip_qrdprodq_d(self.vsip, op, side, matrix.vsip) case (.cf, VSIP_MAT_HERM, VSIP_MAT_RSIDE, .cf): vsip_cqrdprodq_f(self.vsip, op, side, matrix.vsip) case (.cd, VSIP_MAT_HERM, VSIP_MAT_RSIDE, .cd): vsip_cqrdprodq_d(self.vsip, op, side, matrix.vsip) default: preconditionFailure("Type \(t) not supported for QRD prodq.") } } public func solveR(matrixOperator opR: vsip_mat_op, alpha: Scalar, XB: Matrix) -> Int { let t = (opR, XB.type) switch t { case (VSIP_MAT_NTRANS, .f): return Int(vsip_qrdsolr_f(self.vsip, VSIP_MAT_NTRANS, alpha.vsip_f, XB.vsip)) case (VSIP_MAT_TRANS, .f): return Int(vsip_qrdsolr_f(self.vsip, VSIP_MAT_TRANS, alpha.vsip_f, XB.vsip)) case (VSIP_MAT_NTRANS, .d): return Int(vsip_qrdsolr_d(self.vsip, VSIP_MAT_NTRANS, alpha.vsip_d, XB.vsip)) case (VSIP_MAT_TRANS, .f): return Int(vsip_qrdsolr_d(self.vsip, VSIP_MAT_TRANS, alpha.vsip_d, XB.vsip)) case (VSIP_MAT_NTRANS, .cf): return Int(vsip_cqrdsolr_f(self.vsip, VSIP_MAT_NTRANS, alpha.vsip_cf, XB.vsip)) case (VSIP_MAT_TRANS, .cf): return Int(vsip_cqrdsolr_f(self.vsip, VSIP_MAT_HERM, alpha.vsip_cf, XB.vsip)) case (VSIP_MAT_NTRANS, .d): return Int(vsip_cqrdsolr_d(self.vsip, VSIP_MAT_NTRANS, alpha.vsip_cd, XB.vsip)) case (VSIP_MAT_TRANS, .f): return Int(vsip_cqrdsolr_d(self.vsip, VSIP_MAT_HERM, alpha.vsip_cd, XB.vsip)) default: preconditionFailure("Case \(t) not found for solveR") } } public func solveCovariance(solveProblem prob: vsip_qrd_prob, XB: Matrix) -> Int { let t = (prob, XB.type) switch t { case (VSIP_COV, .f): return Int(vsip_qrsol_f(self.vsip, VSIP_COV, XB.vsip)) case (VSIP_LLS, .f): return Int(vsip_qrsol_f(self.vsip, VSIP_LLS, XB.vsip)) case (VSIP_COV, .d): return Int(vsip_qrsol_d(self.vsip, VSIP_COV, XB.vsip)) case (VSIP_LLS, .d): return Int(vsip_qrsol_d(self.vsip, VSIP_LLS, XB.vsip)) case (VSIP_COV, .cf): return Int(vsip_cqrsol_f(self.vsip, VSIP_COV, XB.vsip)) case (VSIP_LLS, .cf): return Int(vsip_cqrsol_f(self.vsip, VSIP_LLS, XB.vsip)) case (VSIP_COV, .cd): return Int(vsip_cqrsol_d(self.vsip, VSIP_COV, XB.vsip)) case (VSIP_LLS, .cd): return Int(vsip_cqrsol_d(self.vsip, VSIP_LLS, XB.vsip)) default: preconditionFailure("Case \(t) not found for Covariance/LeastSquare solver") } } } <file_sep>/* Created RJudd September 18, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mcreate_bl.c,v 2.0 2003/02/22 15:18:55 judd Exp $ */ #include"vsip.h" #include"VI_blockcreate_bl.h" #include"VI_blockdestroy_bl.h" vsip_mview_bl* (vsip_mcreate_bl)( vsip_length col_length, vsip_length row_length, vsip_major major, vsip_memory_hint mem_hint) { vsip_block_bl* b = VI_blockcreate_bl( (vsip_length)(col_length * row_length), mem_hint); vsip_mview_bl *v = (vsip_mview_bl*)NULL; if(b != NULL){ v = (major == VSIP_ROW) ? vsip_mbind_bl(b, (vsip_offset)0, (vsip_stride)row_length, col_length, (vsip_stride)1, row_length) : vsip_mbind_bl(b, (vsip_offset)0, (vsip_stride)1,col_length, (vsip_stride)col_length, row_length); if(v == (vsip_mview_bl*)NULL) VI_blockdestroy_bl(b); } return v; } <file_sep>#!python # Example of solving Ax=b using LU import pyJvsip as pv import cProfile #create a non-singular matrix def mySolve(A,x): p,l,u=A.plu u.usolve(l.lsolve(x.permute(p))) N=100 A=pv.create('mview_d',N,N).fill(-1.0) A.diagview(0).ramp(1,1.1) A.diagview(1).fill(2) A.diagview(-1).fill(2) #create a test 'good x' vector x0=pv.create('vview_d',A.rowlength).ramp(.1,.1) # create and calculate a y vector based on x vector y0=A.prod(x0) #Create a copy of y0 to solve for x0 xy=y0.copy #check to make sure A non-singular. Det uses up A so make copy if A.copy.det < .0001: print('Matrix may be singular') #solve longhand using plu and triangular backsolverssolvers (mySolve Above) print('RESULTS for mySolve function using plu method and backsolvers') cProfile.run('mySolve(A,xy)') #check to see if xy is x0 chk=(xy-x0).sumsqval if chk > .000001: print('We don\'t seem to have the right answer using mySolve; check=%e'%chk) else: print('Check only %e. This is probably correct for mySolve function'%chk) #Solve using luSolve method. Make copy of A so we con't overwrite it xy=y0.copy print('\nRESULTS using VSIPL LUD solver methods') cProfile.run('A.copy.luSolve(xy)') chk = (xy-x0).sumsqval chk=(xy-x0).sumsqval if chk > .000001: print('We don\'t seem to have the right answer using luSolve method; check=%e'%chk) else: print('Check is %e. This is probably correct for luSolve method'%chk)<file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: get_put_length_bl.h,v 2.1 2007/04/18 17:05:56 judd Exp $ */ static void get_put_length_bl(void){ printf("********\nTEST get_put_length_bl\n"); { vsip_offset ivo = 3; vsip_stride ivs = 0; vsip_length ivl = 3; vsip_length jvl = 5; vsip_stride irs = 0, ics = 0; vsip_length irl = 2, icl = 3; vsip_length jrl = 5, jcl = 2; vsip_block_bl *b = vsip_blockcreate_bl(80,VSIP_MEM_NONE); vsip_vview_bl *v = vsip_vbind_bl(b,ivo,ivs,ivl); vsip_mview_bl *m = vsip_mbind_bl(b,ivo,ics,icl,irs,irl); vsip_length s; printf("test vgetlength_bl\n"); fflush(stdout); { s = vsip_vgetlength_bl(v); (s == ivl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test vputlength_bl\n"); fflush(stdout); { vsip_vputlength_bl(v,jvl); s = vsip_vgetlength_bl(v); (s == jvl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /*************************************************************************/ printf("test mgetrowlength_bl\n"); fflush(stdout); { s = vsip_mgetrowlength_bl(m); (s == irl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputrowlength_bl\n"); fflush(stdout); { vsip_mputrowlength_bl(m,jrl); s = vsip_mgetrowlength_bl(m); (s == jrl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } printf("test mgetcollength_bl\n"); fflush(stdout); { s = vsip_mgetcollength_bl(m); (s == icl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } /* the next test requires the previous test to be correct */ printf("test mputcollength_bl\n"); fflush(stdout); { vsip_mputcollength_bl(m,jcl); s = vsip_mgetcollength_bl(m); (s == jcl) ? printf("length correct\n") : printf("length error \n"); fflush(stdout); } vsip_vdestroy_bl(v); vsip_malldestroy_bl(m); } return; } <file_sep>/* Created by RJudd June 10, 2002 */ /* SPAWARSYSCEN code 2857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_ccfftop_d_fftw.h,v 2.0 2003/02/22 15:18:30 judd Exp $ */ /* use fftw for calculation */ #include"vsip.h" #include"vsip_fftattributes_d.h" #include"vsip_cvviewattributes_d.h" #if !defined(VSIP_ASSUME_COMPLEX_IS_INTERLEAVED) #define __VSIPL_CVCOPY_TO_FFTW_D #define __VSIPL_CVCOPY_FROM_FFTW_D #endif #include"VI_fftw_obj.h" /*========================================================*/ void vsip_ccfftop_d(const vsip_fft_d *Offt, const vsip_cvview_d *x, const vsip_cvview_d *y) { vsip_fft_d Nfft = *Offt; vsip_fft_d *fft = &Nfft; vsipl_fftw_obj *obj = (vsipl_fftw_obj*)fft->ext_fft_obj; #if defined(VSIP_ASSUME_COMPLEX_IS_INTERLEAVED) int howmany = 1; int istride = (int)x->stride; int ostride = (int)y->stride; int idist = 1, odist = 1; fftw_complex *in = (fftw_complex*)(x->block->R->array + x->offset * x->block->R->rstride); fftw_complex *out = (fftw_complex*)(y->block->R->array + y->offset * y->block->R->rstride); fftw(obj->p,howmany,in,istride,idist,out,ostride,odist); #else vsipl_cvcopy_to_fftw_d(x,obj); fftw_one(obj->p,obj->in,obj->out); vsipl_cvcopy_from_fftw_d(obj,y); #endif if (fft->scale != 1) vsip_rscvmul_d(fft->scale,y,y); return; } <file_sep>/* Created RJudd September 19, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_mbind_f.c,v 2.0 2003/02/22 15:18:54 judd Exp $ */ #include"vsip.h" #include"vsip_mviewattributes_f.h" vsip_mview_f* (vsip_mbind_f)( const vsip_block_f* b, vsip_offset o, vsip_stride c_s, vsip_length c_l, vsip_stride r_s, vsip_length r_l) { vsip_mview_f* v = (vsip_mview_f*)malloc(sizeof(vsip_mview_f)); if(v != (vsip_mview_f*)NULL){ v->block = (vsip_block_f*)b; v->offset = o; v->row_stride = r_s; v->col_stride = c_s; v->row_length = r_l; v->col_length = c_l; v->markings = VSIP_VALID_STRUCTURE_OBJECT; } return v; } <file_sep>#!/usr/bin/env python """ setup.py file for tvcpp code and SWIG Wrapper """ from distutils.core import setup, Extension vsip_module = Extension('_vsip', sources=[ './c_src/copyToList.c', './c_src/indexptr.c', './c_src/py_jdot.c', './c_src/vsipScalarFunctions.c', './c_src/jvsip_mprod.c', '../../c_VSIP_src/vsip_arg_d.c', '../../c_VSIP_src/vsip_arg_f.c', '../../c_VSIP_src/vsip_blockadmit_bl.c', '../../c_VSIP_src/vsip_blockadmit_d.c', '../../c_VSIP_src/vsip_blockadmit_f.c', '../../c_VSIP_src/vsip_blockadmit_i.c', '../../c_VSIP_src/vsip_blockadmit_mi.c', '../../c_VSIP_src/vsip_blockadmit_si.c', '../../c_VSIP_src/vsip_blockadmit_uc.c', '../../c_VSIP_src/vsip_blockadmit_vi.c', '../../c_VSIP_src/vsip_blockbind_bl.c', '../../c_VSIP_src/vsip_blockbind_d.c', '../../c_VSIP_src/vsip_blockbind_f.c', '../../c_VSIP_src/vsip_blockbind_i.c', '../../c_VSIP_src/vsip_blockbind_mi.c', '../../c_VSIP_src/vsip_blockbind_si.c', '../../c_VSIP_src/vsip_blockbind_uc.c', '../../c_VSIP_src/vsip_blockbind_vi.c', '../../c_VSIP_src/vsip_blockcreate_bl.c', '../../c_VSIP_src/vsip_blockcreate_d.c', '../../c_VSIP_src/vsip_blockcreate_f.c', '../../c_VSIP_src/vsip_blockcreate_i.c', '../../c_VSIP_src/vsip_blockcreate_mi.c', '../../c_VSIP_src/vsip_blockcreate_si.c', '../../c_VSIP_src/vsip_blockcreate_uc.c', '../../c_VSIP_src/vsip_blockcreate_vi.c', '../../c_VSIP_src/vsip_blockdestroy_bl.c', '../../c_VSIP_src/vsip_blockdestroy_d.c', '../../c_VSIP_src/vsip_blockdestroy_f.c', '../../c_VSIP_src/vsip_blockdestroy_i.c', '../../c_VSIP_src/vsip_blockdestroy_mi.c', '../../c_VSIP_src/vsip_blockdestroy_si.c', '../../c_VSIP_src/vsip_blockdestroy_uc.c', '../../c_VSIP_src/vsip_blockdestroy_vi.c', '../../c_VSIP_src/vsip_blockfind_bl.c', '../../c_VSIP_src/vsip_blockfind_d.c', '../../c_VSIP_src/vsip_blockfind_f.c', '../../c_VSIP_src/vsip_blockfind_i.c', '../../c_VSIP_src/vsip_blockfind_mi.c', '../../c_VSIP_src/vsip_blockfind_si.c', '../../c_VSIP_src/vsip_blockfind_uc.c', '../../c_VSIP_src/vsip_blockfind_vi.c', '../../c_VSIP_src/vsip_blockrebind_bl.c', '../../c_VSIP_src/vsip_blockrebind_d.c', '../../c_VSIP_src/vsip_blockrebind_f.c', '../../c_VSIP_src/vsip_blockrebind_i.c', '../../c_VSIP_src/vsip_blockrebind_mi.c', '../../c_VSIP_src/vsip_blockrebind_si.c', '../../c_VSIP_src/vsip_blockrebind_uc.c', '../../c_VSIP_src/vsip_blockrebind_vi.c', '../../c_VSIP_src/vsip_blockrelease_bl.c', '../../c_VSIP_src/vsip_blockrelease_d.c', '../../c_VSIP_src/vsip_blockrelease_f.c', '../../c_VSIP_src/vsip_blockrelease_i.c', '../../c_VSIP_src/vsip_blockrelease_mi.c', '../../c_VSIP_src/vsip_blockrelease_si.c', '../../c_VSIP_src/vsip_blockrelease_uc.c', '../../c_VSIP_src/vsip_blockrelease_vi.c', '../../c_VSIP_src/vsip_cadd_d.c', '../../c_VSIP_src/vsip_cadd_f.c', '../../c_VSIP_src/vsip_cblockadmit_d.c', '../../c_VSIP_src/vsip_cblockadmit_f.c', '../../c_VSIP_src/vsip_cblockbind_d.c', '../../c_VSIP_src/vsip_cblockbind_f.c', '../../c_VSIP_src/vsip_cblockcreate_d.c', '../../c_VSIP_src/vsip_cblockcreate_f.c', '../../c_VSIP_src/vsip_cblockdestroy_d.c', '../../c_VSIP_src/vsip_cblockdestroy_f.c', '../../c_VSIP_src/vsip_cblockfind_d.c', '../../c_VSIP_src/vsip_cblockfind_f.c', '../../c_VSIP_src/vsip_cblockrebind_d.c', '../../c_VSIP_src/vsip_cblockrebind_f.c', '../../c_VSIP_src/vsip_cblockrelease_d.c', '../../c_VSIP_src/vsip_cblockrelease_f.c', '../../c_VSIP_src/vsip_ccfftip_create_d.c', '../../c_VSIP_src/vsip_ccfftip_create_f.c', '../../c_VSIP_src/vsip_ccfftip_d.c', '../../c_VSIP_src/vsip_ccfftip_f.c', '../../c_VSIP_src/vsip_ccfftmip_create_d.c', '../../c_VSIP_src/vsip_ccfftmip_create_f.c', '../../c_VSIP_src/vsip_ccfftmip_d.c', '../../c_VSIP_src/vsip_ccfftmip_f.c', '../../c_VSIP_src/vsip_ccfftmop_create_d.c', '../../c_VSIP_src/vsip_ccfftmop_create_f.c', '../../c_VSIP_src/vsip_ccfftmop_d.c', '../../c_VSIP_src/vsip_ccfftmop_f.c', '../../c_VSIP_src/vsip_ccfftop_create_d.c', '../../c_VSIP_src/vsip_ccfftop_create_f.c', '../../c_VSIP_src/vsip_ccfftop_d.c', '../../c_VSIP_src/vsip_ccfftop_f.c', '../../c_VSIP_src/vsip_cchold_create_d.c', '../../c_VSIP_src/vsip_cchold_create_f.c', '../../c_VSIP_src/vsip_cchold_d.c', '../../c_VSIP_src/vsip_cchold_destroy_d.c', '../../c_VSIP_src/vsip_cchold_destroy_f.c', '../../c_VSIP_src/vsip_cchold_f.c', '../../c_VSIP_src/vsip_cchold_getattr_d.c', '../../c_VSIP_src/vsip_cchold_getattr_f.c', '../../c_VSIP_src/vsip_ccholsol_d.c', '../../c_VSIP_src/vsip_ccholsol_f.c', '../../c_VSIP_src/vsip_ccorr1d_create_d.c', '../../c_VSIP_src/vsip_ccorr1d_create_f.c', '../../c_VSIP_src/vsip_ccorr1d_destroy_d.c', '../../c_VSIP_src/vsip_ccorr1d_destroy_f.c', '../../c_VSIP_src/vsip_ccorr1d_getattr_d.c', '../../c_VSIP_src/vsip_ccorr1d_getattr_f.c', '../../c_VSIP_src/vsip_ccorrelate1d_d.c', '../../c_VSIP_src/vsip_ccorrelate1d_f.c', '../../c_VSIP_src/vsip_ccovsol_d.c', '../../c_VSIP_src/vsip_ccovsol_f.c', '../../c_VSIP_src/vsip_cdiv_d.c', '../../c_VSIP_src/vsip_cdiv_f.c', '../../c_VSIP_src/vsip_cexp_d.c', '../../c_VSIP_src/vsip_cexp_f.c', '../../c_VSIP_src/vsip_rcfir_create_d.c', '../../c_VSIP_src/vsip_rcfir_create_f.c', '../../c_VSIP_src/vsip_rcfir_destroy_d.c', '../../c_VSIP_src/vsip_rcfir_destroy_f.c', '../../c_VSIP_src/vsip_rcfir_getattr_d.c', '../../c_VSIP_src/vsip_rcfir_getattr_f.c', '../../c_VSIP_src/vsip_rcfir_reset_d.c', '../../c_VSIP_src/vsip_rcfir_reset_f.c', '../../c_VSIP_src/vsip_rcfirflt_d.c', '../../c_VSIP_src/vsip_rcfirflt_f.c', '../../c_VSIP_src/vsip_cfir_create_d.c', '../../c_VSIP_src/vsip_cfir_create_f.c', '../../c_VSIP_src/vsip_cfir_destroy_d.c', '../../c_VSIP_src/vsip_cfir_destroy_f.c', '../../c_VSIP_src/vsip_cfir_getattr_d.c', '../../c_VSIP_src/vsip_cfir_getattr_f.c', '../../c_VSIP_src/vsip_cfir_reset_d.c', '../../c_VSIP_src/vsip_cfir_reset_f.c', '../../c_VSIP_src/vsip_cfirflt_d.c', '../../c_VSIP_src/vsip_cfirflt_f.c', '../../c_VSIP_src/vsip_cgemp_d.c', '../../c_VSIP_src/vsip_cgemp_f.c', '../../c_VSIP_src/vsip_cgems_d.c', '../../c_VSIP_src/vsip_cgems_f.c', '../../c_VSIP_src/vsip_chold_create_d.c', '../../c_VSIP_src/vsip_chold_create_f.c', '../../c_VSIP_src/vsip_chold_d.c', '../../c_VSIP_src/vsip_chold_destroy_d.c', '../../c_VSIP_src/vsip_chold_destroy_f.c', '../../c_VSIP_src/vsip_chold_f.c', '../../c_VSIP_src/vsip_chold_getattr_d.c', '../../c_VSIP_src/vsip_chold_getattr_f.c', '../../c_VSIP_src/vsip_cholsol_d.c', '../../c_VSIP_src/vsip_cholsol_f.c', '../../c_VSIP_src/vsip_cjmul_d.c', '../../c_VSIP_src/vsip_cjmul_f.c', '../../c_VSIP_src/vsip_cllsqsol_d.c', '../../c_VSIP_src/vsip_cllsqsol_f.c', '../../c_VSIP_src/vsip_clog_d.c', '../../c_VSIP_src/vsip_clog_f.c', '../../c_VSIP_src/vsip_clud_create_d.c', '../../c_VSIP_src/vsip_clud_create_f.c', '../../c_VSIP_src/vsip_clud_d.c', '../../c_VSIP_src/vsip_clud_destroy_d.c', '../../c_VSIP_src/vsip_clud_destroy_f.c', '../../c_VSIP_src/vsip_clud_f.c', '../../c_VSIP_src/vsip_clud_getattr_d.c', '../../c_VSIP_src/vsip_clud_getattr_f.c', '../../c_VSIP_src/vsip_clusol_d.c', '../../c_VSIP_src/vsip_clusol_f.c', '../../c_VSIP_src/vsip_cmadd_d.c', '../../c_VSIP_src/vsip_cmadd_f.c', '../../c_VSIP_src/vsip_cmag_d.c', '../../c_VSIP_src/vsip_cmag_f.c', '../../c_VSIP_src/vsip_cmagsq_d.c', '../../c_VSIP_src/vsip_cmagsq_f.c', '../../c_VSIP_src/vsip_cmalldestroy_d.c', '../../c_VSIP_src/vsip_cmalldestroy_f.c', '../../c_VSIP_src/vsip_cmbind_d.c', '../../c_VSIP_src/vsip_cmbind_f.c', '../../c_VSIP_src/vsip_cmcloneview_d.c', '../../c_VSIP_src/vsip_cmcloneview_f.c', '../../c_VSIP_src/vsip_cmcolview_d.c', '../../c_VSIP_src/vsip_cmcolview_f.c', '../../c_VSIP_src/vsip_cmconj_d.c', '../../c_VSIP_src/vsip_cmconj_f.c', '../../c_VSIP_src/vsip_cmcopy_d_d.c', '../../c_VSIP_src/vsip_cmcopy_d_f.c', '../../c_VSIP_src/vsip_cmcopy_f_d.c', '../../c_VSIP_src/vsip_cmcopy_f_f.c', '../../c_VSIP_src/vsip_cmcopyfrom_user_d.c', '../../c_VSIP_src/vsip_cmcopyfrom_user_f.c', '../../c_VSIP_src/vsip_cmcopyto_user_d.c', '../../c_VSIP_src/vsip_cmcopyto_user_f.c', '../../c_VSIP_src/vsip_cmcreate_d.c', '../../c_VSIP_src/vsip_cmcreate_f.c', '../../c_VSIP_src/vsip_cmdestroy_d.c', '../../c_VSIP_src/vsip_cmdestroy_f.c', '../../c_VSIP_src/vsip_cmdiagview_d.c', '../../c_VSIP_src/vsip_cmdiagview_f.c', '../../c_VSIP_src/vsip_cmdiv_d.c', '../../c_VSIP_src/vsip_cmdiv_f.c', '../../c_VSIP_src/vsip_cmexp_d.c', '../../c_VSIP_src/vsip_cmexp_f.c', '../../c_VSIP_src/vsip_cmexpoavg_d.c', '../../c_VSIP_src/vsip_cmexpoavg_f.c', '../../c_VSIP_src/vsip_cmfill_d.c', '../../c_VSIP_src/vsip_cmfill_f.c', '../../c_VSIP_src/vsip_cmgather_d.c', '../../c_VSIP_src/vsip_cmgather_f.c', '../../c_VSIP_src/vsip_cmget_d.c', '../../c_VSIP_src/vsip_cmget_f.c', '../../c_VSIP_src/vsip_cmgetattrib_d.c', '../../c_VSIP_src/vsip_cmgetattrib_f.c', '../../c_VSIP_src/vsip_cmgetblock_d.c', '../../c_VSIP_src/vsip_cmgetblock_f.c', '../../c_VSIP_src/vsip_cmgetcollength_d.c', '../../c_VSIP_src/vsip_cmgetcollength_f.c', '../../c_VSIP_src/vsip_cmgetcolstride_d.c', '../../c_VSIP_src/vsip_cmgetcolstride_f.c', '../../c_VSIP_src/vsip_cmgetoffset_d.c', '../../c_VSIP_src/vsip_cmgetoffset_f.c', '../../c_VSIP_src/vsip_cmgetrowlength_d.c', '../../c_VSIP_src/vsip_cmgetrowlength_f.c', '../../c_VSIP_src/vsip_cmgetrowstride_d.c', '../../c_VSIP_src/vsip_cmgetrowstride_f.c', '../../c_VSIP_src/vsip_cmherm_d.c', '../../c_VSIP_src/vsip_cmherm_f.c', '../../c_VSIP_src/vsip_cmjmul_d.c', '../../c_VSIP_src/vsip_cmjmul_f.c', '../../c_VSIP_src/vsip_cmkron_d.c', '../../c_VSIP_src/vsip_cmkron_f.c', '../../c_VSIP_src/vsip_cmlog_d.c', '../../c_VSIP_src/vsip_cmlog_f.c', '../../c_VSIP_src/vsip_cmmag_d.c', '../../c_VSIP_src/vsip_cmmag_f.c', '../../c_VSIP_src/vsip_cmmeansqval_d.c', '../../c_VSIP_src/vsip_cmmeansqval_f.c', '../../c_VSIP_src/vsip_cmmeanval_d.c', '../../c_VSIP_src/vsip_cmmeanval_f.c', '../../c_VSIP_src/vsip_cmmul_d.c', '../../c_VSIP_src/vsip_cmmul_f.c', '../../c_VSIP_src/vsip_cmneg_d.c', '../../c_VSIP_src/vsip_cmneg_f.c', '../../c_VSIP_src/vsip_cmplx_d.c', '../../c_VSIP_src/vsip_cmplx_f.c', '../../c_VSIP_src/vsip_cmprod3_d.c', '../../c_VSIP_src/vsip_cmprod3_f.c', '../../c_VSIP_src/vsip_cmprod4_d.c', '../../c_VSIP_src/vsip_cmprod4_f.c', '../../c_VSIP_src/vsip_cmprod_d.c', '../../c_VSIP_src/vsip_cmprod_f.c', '../../c_VSIP_src/vsip_cmprodh_d.c', '../../c_VSIP_src/vsip_cmprodh_f.c', '../../c_VSIP_src/vsip_cmprodj_d.c', '../../c_VSIP_src/vsip_cmprodj_f.c', '../../c_VSIP_src/vsip_cmprodt_d.c', '../../c_VSIP_src/vsip_cmprodt_f.c', '../../c_VSIP_src/vsip_cmput_d.c', '../../c_VSIP_src/vsip_cmput_f.c', '../../c_VSIP_src/vsip_cmputattrib_d.c', '../../c_VSIP_src/vsip_cmputattrib_f.c', '../../c_VSIP_src/vsip_cmputcollength_d.c', '../../c_VSIP_src/vsip_cmputcollength_f.c', '../../c_VSIP_src/vsip_cmputcolstride_d.c', '../../c_VSIP_src/vsip_cmputcolstride_f.c', '../../c_VSIP_src/vsip_cmputoffset_d.c', '../../c_VSIP_src/vsip_cmputoffset_f.c', '../../c_VSIP_src/vsip_cmputrowlength_d.c', '../../c_VSIP_src/vsip_cmputrowlength_f.c', '../../c_VSIP_src/vsip_cmputrowstride_d.c', '../../c_VSIP_src/vsip_cmputrowstride_f.c', '../../c_VSIP_src/vsip_cmrecip_d.c', '../../c_VSIP_src/vsip_cmrecip_f.c', '../../c_VSIP_src/vsip_cmrowview_d.c', '../../c_VSIP_src/vsip_cmrowview_f.c', '../../c_VSIP_src/vsip_cmrsdiv_d.c', '../../c_VSIP_src/vsip_cmrsdiv_f.c', '../../c_VSIP_src/vsip_cmscatter_d.c', '../../c_VSIP_src/vsip_cmscatter_f.c', '../../c_VSIP_src/vsip_cmsqrt_d.c', '../../c_VSIP_src/vsip_cmsqrt_f.c', '../../c_VSIP_src/vsip_cmsub_d.c', '../../c_VSIP_src/vsip_cmsub_f.c', '../../c_VSIP_src/vsip_cmsubview_d.c', '../../c_VSIP_src/vsip_cmsubview_f.c', '../../c_VSIP_src/vsip_cmsumval_d.c', '../../c_VSIP_src/vsip_cmsumval_f.c', '../../c_VSIP_src/vsip_cmswap_d.c', '../../c_VSIP_src/vsip_cmswap_f.c', '../../c_VSIP_src/vsip_cmtrans_d.c', '../../c_VSIP_src/vsip_cmtrans_f.c', '../../c_VSIP_src/vsip_cmtransview_d.c', '../../c_VSIP_src/vsip_cmtransview_f.c', '../../c_VSIP_src/vsip_cmul_d.c', '../../c_VSIP_src/vsip_cmul_f.c', '../../c_VSIP_src/vsip_cmvprod3_d.c', '../../c_VSIP_src/vsip_cmvprod3_f.c', '../../c_VSIP_src/vsip_cmvprod4_d.c', '../../c_VSIP_src/vsip_cmvprod4_f.c', '../../c_VSIP_src/vsip_cmvprod_d.c', '../../c_VSIP_src/vsip_cmvprod_f.c', '../../c_VSIP_src/vsip_cneg_d.c', '../../c_VSIP_src/vsip_cneg_f.c', '../../c_VSIP_src/vsip_conj_d.c', '../../c_VSIP_src/vsip_conj_f.c', '../../c_VSIP_src/vsip_conv1d_create_d.c', '../../c_VSIP_src/vsip_conv1d_create_f.c', '../../c_VSIP_src/vsip_conv1d_destroy_d.c', '../../c_VSIP_src/vsip_conv1d_destroy_f.c', '../../c_VSIP_src/vsip_conv1d_getattr_d.c', '../../c_VSIP_src/vsip_conv1d_getattr_f.c', '../../c_VSIP_src/vsip_convolve1d_d.c', '../../c_VSIP_src/vsip_convolve1d_f.c', '../../c_VSIP_src/vsip_corr1d_create_d.c', '../../c_VSIP_src/vsip_corr1d_create_f.c', '../../c_VSIP_src/vsip_corr1d_destroy_d.c', '../../c_VSIP_src/vsip_corr1d_destroy_f.c', '../../c_VSIP_src/vsip_corr1d_getattr_d.c', '../../c_VSIP_src/vsip_corr1d_getattr_f.c', '../../c_VSIP_src/vsip_correlate1d_d.c', '../../c_VSIP_src/vsip_correlate1d_f.c', '../../c_VSIP_src/vsip_covsol_d.c', '../../c_VSIP_src/vsip_covsol_f.c', '../../c_VSIP_src/vsip_cqrd_create_d.c', '../../c_VSIP_src/vsip_cqrd_create_f.c', '../../c_VSIP_src/vsip_cqrd_d.c', '../../c_VSIP_src/vsip_cqrd_destroy_d.c', '../../c_VSIP_src/vsip_cqrd_destroy_f.c', '../../c_VSIP_src/vsip_cqrd_f.c', '../../c_VSIP_src/vsip_cqrd_getattr_d.c', '../../c_VSIP_src/vsip_cqrd_getattr_f.c', '../../c_VSIP_src/vsip_cqrdprodq_d.c', '../../c_VSIP_src/vsip_cqrdprodq_f.c', '../../c_VSIP_src/vsip_cqrdsolr_d.c', '../../c_VSIP_src/vsip_cqrdsolr_f.c', '../../c_VSIP_src/vsip_cqrsol_d.c', '../../c_VSIP_src/vsip_cqrsol_f.c', '../../c_VSIP_src/vsip_crandn_d.c', '../../c_VSIP_src/vsip_crandn_f.c', '../../c_VSIP_src/vsip_crandu_d.c', '../../c_VSIP_src/vsip_crandu_f.c', '../../c_VSIP_src/vsip_crdiv_d.c', '../../c_VSIP_src/vsip_crdiv_f.c', '../../c_VSIP_src/vsip_crecip_d.c', '../../c_VSIP_src/vsip_crecip_f.c', '../../c_VSIP_src/vsip_crfftmop_create_d.c', '../../c_VSIP_src/vsip_crfftmop_create_f.c', '../../c_VSIP_src/vsip_crfftmop_d.c', '../../c_VSIP_src/vsip_crfftmop_f.c', '../../c_VSIP_src/vsip_crfftop_create_d.c', '../../c_VSIP_src/vsip_crfftop_create_f.c', '../../c_VSIP_src/vsip_crfftop_d.c', '../../c_VSIP_src/vsip_crfftop_f.c', '../../c_VSIP_src/vsip_crmdiv_d.c', '../../c_VSIP_src/vsip_crmdiv_f.c', '../../c_VSIP_src/vsip_crmsub_d.c', '../../c_VSIP_src/vsip_crmsub_f.c', '../../c_VSIP_src/vsip_crsub_d.c', '../../c_VSIP_src/vsip_crsub_f.c', '../../c_VSIP_src/vsip_crvdiv_d.c', '../../c_VSIP_src/vsip_crvdiv_f.c', '../../c_VSIP_src/vsip_crvsub_d.c', '../../c_VSIP_src/vsip_crvsub_f.c', '../../c_VSIP_src/vsip_csmadd_d.c', '../../c_VSIP_src/vsip_csmadd_f.c', '../../c_VSIP_src/vsip_csmdiv_d.c', '../../c_VSIP_src/vsip_csmdiv_f.c', '../../c_VSIP_src/vsip_csmmul_d.c', '../../c_VSIP_src/vsip_csmmul_f.c', '../../c_VSIP_src/vsip_csmsub_d.c', '../../c_VSIP_src/vsip_csmsub_f.c', '../../c_VSIP_src/vsip_csqrt_d.c', '../../c_VSIP_src/vsip_csqrt_f.c', '../../c_VSIP_src/vsip_cstorage.c', '../../c_VSIP_src/vsip_csub_d.c', '../../c_VSIP_src/vsip_csub_f.c', '../../c_VSIP_src/vsip_csvadd_d.c', '../../c_VSIP_src/vsip_csvadd_f.c', '../../c_VSIP_src/vsip_csvdiv_d.c', '../../c_VSIP_src/vsip_csvdiv_f.c', '../../c_VSIP_src/vsip_csvmul_d.c', '../../c_VSIP_src/vsip_csvmul_f.c', '../../c_VSIP_src/vsip_csvsub_d.c', '../../c_VSIP_src/vsip_csvsub_f.c', '../../c_VSIP_src/vsip_ctalldestroy_d.c', '../../c_VSIP_src/vsip_ctalldestroy_f.c', '../../c_VSIP_src/vsip_ctbind_d.c', '../../c_VSIP_src/vsip_ctbind_f.c', '../../c_VSIP_src/vsip_ctcloneview_d.c', '../../c_VSIP_src/vsip_ctcloneview_f.c', '../../c_VSIP_src/vsip_ctcreate_d.c', '../../c_VSIP_src/vsip_ctcreate_f.c', '../../c_VSIP_src/vsip_ctdestroy_d.c', '../../c_VSIP_src/vsip_ctdestroy_f.c', '../../c_VSIP_src/vsip_ctget_d.c', '../../c_VSIP_src/vsip_ctget_f.c', '../../c_VSIP_src/vsip_ctgetattrib_d.c', '../../c_VSIP_src/vsip_ctgetattrib_f.c', '../../c_VSIP_src/vsip_ctgetblock_d.c', '../../c_VSIP_src/vsip_ctgetblock_f.c', '../../c_VSIP_src/vsip_ctgetoffset_d.c', '../../c_VSIP_src/vsip_ctgetoffset_f.c', '../../c_VSIP_src/vsip_ctgetxlength_d.c', '../../c_VSIP_src/vsip_ctgetxlength_f.c', '../../c_VSIP_src/vsip_ctgetxstride_d.c', '../../c_VSIP_src/vsip_ctgetxstride_f.c', '../../c_VSIP_src/vsip_ctgetylength_d.c', '../../c_VSIP_src/vsip_ctgetylength_f.c', '../../c_VSIP_src/vsip_ctgetystride_d.c', '../../c_VSIP_src/vsip_ctgetystride_f.c', '../../c_VSIP_src/vsip_ctgetzlength_d.c', '../../c_VSIP_src/vsip_ctgetzlength_f.c', '../../c_VSIP_src/vsip_ctgetzstride_d.c', '../../c_VSIP_src/vsip_ctgetzstride_f.c', '../../c_VSIP_src/vsip_ctmatrixview_d.c', '../../c_VSIP_src/vsip_ctmatrixview_f.c', '../../c_VSIP_src/vsip_ctoepsol_d.c', '../../c_VSIP_src/vsip_ctoepsol_f.c', '../../c_VSIP_src/vsip_ctput_d.c', '../../c_VSIP_src/vsip_ctput_f.c', '../../c_VSIP_src/vsip_ctputattrib_d.c', '../../c_VSIP_src/vsip_ctputattrib_f.c', '../../c_VSIP_src/vsip_ctputoffset_d.c', '../../c_VSIP_src/vsip_ctputoffset_f.c', '../../c_VSIP_src/vsip_ctputxlength_d.c', '../../c_VSIP_src/vsip_ctputxlength_f.c', '../../c_VSIP_src/vsip_ctputxstride_d.c', '../../c_VSIP_src/vsip_ctputxstride_f.c', '../../c_VSIP_src/vsip_ctputylength_d.c', '../../c_VSIP_src/vsip_ctputylength_f.c', '../../c_VSIP_src/vsip_ctputystride_d.c', '../../c_VSIP_src/vsip_ctputystride_f.c', '../../c_VSIP_src/vsip_ctputzlength_d.c', '../../c_VSIP_src/vsip_ctputzlength_f.c', '../../c_VSIP_src/vsip_ctputzstride_d.c', '../../c_VSIP_src/vsip_ctputzstride_f.c', '../../c_VSIP_src/vsip_ctsubview_d.c', '../../c_VSIP_src/vsip_ctsubview_f.c', '../../c_VSIP_src/vsip_cttransview_d.c', '../../c_VSIP_src/vsip_cttransview_f.c', '../../c_VSIP_src/vsip_ctvectview_d.c', '../../c_VSIP_src/vsip_ctvectview_f.c', '../../c_VSIP_src/vsip_cvadd_d.c', '../../c_VSIP_src/vsip_cvadd_f.c', '../../c_VSIP_src/vsip_cvalldestroy_d.c', '../../c_VSIP_src/vsip_cvalldestroy_f.c', '../../c_VSIP_src/vsip_cvam_d.c', '../../c_VSIP_src/vsip_cvam_f.c', '../../c_VSIP_src/vsip_cvbind_d.c', '../../c_VSIP_src/vsip_cvbind_f.c', '../../c_VSIP_src/vsip_cvcloneview_d.c', '../../c_VSIP_src/vsip_cvcloneview_f.c', '../../c_VSIP_src/vsip_cvconj_d.c', '../../c_VSIP_src/vsip_cvconj_f.c', '../../c_VSIP_src/vsip_cvcopy_d_d.c', '../../c_VSIP_src/vsip_cvcopy_d_f.c', '../../c_VSIP_src/vsip_cvcopy_f_d.c', '../../c_VSIP_src/vsip_cvcopy_f_f.c', '../../c_VSIP_src/vsip_cvcopyfrom_user_d.c', '../../c_VSIP_src/vsip_cvcopyfrom_user_f.c', '../../c_VSIP_src/vsip_cvcopyto_user_d.c', '../../c_VSIP_src/vsip_cvcopyto_user_f.c', '../../c_VSIP_src/vsip_cvcreate_d.c', '../../c_VSIP_src/vsip_cvcreate_f.c', '../../c_VSIP_src/vsip_cvdestroy_d.c', '../../c_VSIP_src/vsip_cvdestroy_f.c', '../../c_VSIP_src/vsip_cvdiv_d.c', '../../c_VSIP_src/vsip_cvdiv_f.c', '../../c_VSIP_src/vsip_cvdot_d.c', '../../c_VSIP_src/vsip_cvdot_f.c', '../../c_VSIP_src/vsip_cvexp_d.c', '../../c_VSIP_src/vsip_cvexp_f.c', '../../c_VSIP_src/vsip_cvexpoavg_d.c', '../../c_VSIP_src/vsip_cvexpoavg_f.c', '../../c_VSIP_src/vsip_cvfill_d.c', '../../c_VSIP_src/vsip_cvfill_f.c', '../../c_VSIP_src/vsip_cvgather_d.c', '../../c_VSIP_src/vsip_cvgather_f.c', '../../c_VSIP_src/vsip_cvget_d.c', '../../c_VSIP_src/vsip_cvget_f.c', '../../c_VSIP_src/vsip_cvgetattrib_d.c', '../../c_VSIP_src/vsip_cvgetattrib_f.c', '../../c_VSIP_src/vsip_cvgetblock_d.c', '../../c_VSIP_src/vsip_cvgetblock_f.c', '../../c_VSIP_src/vsip_cvgetlength_d.c', '../../c_VSIP_src/vsip_cvgetlength_f.c', '../../c_VSIP_src/vsip_cvgetoffset_d.c', '../../c_VSIP_src/vsip_cvgetoffset_f.c', '../../c_VSIP_src/vsip_cvgetstride_d.c', '../../c_VSIP_src/vsip_cvgetstride_f.c', '../../c_VSIP_src/vsip_cvjdot_d.c', '../../c_VSIP_src/vsip_cvjdot_f.c', '../../c_VSIP_src/vsip_cvjmul_d.c', '../../c_VSIP_src/vsip_cvjmul_f.c', '../../c_VSIP_src/vsip_cvkron_d.c', '../../c_VSIP_src/vsip_cvkron_f.c', '../../c_VSIP_src/vsip_cvlog_d.c', '../../c_VSIP_src/vsip_cvlog_f.c', '../../c_VSIP_src/vsip_cvma_d.c', '../../c_VSIP_src/vsip_cvma_f.c', '../../c_VSIP_src/vsip_cvmag_d.c', '../../c_VSIP_src/vsip_cvmag_f.c', '../../c_VSIP_src/vsip_cvmeansqval_d.c', '../../c_VSIP_src/vsip_cvmeansqval_f.c', '../../c_VSIP_src/vsip_cvmeanval_d.c', '../../c_VSIP_src/vsip_cvmeanval_f.c', '../../c_VSIP_src/vsip_cvmmul_d.c', '../../c_VSIP_src/vsip_cvmmul_f.c', '../../c_VSIP_src/vsip_cvmodulate_d.c', '../../c_VSIP_src/vsip_cvmodulate_f.c', '../../c_VSIP_src/vsip_cvmprod_d.c', '../../c_VSIP_src/vsip_cvmprod_f.c', '../../c_VSIP_src/vsip_cvmsa_d.c', '../../c_VSIP_src/vsip_cvmsa_f.c', '../../c_VSIP_src/vsip_cvmsb_d.c', '../../c_VSIP_src/vsip_cvmsb_f.c', '../../c_VSIP_src/vsip_cvmul_d.c', '../../c_VSIP_src/vsip_cvmul_f.c', '../../c_VSIP_src/vsip_cvneg_d.c', '../../c_VSIP_src/vsip_cvneg_f.c', '../../c_VSIP_src/vsip_cvouter_d.c', '../../c_VSIP_src/vsip_cvouter_f.c', '../../c_VSIP_src/vsip_cvput_d.c', '../../c_VSIP_src/vsip_cvput_f.c', '../../c_VSIP_src/vsip_cvputattrib_d.c', '../../c_VSIP_src/vsip_cvputattrib_f.c', '../../c_VSIP_src/vsip_cvputlength_d.c', '../../c_VSIP_src/vsip_cvputlength_f.c', '../../c_VSIP_src/vsip_cvputoffset_d.c', '../../c_VSIP_src/vsip_cvputoffset_f.c', '../../c_VSIP_src/vsip_cvputstride_d.c', '../../c_VSIP_src/vsip_cvputstride_f.c', '../../c_VSIP_src/vsip_cmrandn_d.c', '../../c_VSIP_src/vsip_cmrandn_f.c', '../../c_VSIP_src/vsip_cmrandu_d.c', '../../c_VSIP_src/vsip_cmrandu_f.c', '../../c_VSIP_src/vsip_cvrandn_d.c', '../../c_VSIP_src/vsip_cvrandn_f.c', '../../c_VSIP_src/vsip_cvrandu_d.c', '../../c_VSIP_src/vsip_cvrandu_f.c', '../../c_VSIP_src/vsip_cvrecip_d.c', '../../c_VSIP_src/vsip_cvrecip_f.c', '../../c_VSIP_src/vsip_cvrsdiv_d.c', '../../c_VSIP_src/vsip_cvrsdiv_f.c', '../../c_VSIP_src/vsip_cvsam_d.c', '../../c_VSIP_src/vsip_cvsam_f.c', '../../c_VSIP_src/vsip_cvsbm_d.c', '../../c_VSIP_src/vsip_cvsbm_f.c', '../../c_VSIP_src/vsip_cvscatter_d.c', '../../c_VSIP_src/vsip_cvscatter_f.c', '../../c_VSIP_src/vsip_cvsma_d.c', '../../c_VSIP_src/vsip_cvsma_f.c', '../../c_VSIP_src/vsip_cvsmsa_d.c', '../../c_VSIP_src/vsip_cvsmsa_f.c', '../../c_VSIP_src/vsip_cvsqrt_d.c', '../../c_VSIP_src/vsip_cvsqrt_f.c', '../../c_VSIP_src/vsip_cvsub_d.c', '../../c_VSIP_src/vsip_cvsub_f.c', '../../c_VSIP_src/vsip_cvsubview_d.c', '../../c_VSIP_src/vsip_cvsubview_f.c', '../../c_VSIP_src/vsip_cvsumval_d.c', '../../c_VSIP_src/vsip_cvsumval_f.c', '../../c_VSIP_src/vsip_cvswap_d.c', '../../c_VSIP_src/vsip_cvswap_f.c', '../../c_VSIP_src/vsip_fft_destroy_d.c', '../../c_VSIP_src/vsip_fft_destroy_f.c', '../../c_VSIP_src/vsip_fft_getattr_d.c', '../../c_VSIP_src/vsip_fft_getattr_f.c', '../../c_VSIP_src/vsip_fftm_destroy_d.c', '../../c_VSIP_src/vsip_fftm_destroy_f.c', '../../c_VSIP_src/vsip_fftm_getattr_d.c', '../../c_VSIP_src/vsip_fftm_getattr_f.c', '../../c_VSIP_src/vsip_finalize.c', '../../c_VSIP_src/vsip_fir_create_d.c', '../../c_VSIP_src/vsip_fir_create_f.c', '../../c_VSIP_src/vsip_fir_destroy_d.c', '../../c_VSIP_src/vsip_fir_destroy_f.c', '../../c_VSIP_src/vsip_fir_getattr_d.c', '../../c_VSIP_src/vsip_fir_getattr_f.c', '../../c_VSIP_src/vsip_fir_reset_d.c', '../../c_VSIP_src/vsip_fir_reset_f.c', '../../c_VSIP_src/vsip_firflt_d.c', '../../c_VSIP_src/vsip_firflt_f.c', '../../c_VSIP_src/vsip_gemp_d.c', '../../c_VSIP_src/vsip_gemp_f.c', '../../c_VSIP_src/vsip_gems_d.c', '../../c_VSIP_src/vsip_gems_f.c', '../../c_VSIP_src/vsip_init.c', '../../c_VSIP_src/vsip_llsqsol_d.c', '../../c_VSIP_src/vsip_llsqsol_f.c', '../../c_VSIP_src/vsip_lud_create_d.c', '../../c_VSIP_src/vsip_lud_create_f.c', '../../c_VSIP_src/vsip_lud_d.c', '../../c_VSIP_src/vsip_lud_destroy_d.c', '../../c_VSIP_src/vsip_lud_destroy_f.c', '../../c_VSIP_src/vsip_lud_f.c', '../../c_VSIP_src/vsip_lud_getattr_d.c', '../../c_VSIP_src/vsip_lud_getattr_f.c', '../../c_VSIP_src/vsip_lusol_d.c', '../../c_VSIP_src/vsip_lusol_f.c', '../../c_VSIP_src/vsip_macos_d.c', '../../c_VSIP_src/vsip_macos_f.c', '../../c_VSIP_src/vsip_madd_d.c', '../../c_VSIP_src/vsip_madd_f.c', '../../c_VSIP_src/vsip_madd_i.c', '../../c_VSIP_src/vsip_madd_si.c', '../../c_VSIP_src/vsip_malldestroy_bl.c', '../../c_VSIP_src/vsip_malldestroy_d.c', '../../c_VSIP_src/vsip_malldestroy_f.c', '../../c_VSIP_src/vsip_malldestroy_i.c', '../../c_VSIP_src/vsip_malldestroy_si.c', '../../c_VSIP_src/vsip_malldestroy_uc.c', '../../c_VSIP_src/vsip_malltrue_bl.c', '../../c_VSIP_src/vsip_mand_i.c', '../../c_VSIP_src/vsip_mand_si.c', '../../c_VSIP_src/vsip_manytrue_bl.c', '../../c_VSIP_src/vsip_marg_d.c', '../../c_VSIP_src/vsip_marg_f.c', '../../c_VSIP_src/vsip_masin_d.c', '../../c_VSIP_src/vsip_masin_f.c', '../../c_VSIP_src/vsip_matan2_d.c', '../../c_VSIP_src/vsip_matan2_f.c', '../../c_VSIP_src/vsip_matan_d.c', '../../c_VSIP_src/vsip_matan_f.c', '../../c_VSIP_src/vsip_matindex.c', '../../c_VSIP_src/vsip_mbind_bl.c', '../../c_VSIP_src/vsip_mbind_d.c', '../../c_VSIP_src/vsip_mbind_f.c', '../../c_VSIP_src/vsip_mbind_i.c', '../../c_VSIP_src/vsip_mbind_si.c', '../../c_VSIP_src/vsip_mbind_uc.c', '../../c_VSIP_src/vsip_mclip_d.c', '../../c_VSIP_src/vsip_mclip_f.c', '../../c_VSIP_src/vsip_mclip_i.c', '../../c_VSIP_src/vsip_mclip_si.c', '../../c_VSIP_src/vsip_mcloneview_bl.c', '../../c_VSIP_src/vsip_mcloneview_d.c', '../../c_VSIP_src/vsip_mcloneview_f.c', '../../c_VSIP_src/vsip_mcloneview_i.c', '../../c_VSIP_src/vsip_mcloneview_si.c', '../../c_VSIP_src/vsip_mcloneview_uc.c', '../../c_VSIP_src/vsip_mcmagsq_d.c', '../../c_VSIP_src/vsip_mcmagsq_f.c', '../../c_VSIP_src/vsip_mcmaxmgsq_d.c', '../../c_VSIP_src/vsip_mcmaxmgsq_f.c', '../../c_VSIP_src/vsip_mcmaxmgsqval_d.c', '../../c_VSIP_src/vsip_mcmaxmgsqval_f.c', '../../c_VSIP_src/vsip_mcminmgsq_d.c', '../../c_VSIP_src/vsip_mcminmgsq_f.c', '../../c_VSIP_src/vsip_mcminmgsqval_d.c', '../../c_VSIP_src/vsip_mcminmgsqval_f.c', '../../c_VSIP_src/vsip_mcolview_bl.c', '../../c_VSIP_src/vsip_mcolview_d.c', '../../c_VSIP_src/vsip_mcolview_f.c', '../../c_VSIP_src/vsip_mcolview_i.c', '../../c_VSIP_src/vsip_mcolview_si.c', '../../c_VSIP_src/vsip_mcolview_uc.c', '../../c_VSIP_src/vsip_mcopy_bl_bl.c', '../../c_VSIP_src/vsip_mcopy_bl_d.c', '../../c_VSIP_src/vsip_mcopy_bl_f.c', '../../c_VSIP_src/vsip_mcopy_d_bl.c', '../../c_VSIP_src/vsip_mcopy_d_d.c', '../../c_VSIP_src/vsip_mcopy_d_f.c', '../../c_VSIP_src/vsip_mcopy_d_i.c', '../../c_VSIP_src/vsip_mcopy_d_uc.c', '../../c_VSIP_src/vsip_mcopy_f_bl.c', '../../c_VSIP_src/vsip_mcopy_f_d.c', '../../c_VSIP_src/vsip_mcopy_f_f.c', '../../c_VSIP_src/vsip_mcopy_f_i.c', '../../c_VSIP_src/vsip_mcopy_f_uc.c', '../../c_VSIP_src/vsip_mcopy_i_f.c', '../../c_VSIP_src/vsip_mcopy_i_i.c', '../../c_VSIP_src/vsip_mcopy_si_f.c', '../../c_VSIP_src/vsip_mcopyfrom_user_d.c', '../../c_VSIP_src/vsip_mcopyfrom_user_f.c', '../../c_VSIP_src/vsip_mcopyto_user_d.c', '../../c_VSIP_src/vsip_mcopyto_user_f.c', '../../c_VSIP_src/vsip_mcos_d.c', '../../c_VSIP_src/vsip_mcos_f.c', '../../c_VSIP_src/vsip_mcosh_d.c', '../../c_VSIP_src/vsip_mcosh_f.c', '../../c_VSIP_src/vsip_mcreate_bl.c', '../../c_VSIP_src/vsip_mcreate_d.c', '../../c_VSIP_src/vsip_mcreate_f.c', '../../c_VSIP_src/vsip_mcreate_i.c', '../../c_VSIP_src/vsip_mcreate_si.c', '../../c_VSIP_src/vsip_mcreate_uc.c', '../../c_VSIP_src/vsip_mcumsum_d.c', '../../c_VSIP_src/vsip_mcumsum_f.c', '../../c_VSIP_src/vsip_mcumsum_i.c', '../../c_VSIP_src/vsip_mcumsum_si.c', '../../c_VSIP_src/vsip_mdestroy_bl.c', '../../c_VSIP_src/vsip_mdestroy_d.c', '../../c_VSIP_src/vsip_mdestroy_f.c', '../../c_VSIP_src/vsip_mdestroy_i.c', '../../c_VSIP_src/vsip_mdestroy_si.c', '../../c_VSIP_src/vsip_mdestroy_uc.c', '../../c_VSIP_src/vsip_mdiagview_bl.c', '../../c_VSIP_src/vsip_mdiagview_d.c', '../../c_VSIP_src/vsip_mdiagview_f.c', '../../c_VSIP_src/vsip_mdiagview_i.c', '../../c_VSIP_src/vsip_mdiagview_si.c', '../../c_VSIP_src/vsip_mdiagview_uc.c', '../../c_VSIP_src/vsip_mdiv_d.c', '../../c_VSIP_src/vsip_mdiv_f.c', '../../c_VSIP_src/vsip_meuler_d.c', '../../c_VSIP_src/vsip_meuler_f.c', '../../c_VSIP_src/vsip_mexp10_d.c', '../../c_VSIP_src/vsip_mexp10_f.c', '../../c_VSIP_src/vsip_mexp_d.c', '../../c_VSIP_src/vsip_mexp_f.c', '../../c_VSIP_src/vsip_mexpoavg_d.c', '../../c_VSIP_src/vsip_mexpoavg_f.c', '../../c_VSIP_src/vsip_mfill_d.c', '../../c_VSIP_src/vsip_mfill_f.c', '../../c_VSIP_src/vsip_mfill_i.c', '../../c_VSIP_src/vsip_mfill_si.c', '../../c_VSIP_src/vsip_mfill_uc.c', '../../c_VSIP_src/vsip_mgather_d.c', '../../c_VSIP_src/vsip_mgather_f.c', '../../c_VSIP_src/vsip_mget_bl.c', '../../c_VSIP_src/vsip_mget_d.c', '../../c_VSIP_src/vsip_mget_f.c', '../../c_VSIP_src/vsip_mget_i.c', '../../c_VSIP_src/vsip_mget_si.c', '../../c_VSIP_src/vsip_mget_uc.c', '../../c_VSIP_src/vsip_mgetattrib_bl.c', '../../c_VSIP_src/vsip_mgetattrib_d.c', '../../c_VSIP_src/vsip_mgetattrib_f.c', '../../c_VSIP_src/vsip_mgetattrib_i.c', '../../c_VSIP_src/vsip_mgetattrib_si.c', '../../c_VSIP_src/vsip_mgetattrib_uc.c', '../../c_VSIP_src/vsip_mgetblock_bl.c', '../../c_VSIP_src/vsip_mgetblock_d.c', '../../c_VSIP_src/vsip_mgetblock_f.c', '../../c_VSIP_src/vsip_mgetblock_i.c', '../../c_VSIP_src/vsip_mgetblock_si.c', '../../c_VSIP_src/vsip_mgetblock_uc.c', '../../c_VSIP_src/vsip_mgetcollength_bl.c', '../../c_VSIP_src/vsip_mgetcollength_d.c', '../../c_VSIP_src/vsip_mgetcollength_f.c', '../../c_VSIP_src/vsip_mgetcollength_i.c', '../../c_VSIP_src/vsip_mgetcollength_si.c', '../../c_VSIP_src/vsip_mgetcollength_uc.c', '../../c_VSIP_src/vsip_mgetcolstride_bl.c', '../../c_VSIP_src/vsip_mgetcolstride_d.c', '../../c_VSIP_src/vsip_mgetcolstride_f.c', '../../c_VSIP_src/vsip_mgetcolstride_i.c', '../../c_VSIP_src/vsip_mgetcolstride_si.c', '../../c_VSIP_src/vsip_mgetcolstride_uc.c', '../../c_VSIP_src/vsip_mgetoffset_bl.c', '../../c_VSIP_src/vsip_mgetoffset_d.c', '../../c_VSIP_src/vsip_mgetoffset_f.c', '../../c_VSIP_src/vsip_mgetoffset_i.c', '../../c_VSIP_src/vsip_mgetoffset_si.c', '../../c_VSIP_src/vsip_mgetoffset_uc.c', '../../c_VSIP_src/vsip_mgetrowlength_bl.c', '../../c_VSIP_src/vsip_mgetrowlength_d.c', '../../c_VSIP_src/vsip_mgetrowlength_f.c', '../../c_VSIP_src/vsip_mgetrowlength_i.c', '../../c_VSIP_src/vsip_mgetrowlength_si.c', '../../c_VSIP_src/vsip_mgetrowlength_uc.c', '../../c_VSIP_src/vsip_mgetrowstride_bl.c', '../../c_VSIP_src/vsip_mgetrowstride_d.c', '../../c_VSIP_src/vsip_mgetrowstride_f.c', '../../c_VSIP_src/vsip_mgetrowstride_i.c', '../../c_VSIP_src/vsip_mgetrowstride_si.c', '../../c_VSIP_src/vsip_mgetrowstride_uc.c', '../../c_VSIP_src/vsip_mhisto_d.c', '../../c_VSIP_src/vsip_mhisto_f.c', '../../c_VSIP_src/vsip_mhisto_i.c', '../../c_VSIP_src/vsip_mhisto_si.c', '../../c_VSIP_src/vsip_mhypot_d.c', '../../c_VSIP_src/vsip_mhypot_f.c', '../../c_VSIP_src/vsip_mimagview_d.c', '../../c_VSIP_src/vsip_mimagview_f.c', '../../c_VSIP_src/vsip_mindexbool.c', '../../c_VSIP_src/vsip_minterp_linear_d.c', '../../c_VSIP_src/vsip_minterp_linear_f.c', '../../c_VSIP_src/vsip_minterp_nearest_d.c', '../../c_VSIP_src/vsip_minterp_nearest_f.c', '../../c_VSIP_src/vsip_minterp_spline_d.c', '../../c_VSIP_src/vsip_minterp_spline_f.c', '../../c_VSIP_src/vsip_minvclip_d.c', '../../c_VSIP_src/vsip_minvclip_f.c', '../../c_VSIP_src/vsip_mkron_d.c', '../../c_VSIP_src/vsip_mkron_f.c', '../../c_VSIP_src/vsip_svlge_d.c', '../../c_VSIP_src/vsip_svlge_f.c', '../../c_VSIP_src/vsip_svlgt.c', '../../c_VSIP_src/vsip_svlle.c', '../../c_VSIP_src/vsip_svllt.c', '../../c_VSIP_src/vsip_svlne.c', '../../c_VSIP_src/vsip_mleq_d.c', '../../c_VSIP_src/vsip_mleq_f.c', '../../c_VSIP_src/vsip_mlge_d.c', '../../c_VSIP_src/vsip_mlge_f.c', '../../c_VSIP_src/vsip_mlgt_d.c', '../../c_VSIP_src/vsip_mlgt_f.c', '../../c_VSIP_src/vsip_mlle_d.c', '../../c_VSIP_src/vsip_mlle_f.c', '../../c_VSIP_src/vsip_mllt_d.c', '../../c_VSIP_src/vsip_mllt_f.c', '../../c_VSIP_src/vsip_mlne_d.c', '../../c_VSIP_src/vsip_mlne_f.c', '../../c_VSIP_src/vsip_mlog10_d.c', '../../c_VSIP_src/vsip_mlog10_f.c', '../../c_VSIP_src/vsip_mlog_d.c', '../../c_VSIP_src/vsip_mlog_f.c', '../../c_VSIP_src/vsip_mmag_d.c', '../../c_VSIP_src/vsip_mmag_f.c', '../../c_VSIP_src/vsip_mmax_d.c', '../../c_VSIP_src/vsip_mmax_f.c', '../../c_VSIP_src/vsip_mmaxmg_d.c', '../../c_VSIP_src/vsip_mmaxmg_f.c', '../../c_VSIP_src/vsip_mmaxmgval_d.c', '../../c_VSIP_src/vsip_mmaxmgval_f.c', '../../c_VSIP_src/vsip_mmaxval_d.c', '../../c_VSIP_src/vsip_mmaxval_f.c', '../../c_VSIP_src/vsip_mmaxval_i.c', '../../c_VSIP_src/vsip_mminval_i.c', '../../c_VSIP_src/vsip_mmaxval_si.c', '../../c_VSIP_src/vsip_mminval_si.c', '../../c_VSIP_src/vsip_mmeansqval_d.c', '../../c_VSIP_src/vsip_mmeansqval_f.c', '../../c_VSIP_src/vsip_mmeanval_d.c', '../../c_VSIP_src/vsip_mmeanval_f.c', '../../c_VSIP_src/vsip_mmin_d.c', '../../c_VSIP_src/vsip_mmin_f.c', '../../c_VSIP_src/vsip_mminmg_d.c', '../../c_VSIP_src/vsip_mminmg_f.c', '../../c_VSIP_src/vsip_mminmgval_d.c', '../../c_VSIP_src/vsip_mminmgval_f.c', '../../c_VSIP_src/vsip_mminval_d.c', '../../c_VSIP_src/vsip_mminval_f.c', '../../c_VSIP_src/vsip_mmul_d.c', '../../c_VSIP_src/vsip_mmul_f.c', '../../c_VSIP_src/vsip_mneg_d.c', '../../c_VSIP_src/vsip_mneg_f.c', '../../c_VSIP_src/vsip_mpermute_create_d.c', '../../c_VSIP_src/vsip_mpermute_create_f.c', '../../c_VSIP_src/vsip_mpermute_d.c', '../../c_VSIP_src/vsip_mpermute_f.c', '../../c_VSIP_src/vsip_mpermute_once_d.c', '../../c_VSIP_src/vsip_mpermute_once_f.c', '../../c_VSIP_src/vsip_cmpermute_once_d.c', '../../c_VSIP_src/vsip_cmpermute_once_f.c', '../../c_VSIP_src/vsip_mprod3_d.c', '../../c_VSIP_src/vsip_mprod3_f.c', '../../c_VSIP_src/vsip_mprod4_d.c', '../../c_VSIP_src/vsip_mprod4_f.c', '../../c_VSIP_src/vsip_mprod_d.c', '../../c_VSIP_src/vsip_mprod_f.c', '../../c_VSIP_src/vsip_mprodt_d.c', '../../c_VSIP_src/vsip_mprodt_f.c', '../../c_VSIP_src/vsip_mput_bl.c', '../../c_VSIP_src/vsip_mput_d.c', '../../c_VSIP_src/vsip_mput_f.c', '../../c_VSIP_src/vsip_mput_i.c', '../../c_VSIP_src/vsip_mput_si.c', '../../c_VSIP_src/vsip_mput_uc.c', '../../c_VSIP_src/vsip_mputattrib_bl.c', '../../c_VSIP_src/vsip_mputattrib_d.c', '../../c_VSIP_src/vsip_mputattrib_f.c', '../../c_VSIP_src/vsip_mputattrib_i.c', '../../c_VSIP_src/vsip_mputattrib_si.c', '../../c_VSIP_src/vsip_mputattrib_uc.c', '../../c_VSIP_src/vsip_mputcollength_bl.c', '../../c_VSIP_src/vsip_mputcollength_d.c', '../../c_VSIP_src/vsip_mputcollength_f.c', '../../c_VSIP_src/vsip_mputcollength_i.c', '../../c_VSIP_src/vsip_mputcollength_si.c', '../../c_VSIP_src/vsip_mputcollength_uc.c', '../../c_VSIP_src/vsip_mputcolstride_bl.c', '../../c_VSIP_src/vsip_mputcolstride_d.c', '../../c_VSIP_src/vsip_mputcolstride_f.c', '../../c_VSIP_src/vsip_mputcolstride_i.c', '../../c_VSIP_src/vsip_mputcolstride_si.c', '../../c_VSIP_src/vsip_mputcolstride_uc.c', '../../c_VSIP_src/vsip_mputoffset_bl.c', '../../c_VSIP_src/vsip_mputoffset_d.c', '../../c_VSIP_src/vsip_mputoffset_f.c', '../../c_VSIP_src/vsip_mputoffset_i.c', '../../c_VSIP_src/vsip_mputoffset_si.c', '../../c_VSIP_src/vsip_mputoffset_uc.c', '../../c_VSIP_src/vsip_mputrowlength_bl.c', '../../c_VSIP_src/vsip_mputrowlength_d.c', '../../c_VSIP_src/vsip_mputrowlength_f.c', '../../c_VSIP_src/vsip_mputrowlength_i.c', '../../c_VSIP_src/vsip_mputrowlength_si.c', '../../c_VSIP_src/vsip_mputrowlength_uc.c', '../../c_VSIP_src/vsip_mputrowstride_bl.c', '../../c_VSIP_src/vsip_mputrowstride_d.c', '../../c_VSIP_src/vsip_mputrowstride_f.c', '../../c_VSIP_src/vsip_mputrowstride_i.c', '../../c_VSIP_src/vsip_mputrowstride_si.c', '../../c_VSIP_src/vsip_mputrowstride_uc.c', '../../c_VSIP_src/vsip_mrealview_d.c', '../../c_VSIP_src/vsip_mrealview_f.c', '../../c_VSIP_src/vsip_mrecip_d.c', '../../c_VSIP_src/vsip_mrecip_f.c', '../../c_VSIP_src/vsip_mrowview_bl.c', '../../c_VSIP_src/vsip_mrowview_d.c', '../../c_VSIP_src/vsip_mrowview_f.c', '../../c_VSIP_src/vsip_mrowview_i.c', '../../c_VSIP_src/vsip_mrowview_si.c', '../../c_VSIP_src/vsip_mrowview_uc.c', '../../c_VSIP_src/vsip_mrsqrt_d.c', '../../c_VSIP_src/vsip_mrsqrt_f.c', '../../c_VSIP_src/vsip_mscatter_d.c', '../../c_VSIP_src/vsip_mscatter_f.c', '../../c_VSIP_src/vsip_msdiv_d.c', '../../c_VSIP_src/vsip_msdiv_f.c', '../../c_VSIP_src/vsip_msin_d.c', '../../c_VSIP_src/vsip_msin_f.c', '../../c_VSIP_src/vsip_msinh_d.c', '../../c_VSIP_src/vsip_msinh_f.c', '../../c_VSIP_src/vsip_msq_d.c', '../../c_VSIP_src/vsip_msq_f.c', '../../c_VSIP_src/vsip_msqrt_d.c', '../../c_VSIP_src/vsip_msqrt_f.c', '../../c_VSIP_src/vsip_msub_d.c', '../../c_VSIP_src/vsip_msub_f.c', '../../c_VSIP_src/vsip_msub_i.c', '../../c_VSIP_src/vsip_msub_si.c', '../../c_VSIP_src/vsip_msubview_bl.c', '../../c_VSIP_src/vsip_msubview_d.c', '../../c_VSIP_src/vsip_msubview_f.c', '../../c_VSIP_src/vsip_msubview_i.c', '../../c_VSIP_src/vsip_msubview_si.c', '../../c_VSIP_src/vsip_msubview_uc.c', '../../c_VSIP_src/vsip_msumsqval_d.c', '../../c_VSIP_src/vsip_msumsqval_f.c', '../../c_VSIP_src/vsip_msumval_bl.c', '../../c_VSIP_src/vsip_msumval_d.c', '../../c_VSIP_src/vsip_msumval_f.c', '../../c_VSIP_src/vsip_mswap_d.c', '../../c_VSIP_src/vsip_mswap_f.c', '../../c_VSIP_src/vsip_mtan_d.c', '../../c_VSIP_src/vsip_mtan_f.c', '../../c_VSIP_src/vsip_mtanh_d.c', '../../c_VSIP_src/vsip_mtanh_f.c', '../../c_VSIP_src/vsip_mtrans_d.c', '../../c_VSIP_src/vsip_mtrans_f.c', '../../c_VSIP_src/vsip_mtransview_bl.c', '../../c_VSIP_src/vsip_mtransview_d.c', '../../c_VSIP_src/vsip_mtransview_f.c', '../../c_VSIP_src/vsip_mtransview_i.c', '../../c_VSIP_src/vsip_mtransview_si.c', '../../c_VSIP_src/vsip_mtransview_uc.c', '../../c_VSIP_src/vsip_mvprod3_d.c', '../../c_VSIP_src/vsip_mvprod3_f.c', '../../c_VSIP_src/vsip_mvprod4_d.c', '../../c_VSIP_src/vsip_mvprod4_f.c', '../../c_VSIP_src/vsip_mvprod_d.c', '../../c_VSIP_src/vsip_mvprod_f.c', '../../c_VSIP_src/vsip_permute_destroy.c', '../../c_VSIP_src/vsip_permute_init.c', '../../c_VSIP_src/vsip_polar_d.c', '../../c_VSIP_src/vsip_polar_f.c', '../../c_VSIP_src/vsip_qrd_create_d.c', '../../c_VSIP_src/vsip_qrd_create_f.c', '../../c_VSIP_src/vsip_qrd_d.c', '../../c_VSIP_src/vsip_qrd_destroy_d.c', '../../c_VSIP_src/vsip_qrd_destroy_f.c', '../../c_VSIP_src/vsip_qrd_f.c', '../../c_VSIP_src/vsip_qrd_getattr_d.c', '../../c_VSIP_src/vsip_qrd_getattr_f.c', '../../c_VSIP_src/vsip_qrdprodq_d.c', '../../c_VSIP_src/vsip_qrdprodq_f.c', '../../c_VSIP_src/vsip_qrdsolr_d.c', '../../c_VSIP_src/vsip_qrdsolr_f.c', '../../c_VSIP_src/vsip_qrsol_d.c', '../../c_VSIP_src/vsip_qrsol_f.c', '../../c_VSIP_src/vsip_randcreate.c', '../../c_VSIP_src/vsip_randdestroy.c', '../../c_VSIP_src/vsip_randn_d.c', '../../c_VSIP_src/vsip_randn_f.c', '../../c_VSIP_src/vsip_randu_d.c', '../../c_VSIP_src/vsip_randu_f.c', '../../c_VSIP_src/vsip_rcadd_d.c', '../../c_VSIP_src/vsip_rcadd_f.c', '../../c_VSIP_src/vsip_rcfftmop_create_d.c', '../../c_VSIP_src/vsip_rcfftmop_create_f.c', '../../c_VSIP_src/vsip_rcfftmop_d.c', '../../c_VSIP_src/vsip_rcfftmop_f.c', '../../c_VSIP_src/vsip_rcfftop_create_d.c', '../../c_VSIP_src/vsip_rcfftop_create_f.c', '../../c_VSIP_src/vsip_rcfftop_d.c', '../../c_VSIP_src/vsip_rcfftop_f.c', '../../c_VSIP_src/vsip_rcmadd_d.c', '../../c_VSIP_src/vsip_rcmadd_f.c', '../../c_VSIP_src/vsip_rcmdiv_d.c', '../../c_VSIP_src/vsip_rcmdiv_f.c', '../../c_VSIP_src/vsip_rcmmul_d.c', '../../c_VSIP_src/vsip_rcmmul_f.c', '../../c_VSIP_src/vsip_rcmsub_d.c', '../../c_VSIP_src/vsip_rcmsub_f.c', '../../c_VSIP_src/vsip_rcmul_d.c', '../../c_VSIP_src/vsip_rcmul_f.c', '../../c_VSIP_src/vsip_rcsub_d.c', '../../c_VSIP_src/vsip_rcsub_f.c', '../../c_VSIP_src/vsip_rcvadd_d.c', '../../c_VSIP_src/vsip_rcvadd_f.c', '../../c_VSIP_src/vsip_rcvdiv_d.c', '../../c_VSIP_src/vsip_rcvdiv_f.c', '../../c_VSIP_src/vsip_rcvmul_d.c', '../../c_VSIP_src/vsip_rcvmul_f.c', '../../c_VSIP_src/vsip_rcvsub_d.c', '../../c_VSIP_src/vsip_rcvsub_f.c', '../../c_VSIP_src/vsip_rect_d.c', '../../c_VSIP_src/vsip_rect_f.c', '../../c_VSIP_src/vsip_rscmadd_d.c', '../../c_VSIP_src/vsip_rscmadd_f.c', '../../c_VSIP_src/vsip_rscmdiv_d.c', '../../c_VSIP_src/vsip_rscmdiv_f.c', '../../c_VSIP_src/vsip_rscmmul_d.c', '../../c_VSIP_src/vsip_rscmmul_f.c', '../../c_VSIP_src/vsip_rscmsub_d.c', '../../c_VSIP_src/vsip_rscmsub_f.c', '../../c_VSIP_src/vsip_rscvadd_d.c', '../../c_VSIP_src/vsip_rscvadd_f.c', '../../c_VSIP_src/vsip_rscvdiv_d.c', '../../c_VSIP_src/vsip_rscvdiv_f.c', '../../c_VSIP_src/vsip_rscvmul_d.c', '../../c_VSIP_src/vsip_rscvmul_f.c', '../../c_VSIP_src/vsip_rscvsub_d.c', '../../c_VSIP_src/vsip_rscvsub_f.c', '../../c_VSIP_src/vsip_rvcmmul_d.c', '../../c_VSIP_src/vsip_rvcmmul_f.c', '../../c_VSIP_src/vsip_smadd_d.c', '../../c_VSIP_src/vsip_smadd_f.c', '../../c_VSIP_src/vsip_smdiv_d.c', '../../c_VSIP_src/vsip_smdiv_f.c', '../../c_VSIP_src/vsip_smmul_d.c', '../../c_VSIP_src/vsip_smmul_f.c', '../../c_VSIP_src/vsip_smsub_d.c', '../../c_VSIP_src/vsip_smsub_f.c', '../../c_VSIP_src/vsip_smsub_i.c', '../../c_VSIP_src/vsip_smsub_si.c', '../../c_VSIP_src/vsip_spline_create_d.c', '../../c_VSIP_src/vsip_spline_create_f.c', '../../c_VSIP_src/vsip_spline_destroy_d.c', '../../c_VSIP_src/vsip_spline_destroy_f.c', '../../c_VSIP_src/vsip_svadd_d.c', '../../c_VSIP_src/vsip_svadd_f.c', '../../c_VSIP_src/vsip_svadd_i.c', '../../c_VSIP_src/vsip_svadd_si.c', '../../c_VSIP_src/vsip_svadd_uc.c', '../../c_VSIP_src/vsip_svadd_vi.c', '../../c_VSIP_src/jvsip_ceil.c', '../../c_VSIP_src/jvsip_floor.c', '../../c_VSIP_src/jvsip_round.c', '../../c_VSIP_src/jvsip_svd_f.c', '../../c_VSIP_src/jvsip_svd_d.c', '../../c_VSIP_src/vsip_svdiv_d.c', '../../c_VSIP_src/vsip_svdiv_f.c', '../../c_VSIP_src/vsip_svmul_d.c', '../../c_VSIP_src/vsip_svmul_f.c', '../../c_VSIP_src/vsip_svmul_i.c', '../../c_VSIP_src/vsip_svmul_si.c', '../../c_VSIP_src/vsip_svmul_uc.c', '../../c_VSIP_src/vsip_svsub_d.c', '../../c_VSIP_src/vsip_svsub_f.c', '../../c_VSIP_src/vsip_svsub_i.c', '../../c_VSIP_src/vsip_svsub_si.c', '../../c_VSIP_src/vsip_svsub_uc.c', '../../c_VSIP_src/vsip_svsub_vi.c', '../../c_VSIP_src/vsip_talldestroy_d.c', '../../c_VSIP_src/vsip_talldestroy_f.c', '../../c_VSIP_src/vsip_talldestroy_i.c', '../../c_VSIP_src/vsip_talldestroy_si.c', '../../c_VSIP_src/vsip_talldestroy_uc.c', '../../c_VSIP_src/vsip_tbind_d.c', '../../c_VSIP_src/vsip_tbind_f.c', '../../c_VSIP_src/vsip_tbind_i.c', '../../c_VSIP_src/vsip_tbind_si.c', '../../c_VSIP_src/vsip_tbind_uc.c', '../../c_VSIP_src/vsip_tcloneview_d.c', '../../c_VSIP_src/vsip_tcloneview_f.c', '../../c_VSIP_src/vsip_tcloneview_i.c', '../../c_VSIP_src/vsip_tcloneview_si.c', '../../c_VSIP_src/vsip_tcloneview_uc.c', '../../c_VSIP_src/vsip_tcreate_d.c', '../../c_VSIP_src/vsip_tcreate_f.c', '../../c_VSIP_src/vsip_tcreate_i.c', '../../c_VSIP_src/vsip_tcreate_si.c', '../../c_VSIP_src/vsip_tcreate_uc.c', '../../c_VSIP_src/vsip_tdestroy_d.c', '../../c_VSIP_src/vsip_tdestroy_f.c', '../../c_VSIP_src/vsip_tdestroy_i.c', '../../c_VSIP_src/vsip_tdestroy_si.c', '../../c_VSIP_src/vsip_tdestroy_uc.c', '../../c_VSIP_src/vsip_tget_d.c', '../../c_VSIP_src/vsip_tget_f.c', '../../c_VSIP_src/vsip_tget_i.c', '../../c_VSIP_src/vsip_tget_si.c', '../../c_VSIP_src/vsip_tget_uc.c', '../../c_VSIP_src/vsip_tgetattrib_d.c', '../../c_VSIP_src/vsip_tgetattrib_f.c', '../../c_VSIP_src/vsip_tgetattrib_i.c', '../../c_VSIP_src/vsip_tgetattrib_si.c', '../../c_VSIP_src/vsip_tgetattrib_uc.c', '../../c_VSIP_src/vsip_tgetblock_d.c', '../../c_VSIP_src/vsip_tgetblock_f.c', '../../c_VSIP_src/vsip_tgetblock_i.c', '../../c_VSIP_src/vsip_tgetblock_si.c', '../../c_VSIP_src/vsip_tgetblock_uc.c', '../../c_VSIP_src/vsip_tgetoffset_d.c', '../../c_VSIP_src/vsip_tgetoffset_f.c', '../../c_VSIP_src/vsip_tgetoffset_i.c', '../../c_VSIP_src/vsip_tgetoffset_si.c', '../../c_VSIP_src/vsip_tgetoffset_uc.c', '../../c_VSIP_src/vsip_tgetxlength_d.c', '../../c_VSIP_src/vsip_tgetxlength_f.c', '../../c_VSIP_src/vsip_tgetxlength_i.c', '../../c_VSIP_src/vsip_tgetxlength_si.c', '../../c_VSIP_src/vsip_tgetxlength_uc.c', '../../c_VSIP_src/vsip_tgetxstride_d.c', '../../c_VSIP_src/vsip_tgetxstride_f.c', '../../c_VSIP_src/vsip_tgetxstride_i.c', '../../c_VSIP_src/vsip_tgetxstride_si.c', '../../c_VSIP_src/vsip_tgetxstride_uc.c', '../../c_VSIP_src/vsip_tgetylength_d.c', '../../c_VSIP_src/vsip_tgetylength_f.c', '../../c_VSIP_src/vsip_tgetylength_i.c', '../../c_VSIP_src/vsip_tgetylength_si.c', '../../c_VSIP_src/vsip_tgetylength_uc.c', '../../c_VSIP_src/vsip_tgetystride_d.c', '../../c_VSIP_src/vsip_tgetystride_f.c', '../../c_VSIP_src/vsip_tgetystride_i.c', '../../c_VSIP_src/vsip_tgetystride_si.c', '../../c_VSIP_src/vsip_tgetystride_uc.c', '../../c_VSIP_src/vsip_tgetzlength_d.c', '../../c_VSIP_src/vsip_tgetzlength_f.c', '../../c_VSIP_src/vsip_tgetzlength_i.c', '../../c_VSIP_src/vsip_tgetzlength_si.c', '../../c_VSIP_src/vsip_tgetzlength_uc.c', '../../c_VSIP_src/vsip_tgetzstride_d.c', '../../c_VSIP_src/vsip_tgetzstride_f.c', '../../c_VSIP_src/vsip_tgetzstride_i.c', '../../c_VSIP_src/vsip_tgetzstride_si.c', '../../c_VSIP_src/vsip_tgetzstride_uc.c', '../../c_VSIP_src/vsip_timagview_d.c', '../../c_VSIP_src/vsip_timagview_f.c', '../../c_VSIP_src/vsip_tmatrixview_d.c', '../../c_VSIP_src/vsip_tmatrixview_f.c', '../../c_VSIP_src/vsip_tmatrixview_i.c', '../../c_VSIP_src/vsip_tmatrixview_si.c', '../../c_VSIP_src/vsip_tmatrixview_uc.c', '../../c_VSIP_src/vsip_toepsol_d.c', '../../c_VSIP_src/vsip_toepsol_f.c', '../../c_VSIP_src/vsip_tput_d.c', '../../c_VSIP_src/vsip_tput_f.c', '../../c_VSIP_src/vsip_tput_i.c', '../../c_VSIP_src/vsip_tput_si.c', '../../c_VSIP_src/vsip_tput_uc.c', '../../c_VSIP_src/vsip_tputattrib_d.c', '../../c_VSIP_src/vsip_tputattrib_f.c', '../../c_VSIP_src/vsip_tputattrib_i.c', '../../c_VSIP_src/vsip_tputattrib_si.c', '../../c_VSIP_src/vsip_tputattrib_uc.c', '../../c_VSIP_src/vsip_tputoffset_d.c', '../../c_VSIP_src/vsip_tputoffset_f.c', '../../c_VSIP_src/vsip_tputoffset_i.c', '../../c_VSIP_src/vsip_tputoffset_si.c', '../../c_VSIP_src/vsip_tputoffset_uc.c', '../../c_VSIP_src/vsip_tputxlength_d.c', '../../c_VSIP_src/vsip_tputxlength_f.c', '../../c_VSIP_src/vsip_tputxlength_i.c', '../../c_VSIP_src/vsip_tputxlength_si.c', '../../c_VSIP_src/vsip_tputxlength_uc.c', '../../c_VSIP_src/vsip_tputxstride_d.c', '../../c_VSIP_src/vsip_tputxstride_f.c', '../../c_VSIP_src/vsip_tputxstride_i.c', '../../c_VSIP_src/vsip_tputxstride_si.c', '../../c_VSIP_src/vsip_tputxstride_uc.c', '../../c_VSIP_src/vsip_tputylength_d.c', '../../c_VSIP_src/vsip_tputylength_f.c', '../../c_VSIP_src/vsip_tputylength_i.c', '../../c_VSIP_src/vsip_tputylength_si.c', '../../c_VSIP_src/vsip_tputylength_uc.c', '../../c_VSIP_src/vsip_tputystride_d.c', '../../c_VSIP_src/vsip_tputystride_f.c', '../../c_VSIP_src/vsip_tputystride_i.c', '../../c_VSIP_src/vsip_tputystride_si.c', '../../c_VSIP_src/vsip_tputystride_uc.c', '../../c_VSIP_src/vsip_tputzlength_d.c', '../../c_VSIP_src/vsip_tputzlength_f.c', '../../c_VSIP_src/vsip_tputzlength_i.c', '../../c_VSIP_src/vsip_tputzlength_si.c', '../../c_VSIP_src/vsip_tputzlength_uc.c', '../../c_VSIP_src/vsip_tputzstride_d.c', '../../c_VSIP_src/vsip_tputzstride_f.c', '../../c_VSIP_src/vsip_tputzstride_i.c', '../../c_VSIP_src/vsip_tputzstride_si.c', '../../c_VSIP_src/vsip_tputzstride_uc.c', '../../c_VSIP_src/vsip_trealview_d.c', '../../c_VSIP_src/vsip_trealview_f.c', '../../c_VSIP_src/vsip_tsubview_d.c', '../../c_VSIP_src/vsip_tsubview_f.c', '../../c_VSIP_src/vsip_tsubview_i.c', '../../c_VSIP_src/vsip_tsubview_si.c', '../../c_VSIP_src/vsip_tsubview_uc.c', '../../c_VSIP_src/vsip_ttransview_d.c', '../../c_VSIP_src/vsip_ttransview_f.c', '../../c_VSIP_src/vsip_ttransview_i.c', '../../c_VSIP_src/vsip_ttransview_si.c', '../../c_VSIP_src/vsip_ttransview_uc.c', '../../c_VSIP_src/vsip_tvectview_d.c', '../../c_VSIP_src/vsip_tvectview_f.c', '../../c_VSIP_src/vsip_tvectview_i.c', '../../c_VSIP_src/vsip_tvectview_si.c', '../../c_VSIP_src/vsip_tvectview_uc.c', '../../c_VSIP_src/vsip_vacos_d.c', '../../c_VSIP_src/vsip_vacos_f.c', '../../c_VSIP_src/vsip_vadd_d.c', '../../c_VSIP_src/vsip_vadd_f.c', '../../c_VSIP_src/vsip_vadd_i.c', '../../c_VSIP_src/vsip_vadd_si.c', '../../c_VSIP_src/vsip_vadd_uc.c', '../../c_VSIP_src/vsip_vadd_vi.c', '../../c_VSIP_src/vsip_valldestroy_bl.c', '../../c_VSIP_src/vsip_valldestroy_d.c', '../../c_VSIP_src/vsip_valldestroy_f.c', '../../c_VSIP_src/vsip_valldestroy_i.c', '../../c_VSIP_src/vsip_valldestroy_mi.c', '../../c_VSIP_src/vsip_valldestroy_si.c', '../../c_VSIP_src/vsip_valldestroy_uc.c', '../../c_VSIP_src/vsip_valldestroy_vi.c', '../../c_VSIP_src/vsip_valltrue_bl.c', '../../c_VSIP_src/vsip_vam_d.c', '../../c_VSIP_src/vsip_vam_f.c', '../../c_VSIP_src/vsip_vand_bl.c', '../../c_VSIP_src/vsip_vand_i.c', '../../c_VSIP_src/vsip_vand_si.c', '../../c_VSIP_src/vsip_vand_uc.c', '../../c_VSIP_src/vsip_vanytrue_bl.c', '../../c_VSIP_src/vsip_varg_d.c', '../../c_VSIP_src/vsip_varg_f.c', '../../c_VSIP_src/vsip_vasin_d.c', '../../c_VSIP_src/vsip_vasin_f.c', '../../c_VSIP_src/vsip_vatan2_d.c', '../../c_VSIP_src/vsip_vatan2_f.c', '../../c_VSIP_src/vsip_vatan_d.c', '../../c_VSIP_src/vsip_vatan_f.c', '../../c_VSIP_src/vsip_vbind_bl.c', '../../c_VSIP_src/vsip_vbind_d.c', '../../c_VSIP_src/vsip_vbind_f.c', '../../c_VSIP_src/vsip_vbind_i.c', '../../c_VSIP_src/vsip_vbind_mi.c', '../../c_VSIP_src/vsip_vbind_si.c', '../../c_VSIP_src/vsip_vbind_uc.c', '../../c_VSIP_src/vsip_vbind_vi.c', '../../c_VSIP_src/vsip_vclip_d.c', '../../c_VSIP_src/vsip_vclip_f.c', '../../c_VSIP_src/vsip_vclip_i.c', '../../c_VSIP_src/vsip_vclip_si.c', '../../c_VSIP_src/vsip_vclip_uc.c', '../../c_VSIP_src/vsip_vcloneview_bl.c', '../../c_VSIP_src/vsip_vcloneview_d.c', '../../c_VSIP_src/vsip_vcloneview_f.c', '../../c_VSIP_src/vsip_vcloneview_i.c', '../../c_VSIP_src/vsip_vcloneview_mi.c', '../../c_VSIP_src/vsip_vcloneview_si.c', '../../c_VSIP_src/vsip_vcloneview_uc.c', '../../c_VSIP_src/vsip_vcloneview_vi.c', '../../c_VSIP_src/vsip_vcmagsq_d.c', '../../c_VSIP_src/vsip_vcmagsq_f.c', '../../c_VSIP_src/vsip_vcmaxmgsq_d.c', '../../c_VSIP_src/vsip_vcmaxmgsq_f.c', '../../c_VSIP_src/vsip_vcmaxmgsqval_d.c', '../../c_VSIP_src/vsip_vcmaxmgsqval_f.c', '../../c_VSIP_src/vsip_vcminmgsq_d.c', '../../c_VSIP_src/vsip_vcminmgsq_f.c', '../../c_VSIP_src/vsip_vcminmgsqval_d.c', '../../c_VSIP_src/vsip_vcminmgsqval_f.c', '../../c_VSIP_src/vsip_vcmplx_d.c', '../../c_VSIP_src/vsip_vcmplx_f.c', '../../c_VSIP_src/vsip_mcmplx_d.c', '../../c_VSIP_src/vsip_mcmplx_f.c', '../../c_VSIP_src/vsip_vcopy_bl_bl.c', '../../c_VSIP_src/vsip_vcopy_bl_d.c', '../../c_VSIP_src/vsip_vcopy_bl_f.c', '../../c_VSIP_src/vsip_vcopy_d_bl.c', '../../c_VSIP_src/vsip_vcopy_d_d.c', '../../c_VSIP_src/vsip_vcopy_d_f.c', '../../c_VSIP_src/vsip_vcopy_d_i.c', '../../c_VSIP_src/vsip_vcopy_d_si.c', '../../c_VSIP_src/vsip_vcopy_d_uc.c', '../../c_VSIP_src/vsip_vcopy_d_vi.c', '../../c_VSIP_src/vsip_vcopy_f_bl.c', '../../c_VSIP_src/vsip_vcopy_f_d.c', '../../c_VSIP_src/vsip_vcopy_f_f.c', '../../c_VSIP_src/vsip_vcopy_f_i.c', '../../c_VSIP_src/vsip_vcopy_f_si.c', '../../c_VSIP_src/vsip_vcopy_f_uc.c', '../../c_VSIP_src/vsip_vcopy_f_vi.c', '../../c_VSIP_src/vsip_vcopy_i_d.c', '../../c_VSIP_src/vsip_vcopy_i_f.c', '../../c_VSIP_src/vsip_vcopy_i_i.c', '../../c_VSIP_src/vsip_vcopy_i_uc.c', '../../c_VSIP_src/vsip_vcopy_i_vi.c', '../../c_VSIP_src/vsip_vcopy_mi_mi.c', '../../c_VSIP_src/vsip_vcopy_si_d.c', '../../c_VSIP_src/vsip_vcopy_si_f.c', '../../c_VSIP_src/vsip_vcopy_si_si.c', '../../c_VSIP_src/vsip_vcopy_vi_i.c', '../../c_VSIP_src/vsip_vcopy_vi_vi.c', '../../c_VSIP_src/vsip_vcopy_vi_f.c', '../../c_VSIP_src/vsip_vcopy_vi_d.c', '../../c_VSIP_src/vsip_vcopyfrom_user_d.c', '../../c_VSIP_src/vsip_vcopyfrom_user_f.c', '../../c_VSIP_src/vsip_vcopyfrom_user_i.c', '../../c_VSIP_src/vsip_vcopyfrom_user_si.c', '../../c_VSIP_src/vsip_vcopyfrom_user_vi.c', '../../c_VSIP_src/vsip_vcopyto_user_d.c', '../../c_VSIP_src/vsip_vcopyto_user_f.c', '../../c_VSIP_src/vsip_vcopyto_user_i.c', '../../c_VSIP_src/vsip_vcopyto_user_si.c', '../../c_VSIP_src/vsip_vcopyto_user_vi.c', '../../c_VSIP_src/vsip_vcos_d.c', '../../c_VSIP_src/vsip_vcos_f.c', '../../c_VSIP_src/vsip_vcosh_d.c', '../../c_VSIP_src/vsip_vcosh_f.c', '../../c_VSIP_src/vsip_vcreate_bl.c', '../../c_VSIP_src/vsip_vcreate_blackman_d.c', '../../c_VSIP_src/vsip_vcreate_blackman_f.c', '../../c_VSIP_src/vsip_vcreate_cheby_d.c', '../../c_VSIP_src/vsip_vcreate_cheby_f.c', '../../c_VSIP_src/vsip_vcreate_d.c', '../../c_VSIP_src/vsip_vcreate_f.c', '../../c_VSIP_src/vsip_vcreate_hanning_d.c', '../../c_VSIP_src/vsip_vcreate_hanning_f.c', '../../c_VSIP_src/vsip_vcreate_i.c', '../../c_VSIP_src/vsip_vcreate_kaiser_d.c', '../../c_VSIP_src/vsip_vcreate_kaiser_f.c', '../../c_VSIP_src/vsip_vcreate_mi.c', '../../c_VSIP_src/vsip_vcreate_si.c', '../../c_VSIP_src/vsip_vcreate_uc.c', '../../c_VSIP_src/vsip_vcreate_vi.c', '../../c_VSIP_src/vsip_vcumsum_d.c', '../../c_VSIP_src/vsip_vcumsum_f.c', '../../c_VSIP_src/vsip_vcumsum_i.c', '../../c_VSIP_src/vsip_vcumsum_si.c', '../../c_VSIP_src/vsip_vdestroy_bl.c', '../../c_VSIP_src/vsip_vdestroy_d.c', '../../c_VSIP_src/vsip_vdestroy_f.c', '../../c_VSIP_src/vsip_vdestroy_i.c', '../../c_VSIP_src/vsip_vdestroy_mi.c', '../../c_VSIP_src/vsip_vdestroy_si.c', '../../c_VSIP_src/vsip_vdestroy_uc.c', '../../c_VSIP_src/vsip_vdestroy_vi.c', '../../c_VSIP_src/vsip_vdiv_d.c', '../../c_VSIP_src/vsip_vdiv_f.c', '../../c_VSIP_src/vsip_vdot_d.c', '../../c_VSIP_src/vsip_vdot_f.c', '../../c_VSIP_src/vsip_veuler_d.c', '../../c_VSIP_src/vsip_veuler_f.c', '../../c_VSIP_src/vsip_vexp10_d.c', '../../c_VSIP_src/vsip_vexp10_f.c', '../../c_VSIP_src/vsip_vexp_d.c', '../../c_VSIP_src/vsip_vexp_f.c', '../../c_VSIP_src/vsip_vexpoavg_d.c', '../../c_VSIP_src/vsip_vexpoavg_f.c', '../../c_VSIP_src/vsip_vfill_d.c', '../../c_VSIP_src/vsip_vfill_f.c', '../../c_VSIP_src/vsip_vfill_i.c', '../../c_VSIP_src/vsip_vfill_si.c', '../../c_VSIP_src/vsip_vfill_uc.c', '../../c_VSIP_src/vsip_vfill_vi.c', '../../c_VSIP_src/vsip_vfirst_d.c', '../../c_VSIP_src/vsip_vfirst_f.c', '../../c_VSIP_src/vsip_vfirst_i.c', '../../c_VSIP_src/vsip_vfirst_mi.c', '../../c_VSIP_src/vsip_vfirst_vi.c', '../../c_VSIP_src/vsip_vgather_d.c', '../../c_VSIP_src/vsip_vgather_f.c', '../../c_VSIP_src/vsip_vgather_i.c', '../../c_VSIP_src/vsip_vgather_mi.c', '../../c_VSIP_src/vsip_vgather_si.c', '../../c_VSIP_src/vsip_vgather_uc.c', '../../c_VSIP_src/vsip_vgather_vi.c', '../../c_VSIP_src/vsip_vget_bl.c', '../../c_VSIP_src/vsip_vget_d.c', '../../c_VSIP_src/vsip_vget_f.c', '../../c_VSIP_src/vsip_vget_i.c', '../../c_VSIP_src/vsip_vget_mi.c', '../../c_VSIP_src/vsip_vget_si.c', '../../c_VSIP_src/vsip_vget_uc.c', '../../c_VSIP_src/vsip_vget_vi.c', '../../c_VSIP_src/vsip_vgetattrib_bl.c', '../../c_VSIP_src/vsip_vgetattrib_d.c', '../../c_VSIP_src/vsip_vgetattrib_f.c', '../../c_VSIP_src/vsip_vgetattrib_i.c', '../../c_VSIP_src/vsip_vgetattrib_mi.c', '../../c_VSIP_src/vsip_vgetattrib_si.c', '../../c_VSIP_src/vsip_vgetattrib_uc.c', '../../c_VSIP_src/vsip_vgetattrib_vi.c', '../../c_VSIP_src/vsip_vgetblock_bl.c', '../../c_VSIP_src/vsip_vgetblock_d.c', '../../c_VSIP_src/vsip_vgetblock_f.c', '../../c_VSIP_src/vsip_vgetblock_i.c', '../../c_VSIP_src/vsip_vgetblock_mi.c', '../../c_VSIP_src/vsip_vgetblock_si.c', '../../c_VSIP_src/vsip_vgetblock_uc.c', '../../c_VSIP_src/vsip_vgetblock_vi.c', '../../c_VSIP_src/vsip_vgetlength_bl.c', '../../c_VSIP_src/vsip_vgetlength_d.c', '../../c_VSIP_src/vsip_vgetlength_f.c', '../../c_VSIP_src/vsip_vgetlength_i.c', '../../c_VSIP_src/vsip_vgetlength_mi.c', '../../c_VSIP_src/vsip_vgetlength_si.c', '../../c_VSIP_src/vsip_vgetlength_uc.c', '../../c_VSIP_src/vsip_vgetlength_vi.c', '../../c_VSIP_src/vsip_vgetoffset_bl.c', '../../c_VSIP_src/vsip_vgetoffset_d.c', '../../c_VSIP_src/vsip_vgetoffset_f.c', '../../c_VSIP_src/vsip_vgetoffset_i.c', '../../c_VSIP_src/vsip_vgetoffset_mi.c', '../../c_VSIP_src/vsip_vgetoffset_si.c', '../../c_VSIP_src/vsip_vgetoffset_uc.c', '../../c_VSIP_src/vsip_vgetoffset_vi.c', '../../c_VSIP_src/vsip_vgetstride_bl.c', '../../c_VSIP_src/vsip_vgetstride_d.c', '../../c_VSIP_src/vsip_vgetstride_f.c', '../../c_VSIP_src/vsip_vgetstride_i.c', '../../c_VSIP_src/vsip_vgetstride_mi.c', '../../c_VSIP_src/vsip_vgetstride_si.c', '../../c_VSIP_src/vsip_vgetstride_uc.c', '../../c_VSIP_src/vsip_vgetstride_vi.c', '../../c_VSIP_src/vsip_vhisto_d.c', '../../c_VSIP_src/vsip_vhisto_f.c', '../../c_VSIP_src/vsip_vhisto_i.c', '../../c_VSIP_src/vsip_vhisto_si.c', '../../c_VSIP_src/vsip_vhypot_d.c', '../../c_VSIP_src/vsip_vhypot_f.c', '../../c_VSIP_src/vsip_vimag_d.c', '../../c_VSIP_src/vsip_vimag_f.c', '../../c_VSIP_src/vsip_mimag_d.c', '../../c_VSIP_src/vsip_mimag_f.c', '../../c_VSIP_src/vsip_vimagview_d.c', '../../c_VSIP_src/vsip_vimagview_f.c', '../../c_VSIP_src/vsip_vindexbool.c', '../../c_VSIP_src/vsip_vinterp_linear_d.c', '../../c_VSIP_src/vsip_vinterp_linear_f.c', '../../c_VSIP_src/vsip_vinterp_nearest_d.c', '../../c_VSIP_src/vsip_vinterp_nearest_f.c', '../../c_VSIP_src/vsip_vinterp_spline_d.c', '../../c_VSIP_src/vsip_vinterp_spline_f.c', '../../c_VSIP_src/vsip_vinvclip_d.c', '../../c_VSIP_src/vsip_vinvclip_f.c', '../../c_VSIP_src/vsip_vinvclip_i.c', '../../c_VSIP_src/vsip_vinvclip_si.c', '../../c_VSIP_src/vsip_vinvclip_uc.c', '../../c_VSIP_src/vsip_vkron_d.c', '../../c_VSIP_src/vsip_vkron_f.c', '../../c_VSIP_src/vsip_svleq_d.c', '../../c_VSIP_src/vsip_svleq_f.c', '../../c_VSIP_src/vsip_vleq_d.c', '../../c_VSIP_src/vsip_vleq_f.c', '../../c_VSIP_src/vsip_vleq_i.c', '../../c_VSIP_src/vsip_vleq_si.c', '../../c_VSIP_src/vsip_vleq_uc.c', '../../c_VSIP_src/vsip_vlge_d.c', '../../c_VSIP_src/vsip_vlge_f.c', '../../c_VSIP_src/vsip_vlge_i.c', '../../c_VSIP_src/vsip_vlge_si.c', '../../c_VSIP_src/vsip_vlge_uc.c', '../../c_VSIP_src/vsip_vlgt_d.c', '../../c_VSIP_src/vsip_vlgt_f.c', '../../c_VSIP_src/vsip_vlgt_i.c', '../../c_VSIP_src/vsip_vlgt_si.c', '../../c_VSIP_src/vsip_vlgt_uc.c', '../../c_VSIP_src/vsip_vlle_d.c', '../../c_VSIP_src/vsip_vlle_f.c', '../../c_VSIP_src/vsip_vlle_i.c', '../../c_VSIP_src/vsip_vlle_si.c', '../../c_VSIP_src/vsip_vlle_uc.c', '../../c_VSIP_src/vsip_vllt_d.c', '../../c_VSIP_src/vsip_vllt_f.c', '../../c_VSIP_src/vsip_vllt_i.c', '../../c_VSIP_src/vsip_vllt_si.c', '../../c_VSIP_src/vsip_vllt_uc.c', '../../c_VSIP_src/vsip_vlne_d.c', '../../c_VSIP_src/vsip_vlne_f.c', '../../c_VSIP_src/vsip_vlne_i.c', '../../c_VSIP_src/vsip_vlne_si.c', '../../c_VSIP_src/vsip_vlne_uc.c', '../../c_VSIP_src/vsip_vlog10_d.c', '../../c_VSIP_src/vsip_vlog10_f.c', '../../c_VSIP_src/vsip_vlog_d.c', '../../c_VSIP_src/vsip_vlog_f.c', '../../c_VSIP_src/vsip_vma_d.c', '../../c_VSIP_src/vsip_vma_f.c', '../../c_VSIP_src/vsip_vmag_d.c', '../../c_VSIP_src/vsip_vmag_f.c', '../../c_VSIP_src/vsip_vmag_i.c', '../../c_VSIP_src/vsip_vmag_si.c', '../../c_VSIP_src/vsip_vmax_d.c', '../../c_VSIP_src/vsip_vmax_f.c', '../../c_VSIP_src/vsip_vmaxmg_d.c', '../../c_VSIP_src/vsip_vmaxmg_f.c', '../../c_VSIP_src/vsip_vmaxmgval_d.c', '../../c_VSIP_src/vsip_vmaxmgval_f.c', '../../c_VSIP_src/vsip_vmaxval_d.c', '../../c_VSIP_src/vsip_vmaxval_f.c', '../../c_VSIP_src/vsip_vmaxval_i.c', '../../c_VSIP_src/vsip_vminval_i.c', '../../c_VSIP_src/vsip_vmaxval_vi.c', '../../c_VSIP_src/vsip_vminval_vi.c', '../../c_VSIP_src/vsip_vmaxval_si.c', '../../c_VSIP_src/vsip_vminval_si.c', '../../c_VSIP_src/vsip_vmeansqval_d.c', '../../c_VSIP_src/vsip_vmeansqval_f.c', '../../c_VSIP_src/vsip_vmeanval_d.c', '../../c_VSIP_src/vsip_vmeanval_f.c', '../../c_VSIP_src/vsip_vmin_d.c', '../../c_VSIP_src/vsip_vmin_f.c', '../../c_VSIP_src/vsip_vminmg_d.c', '../../c_VSIP_src/vsip_vminmg_f.c', '../../c_VSIP_src/vsip_vminmgval_d.c', '../../c_VSIP_src/vsip_vminmgval_f.c', '../../c_VSIP_src/vsip_vminval_d.c', '../../c_VSIP_src/vsip_vminval_f.c', '../../c_VSIP_src/vsip_vmmul_d.c', '../../c_VSIP_src/vsip_vmmul_f.c', '../../c_VSIP_src/vsip_vmodulate_d.c', '../../c_VSIP_src/vsip_vmodulate_f.c', '../../c_VSIP_src/vsip_vmprod_d.c', '../../c_VSIP_src/vsip_vmprod_f.c', '../../c_VSIP_src/vsip_vmsa_d.c', '../../c_VSIP_src/vsip_vmsa_f.c', '../../c_VSIP_src/vsip_vmsb_d.c', '../../c_VSIP_src/vsip_vmsb_f.c', '../../c_VSIP_src/vsip_vmul_d.c', '../../c_VSIP_src/vsip_vmul_f.c', '../../c_VSIP_src/vsip_vmul_i.c', '../../c_VSIP_src/vsip_vmul_si.c', '../../c_VSIP_src/vsip_vmul_uc.c', '../../c_VSIP_src/vsip_vneg_d.c', '../../c_VSIP_src/vsip_vneg_f.c', '../../c_VSIP_src/vsip_vneg_i.c', '../../c_VSIP_src/vsip_vneg_si.c', '../../c_VSIP_src/vsip_vnot_bl.c', '../../c_VSIP_src/vsip_vnot_i.c', '../../c_VSIP_src/vsip_vnot_si.c', '../../c_VSIP_src/vsip_vnot_uc.c', '../../c_VSIP_src/vsip_vor_bl.c', '../../c_VSIP_src/vsip_vor_i.c', '../../c_VSIP_src/vsip_vor_si.c', '../../c_VSIP_src/vsip_vor_uc.c', '../../c_VSIP_src/vsip_vouter_d.c', '../../c_VSIP_src/vsip_vouter_f.c', '../../c_VSIP_src/vsip_vpolar_d.c', '../../c_VSIP_src/vsip_vpolar_f.c', '../../c_VSIP_src/vsip_mpolar_d.c', '../../c_VSIP_src/vsip_mpolar_f.c', '../../c_VSIP_src/vsip_vput_bl.c', '../../c_VSIP_src/vsip_vput_d.c', '../../c_VSIP_src/vsip_vput_f.c', '../../c_VSIP_src/vsip_vput_i.c', '../../c_VSIP_src/vsip_vput_mi.c', '../../c_VSIP_src/vsip_vput_si.c', '../../c_VSIP_src/vsip_vput_uc.c', '../../c_VSIP_src/vsip_vput_vi.c', '../../c_VSIP_src/vsip_vputattrib_bl.c', '../../c_VSIP_src/vsip_vputattrib_d.c', '../../c_VSIP_src/vsip_vputattrib_f.c', '../../c_VSIP_src/vsip_vputattrib_i.c', '../../c_VSIP_src/vsip_vputattrib_mi.c', '../../c_VSIP_src/vsip_vputattrib_si.c', '../../c_VSIP_src/vsip_vputattrib_uc.c', '../../c_VSIP_src/vsip_vputattrib_vi.c', '../../c_VSIP_src/vsip_vputlength_bl.c', '../../c_VSIP_src/vsip_vputlength_d.c', '../../c_VSIP_src/vsip_vputlength_f.c', '../../c_VSIP_src/vsip_vputlength_i.c', '../../c_VSIP_src/vsip_vputlength_mi.c', '../../c_VSIP_src/vsip_vputlength_si.c', '../../c_VSIP_src/vsip_vputlength_uc.c', '../../c_VSIP_src/vsip_vputlength_vi.c', '../../c_VSIP_src/vsip_vputoffset_bl.c', '../../c_VSIP_src/vsip_vputoffset_d.c', '../../c_VSIP_src/vsip_vputoffset_f.c', '../../c_VSIP_src/vsip_vputoffset_i.c', '../../c_VSIP_src/vsip_vputoffset_mi.c', '../../c_VSIP_src/vsip_vputoffset_si.c', '../../c_VSIP_src/vsip_vputoffset_uc.c', '../../c_VSIP_src/vsip_vputoffset_vi.c', '../../c_VSIP_src/vsip_vputstride_bl.c', '../../c_VSIP_src/vsip_vputstride_d.c', '../../c_VSIP_src/vsip_vputstride_f.c', '../../c_VSIP_src/vsip_vputstride_i.c', '../../c_VSIP_src/vsip_vputstride_mi.c', '../../c_VSIP_src/vsip_vputstride_si.c', '../../c_VSIP_src/vsip_vputstride_uc.c', '../../c_VSIP_src/vsip_vputstride_vi.c', '../../c_VSIP_src/vsip_vramp_d.c', '../../c_VSIP_src/vsip_vramp_f.c', '../../c_VSIP_src/vsip_vramp_i.c', '../../c_VSIP_src/vsip_vramp_si.c', '../../c_VSIP_src/vsip_vramp_uc.c', '../../c_VSIP_src/vsip_vramp_vi.c', '../../c_VSIP_src/vsip_mrandn_d.c', '../../c_VSIP_src/vsip_mrandn_f.c', '../../c_VSIP_src/vsip_mrandu_d.c', '../../c_VSIP_src/vsip_mrandu_f.c', '../../c_VSIP_src/vsip_vrandn_d.c', '../../c_VSIP_src/vsip_vrandn_f.c', '../../c_VSIP_src/vsip_vrandu_d.c', '../../c_VSIP_src/vsip_vrandu_f.c', '../../c_VSIP_src/vsip_vreal_d.c', '../../c_VSIP_src/vsip_vreal_f.c', '../../c_VSIP_src/vsip_mreal_d.c', '../../c_VSIP_src/vsip_mreal_f.c', '../../c_VSIP_src/vsip_vrealview_d.c', '../../c_VSIP_src/vsip_vrealview_f.c', '../../c_VSIP_src/vsip_vrecip_d.c', '../../c_VSIP_src/vsip_vrecip_f.c', '../../c_VSIP_src/vsip_vrect_d.c', '../../c_VSIP_src/vsip_vrect_f.c', '../../c_VSIP_src/vsip_mrect_d.c', '../../c_VSIP_src/vsip_mrect_f.c', '../../c_VSIP_src/vsip_vrsqrt_d.c', '../../c_VSIP_src/vsip_vrsqrt_f.c', '../../c_VSIP_src/vsip_vsam_d.c', '../../c_VSIP_src/vsip_vsam_f.c', '../../c_VSIP_src/vsip_vsbm_d.c', '../../c_VSIP_src/vsip_vsbm_f.c', '../../c_VSIP_src/vsip_vscatter_d.c', '../../c_VSIP_src/vsip_vscatter_f.c', '../../c_VSIP_src/vsip_vscatter_i.c', '../../c_VSIP_src/vsip_vscatter_si.c', '../../c_VSIP_src/vsip_vscatter_uc.c', '../../c_VSIP_src/vsip_vsdiv_d.c', '../../c_VSIP_src/vsip_vsdiv_f.c', '../../c_VSIP_src/vsip_vsin_d.c', '../../c_VSIP_src/vsip_vsin_f.c', '../../c_VSIP_src/vsip_vsinh_d.c', '../../c_VSIP_src/vsip_vsinh_f.c', '../../c_VSIP_src/vsip_vsma_d.c', '../../c_VSIP_src/vsip_vsma_f.c', '../../c_VSIP_src/vsip_vsmsa_d.c', '../../c_VSIP_src/vsip_vsmsa_f.c', '../../c_VSIP_src/vsip_vsortip_d.c', '../../c_VSIP_src/vsip_vsortip_f.c', '../../c_VSIP_src/vsip_vsortip_i.c', '../../c_VSIP_src/vsip_vsortip_vi.c', '../../c_VSIP_src/vsip_vsq_d.c', '../../c_VSIP_src/vsip_vsq_f.c', '../../c_VSIP_src/vsip_vsqrt_d.c', '../../c_VSIP_src/vsip_vsqrt_f.c', '../../c_VSIP_src/vsip_vsub_d.c', '../../c_VSIP_src/vsip_vsub_f.c', '../../c_VSIP_src/vsip_vsub_i.c', '../../c_VSIP_src/vsip_vsub_si.c', '../../c_VSIP_src/vsip_vsub_uc.c', '../../c_VSIP_src/vsip_vsubview_bl.c', '../../c_VSIP_src/vsip_vsubview_d.c', '../../c_VSIP_src/vsip_vsubview_f.c', '../../c_VSIP_src/vsip_vsubview_i.c', '../../c_VSIP_src/vsip_vsubview_mi.c', '../../c_VSIP_src/vsip_vsubview_si.c', '../../c_VSIP_src/vsip_vsubview_uc.c', '../../c_VSIP_src/vsip_vsubview_vi.c', '../../c_VSIP_src/vsip_vsumsqval_d.c', '../../c_VSIP_src/vsip_vsumsqval_f.c', '../../c_VSIP_src/vsip_vsumval_bl.c', '../../c_VSIP_src/vsip_vsumval_d.c', '../../c_VSIP_src/vsip_vsumval_f.c', '../../c_VSIP_src/vsip_vsumval_i.c', '../../c_VSIP_src/vsip_vsumval_si.c', '../../c_VSIP_src/vsip_vsumval_uc.c', '../../c_VSIP_src/vsip_vswap_d.c', '../../c_VSIP_src/vsip_vswap_f.c', '../../c_VSIP_src/vsip_vswap_i.c', '../../c_VSIP_src/vsip_vswap_si.c', '../../c_VSIP_src/vsip_vswap_uc.c', '../../c_VSIP_src/vsip_vtan_d.c', '../../c_VSIP_src/vsip_vtan_f.c', '../../c_VSIP_src/vsip_vtanh_d.c', '../../c_VSIP_src/vsip_vtanh_f.c', '../../c_VSIP_src/vsip_vxor_bl.c', '../../c_VSIP_src/vsip_vxor_i.c', '../../c_VSIP_src/vsip_vxor_si.c', '../../c_VSIP_src/vsip_vxor_uc.c', '../../c_VSIP_src/vsip_cvfreqswap_d.c', '../../c_VSIP_src/vsip_vfreqswap_d.c', '../../c_VSIP_src/vsip_cmfreqswap_d.c', '../../c_VSIP_src/vsip_mfreqswap_d.c', '../../c_VSIP_src/vsip_cvfreqswap_f.c', '../../c_VSIP_src/vsip_vfreqswap_f.c', '../../c_VSIP_src/vsip_cmfreqswap_f.c', '../../c_VSIP_src/vsip_mfreqswap_f.c', 'vsip_wrap.c'], include_dirs=['../../c_VSIP_src','./c_src'], ) setup (name = 'vsip', version = '0.6', author = "<NAME>", description = """Swig module of TVCPP""", ext_modules = [vsip_module], py_modules = ["vsip"], ) <file_sep>/* Created RJudd */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: matan2_d.h,v 2.0 2003/02/22 15:23:24 judd Exp $ */ #include"VU_mprintm_d.include" static void matan2_d(void){ printf("\n*******\nTEST matan2_d\n\n"); { vsip_scalar_d data_a[] = {0,1,2,3,4,5}; vsip_scalar_d data_b[] = {5,4,3,2,1,0}; vsip_scalar_d ans[] = {0, 0.2450, 0.5880, 0.9828, 1.3258, 1.5708}; vsip_block_d *block_a = vsip_blockbind_d(data_a,6,VSIP_MEM_NONE); vsip_block_d *block_b = vsip_blockbind_d(data_b,6,VSIP_MEM_NONE); vsip_block_d *ans_block = vsip_blockbind_d(ans,6,VSIP_MEM_NONE); vsip_mview_d *a = vsip_mbind_d(block_a,0,3,2,1,3); vsip_mview_d *b = vsip_mbind_d(block_b,0,3,2,1,3); vsip_mview_d *ansm = vsip_mbind_d(ans_block,0,3,2,1,3); vsip_mview_d *c = vsip_mcreate_d(2,3,VSIP_ROW,VSIP_MEM_NONE); vsip_mview_d *chk = vsip_mcreate_d(2,3,VSIP_ROW,VSIP_MEM_NONE); vsip_blockadmit_d(block_a,VSIP_TRUE); vsip_blockadmit_d(block_b,VSIP_TRUE); vsip_blockadmit_d(ans_block,VSIP_TRUE); printf("vsip_matan2_d(a,b,c)\n"); vsip_matan2_d(a,b,c); printf("matrix a\n");VU_mprintm_d("8.6",a); printf("matrix b\n");VU_mprintm_d("8.6",b); printf("matrix c\n");VU_mprintm_d("8.6",c); printf("right answer \n");VU_mprintm_d("8.4",ansm); vsip_msub_d(c,ansm,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); printf("inplace b,c\n"); vsip_matan2_d(a,b,b); vsip_msub_d(b,ansm,chk); vsip_mmag_d(chk,chk); vsip_mclip_d(chk,.0001,.0001,0,1,chk); if(vsip_msumval_d(chk) > .5) printf("error\n"); else printf("correct\n"); vsip_malldestroy_d(a); vsip_malldestroy_d(b); vsip_malldestroy_d(c); vsip_malldestroy_d(chk); vsip_malldestroy_d(ansm); } return; } <file_sep>#include"kw.h" void kw_zero(kw_obj *kw){ vsip_mfill_f(0.0,kw->m_gram); } void komega( kw_obj* kw, vsip_mview_f *m_data){ /* Data tapers for time and space */ vsip_vmmul_f(kw->ts_taper,m_data,VSIP_ROW,m_data); vsip_vmmul_f(kw->array_taper,m_data,VSIP_COL,m_data); /* FFT for time and space */ vsip_rcfftmop_f(kw->rcfftm,m_data,kw->cm_freq); vsip_ccfftmip_f(kw->ccfftm,kw->cm_freq); /* power estimate */ /* to save memory place estimate in real part of spectral matrix */ vsip_mcmagsq_f(kw->cm_freq,kw->rm_freq); /* scaling for average */ vsip_smmul_f(1.0/(float)kw->Navg,kw->rm_freq,kw->rm_freq); /* add in new values to gram estimate */ vsip_madd_f(kw->rm_freq,kw->m_gram,kw->m_gram); return; } /* initialize the komega object */ int kw_init(kw_obj* kw, param_obj* param){ int retval = 0; vsip_length Nsens = param->Nsens; vsip_length Nts = param->Nts; vsip_length Nfreq; if(param->Nts % 2){ printf("Data length must be even\n"); retval++; } kw->Nfreq = Nts/2 + 1; kw->Navg = param->Navg; Nfreq = kw->Nfreq; kw->cm_freq = vsip_cmcreate_f(Nsens,Nfreq,VSIP_COL,VSIP_MEM_NONE); if(kw->cm_freq){ kw->rm_freq=vsip_mrealview_f(kw->cm_freq); if(!kw->rm_freq) retval++; } else { retval++; kw->rm_freq = NULL; } kw->m_gram = vsip_mcreate_f(Nsens, Nfreq, VSIP_COL,VSIP_MEM_NONE); if(!kw->m_gram) retval++; kw->rcfftm = vsip_rcfftmop_create_f(Nsens,Nts,1,VSIP_ROW,0,0); if(!kw->rcfftm) retval++; kw->ccfftm = vsip_ccfftmip_create_f(Nsens,Nfreq,VSIP_FFT_FWD,1,VSIP_COL,0,0); if(!kw->ccfftm) retval++; kw->ts_taper = vsip_vcreate_hanning_f(Nts,0); if(!kw->ts_taper) retval++; kw->array_taper = vsip_vcreate_hanning_f(Nsens,0); if(!kw->array_taper) retval++; if(retval) printf("Error in kw initialization\n"); return retval; } /* finalize the komega object */ void kw_fin( kw_obj *kw){ vsip_malldestroy_f(kw->m_gram); vsip_fftm_destroy_f(kw->rcfftm); vsip_fftm_destroy_f(kw->ccfftm); vsip_valldestroy_f(kw->ts_taper); vsip_valldestroy_f(kw->array_taper); vsip_mdestroy_f(kw->rm_freq); vsip_cmalldestroy_f(kw->cm_freq); return; } vsip_mview_f *kw_instance(kw_obj* kw){ return kw->m_gram; }; <file_sep>/* Created by RJudd June 15, 2002 */ /* SPAWARSYSCEN Code 2857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_crfftop_d_fftw.h,v 2.1 2003/03/08 14:43:33 judd Exp $ */ /* Note that the spec requires x and z views to be unit stride */ #include"VI_fftw_obj.h" void vsip_crfftop_d( const vsip_fft_d *Offt, const vsip_cvview_d *z, const vsip_vview_d *x) { vsip_fft_d Nfft = *Offt; vsip_fft_d *fft = &Nfft; vsip_scalar_d scale = fft->scale; vsipl_fftw_obj *obj = (vsipl_fftw_obj*)fft->ext_fft_obj; vsip_length n = fft->N; vsip_cvview_d *w = fft->temp; vsip_stride wst = w->stride * w->block->R->rstride; vsip_scalar_d *wpr = (vsip_scalar_d *)((w->block->R->array) + wst * w->offset), *wpi = (vsip_scalar_d *)((w->block->I->array) + wst * w->offset); vsip_stride fst = z->block->R->rstride; vsip_stride bst = -fst; vsip_scalar_d *fpr = (vsip_scalar_d *)((z->block->R->array) + fst * z->offset), *bpr = (vsip_scalar_d *)((z->block->R->array) + fst * (z->offset + n)), *fpi = (vsip_scalar_d *)((z->block->I->array) + fst * z->offset), *bpi = (vsip_scalar_d *)((z->block->I->array) + fst * (z->offset + n)); vsip_stride xst = x->block->rstride; vsip_scalar_d *xptr = (vsip_scalar_d *)((x->block->array) + x->offset * xst); fftw_complex *in = obj->in; if(scale == 1){ (*in).re = (*fpr + *bpr); (*in).im = (*fpr - *bpr); while(n-- > 1){ in++; wpr += wst; wpi += wst; fpr += fst; fpi += fst; bpr += bst; bpi += bst; (*in).re = (*fpr + *bpr + *wpi * (*bpr - *fpr) - *wpr * (*fpi + *bpi)); (*in).im = (*fpi - *bpi - *wpi * (*fpi + *bpi) + *wpr * (*fpr - *bpr)); } } else { (*in).re = scale * (*fpr + *bpr); (*in).im = scale * (*fpr - *bpr); while(n-- > 1){ in++; wpr += wst; wpi += wst; fpr += fst; fpi += fst; bpr += bst; bpi += bst; (*in).re = scale * (*fpr + *bpr + *wpi * (*bpr - *fpr) - *wpr * (*fpi + *bpi)); (*in).im = scale * (*fpi - *bpi - *wpi * (*fpi + *bpi) + *wpr * (*fpr - *bpr)); } } #if defined(VSIP_ASSUME_COMPLEX_IS_INTERLEAVED) fftw_one(obj->p,obj->in,(fftw_complex*)xptr); #else { fftw_complex *out = obj->out; fftw_one(obj->p,obj->in,obj->out); n = fft->N; while(n-- > 0){ *xptr = (*out).re; xptr += xst; *xptr = (*out).im; xptr += xst; out++; } } #endif return; } <file_sep>/* Created RJudd September 19, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_vbind_d.c,v 2.0 2003/02/22 15:19:10 judd Exp $ */ #include"vsip.h" #include"vsip_vviewattributes_d.h" vsip_vview_d* (vsip_vbind_d)( const vsip_block_d* b, vsip_offset o, vsip_stride s, vsip_length n) { vsip_vview_d* v = (vsip_vview_d*)malloc(sizeof(vsip_vview_d)); if(v != (vsip_vview_d*)NULL){ v->block = (vsip_block_d*)b; v->offset = o; v->stride = s; v->length = n; v->markings = VSIP_VALID_STRUCTURE_OBJECT; } return v; } <file_sep>static void VI_cgivens_d( vsip_cscalar_d a, vsip_cscalar_d b, vsip_cscalar_d *c, vsip_cscalar_d *s, vsip_cscalar_d *r) { vsip_scalar_d am = vsip_cmag_d(a); vsip_scalar_d bm = vsip_cmag_d(b); c->i = 0.0; if(am == 0.0){ *r = b; c->r = 0.0; s->r = 1; s->i = 0.0; } else { vsip_scalar_d scale = am + bm; vsip_cscalar_d alpha = vsip_cmplx_d(a.r/am, a.i/am); vsip_scalar_d scalesq = scale * scale; vsip_scalar_d norm = scale * (vsip_scalar_d)sqrt((am*am)/scalesq + (bm * bm)/scalesq); c->r =am/norm; s->r = (alpha.r * b.r + alpha.i * b.i)/norm; s->i = (-alpha.r * b.i + alpha.i * b.r)/norm; r->r = alpha.r * norm; r->i = alpha.i * norm; } return; } static void VI_cgivens_r_d( vsip_cmview_d *A) { vsip_length m = A->col_length; vsip_length n = A->row_length; vsip_length i,j,k; vsip_cscalar_d c,s10,s01,r; vsip_stride r_st = A->row_stride * A->block->cstride; for(j=0; j<n; j++){ for(i=m-1; i>j; i--){ vsip_scalar_d *a0p_r = A->block->R->array + (A->offset + (i-1) * A->col_stride + j * A->row_stride) * A->block->cstride; vsip_scalar_d *a0p_i = A->block->I->array + (A->offset + (i-1) * A->col_stride + j * A->row_stride) * A->block->cstride; vsip_scalar_d *a1p_r = A->block->R->array + (A->offset + i * A->col_stride + j * A->row_stride) * A->block->cstride; vsip_scalar_d *a1p_i = A->block->I->array + (A->offset + i * A->col_stride + j * A->row_stride) * A->block->cstride; vsip_cscalar_d a,b; a.r = *a0p_r; a.i = *a0p_i; b.r = *a1p_r; b.i = *a1p_i; VI_cgivens_d(a,b,&c,&s01,&r); /* rotate r so the iamginary part is 0 */ *a0p_r = vsip_cmag_d(r); *a0p_i = 0; *a1p_r = 0.0; *a1p_i = 0.0; /* store a rotation vector in r */ r.r /= *a0p_r; r.i = - r.i / *a0p_r; a0p_r += r_st; a0p_i += r_st; a1p_r += r_st; a1p_i += r_st; s10.r = - s01.r; s10.i = s01.i; for(k=1; k<n-j; k++){ vsip_scalar_d a0_r = *a0p_r, a1_r = *a1p_r; vsip_scalar_d a0_i = *a0p_i, a1_i = *a1p_i; vsip_cscalar_d a0; a0.r = a0_r * c.r + a1_r * s01.r - a1_i * s01.i; a0.i = a0_i * c.r + s01.r * a1_i + a1_r * s01.i; /* correct a0 for rotation and place in matrix*/ *a0p_r = r.r * a0.r - r.i * a0.i; *a0p_i = r.r * a0.i + r.i * a0.r; *a1p_r = a1_r * c.r + s10.r * a0_r - s10.i * a0_i; *a1p_i = a1_i * c.r + s10.r * a0_i + s10.i * a0_r; a0p_r += r_st; a0p_i += r_st; a1p_r += r_st; a1p_i += r_st; } } } return; } <file_sep>/* Created RJudd August 30, 2002 */ /* SPAWARSYSCEN */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cchold_d.c,v 2.3 2004/09/22 02:25:38 judd Exp $ */ #include"vsip.h" #include"vsip_cmviewattributes_d.h" #include"vsip_cvviewattributes_d.h" #include"vsip_ccholdattributes_d.h" static int VI_ccholesky_low_ai_d( const vsip_cmview_d *A) { int retval = 0; vsip_index j,k; vsip_length n = A->col_length; double scale = 1; vsip_scalar_d re_scale = 1, im_scale = 1; vsip_scalar_d *scale_ptr; vsip_scalar_d *aptr_re; vsip_scalar_d *bptr_re; vsip_stride col_str = A->col_stride * 2; vsip_offset off_a_col = (A->offset + A->col_stride) * 2; vsip_stride A_diag_str = (A->col_stride + A->row_stride) * 2; vsip_offset off_A_diag = 2 * A->offset; vsip_length m0 = n; vsip_length m; vsip_offset off_b0 = off_A_diag; vsip_offset off_b; vsip_offset off_a0 = off_A_diag; vsip_offset off_a; vsip_offset off_as; for(k=0; k<n; k++){ vsip_scalar_d *a_kk_r = A->block->R->array + off_A_diag; off_A_diag += A_diag_str; /* for the diagonal a_kk must have zero imaginary */ if(*a_kk_r <= 0){ retval++; return retval; } else { scale = (double) *a_kk_r; scale = sqrt(scale); } re_scale = (vsip_scalar_d) scale; *a_kk_r = re_scale; *(a_kk_r + 1) = 0.0; aptr_re = A->block->R->array + off_a_col; off_a_col += A_diag_str; m0--; m = m0; while(m-- > 0){ *aptr_re /= re_scale; *(aptr_re + 1) /= re_scale; aptr_re += col_str; } off_b = off_b0; off_b0 += A_diag_str; off_as = off_a0; off_a = off_a0; off_a0 += A_diag_str; scale_ptr = A->block->R->array + off_as; for(j=k+1; j<n; j++){ off_b += col_str; bptr_re = A->block->R->array + off_b; off_as += col_str; scale_ptr += col_str; re_scale = - *scale_ptr; im_scale = *(scale_ptr + 1); off_a += A_diag_str; aptr_re = A->block->R->array + off_a; m = n - j; while(m-- >0){ vsip_scalar_d br = *bptr_re, bi = *(bptr_re + 1); *aptr_re += br * re_scale - bi * im_scale; *(aptr_re + 1) += br * im_scale + bi * re_scale; aptr_re += col_str; bptr_re += col_str; } } } return retval; } static int VI_ccholesky_low_d( const vsip_cmview_d *A) { int retval = 0; vsip_index j,k; vsip_length n = A->col_length; double scale = 1; vsip_scalar_d re_scale = 1, im_scale = 1; vsip_scalar_d *aptr_re, *aptr_im; vsip_scalar_d *bptr_re, *bptr_im; vsip_stride col_str = A->col_stride * A->block->cstride; vsip_offset off_a_col = (A->offset + A->col_stride) * A->block->cstride; vsip_stride A_diag_str = (A->col_stride + A->row_stride) * A->block->cstride; vsip_offset off_A_diag = A->block->cstride * A->offset; vsip_length m0 = n; vsip_length m; vsip_offset off_b0 = off_A_diag; vsip_offset off_b; vsip_offset off_a0 = off_A_diag; vsip_offset off_a; vsip_offset off_as; for(k=0; k<n; k++){ vsip_scalar_d *a_kk_r = A->block->R->array + off_A_diag; vsip_scalar_d *a_kk_i = A->block->I->array + off_A_diag; off_A_diag += A_diag_str; /* for the diagonal a_kk must have zero imainary */ *a_kk_i = 0.0; if(*a_kk_r <= 0){ retval++; return retval; } else { scale = (double) *a_kk_r; scale = sqrt(scale); } re_scale = (vsip_scalar_d) scale; *a_kk_r = re_scale; aptr_re = A->block->R->array + off_a_col; aptr_im = A->block->I->array + off_a_col; off_a_col += A_diag_str; m0--; m = m0; while(m-- > 0){ *aptr_re /= re_scale; *aptr_im /= re_scale; aptr_re += col_str; aptr_im += col_str; } off_b = off_b0; off_b0 += A_diag_str; off_as = off_a0; off_a = off_a0; for(j=k+1; j<n; j++){ off_b += col_str; bptr_re = A->block->R->array + off_b; bptr_im = A->block->I->array + off_b; off_as += col_str; re_scale = - *(A->block->R->array + off_as); im_scale = *(A->block->I->array + off_as); off_a += A_diag_str; aptr_re = A->block->R->array + off_a; aptr_im = A->block->I->array + off_a; m = n - j; while(m-- >0){ *aptr_re += *bptr_re * re_scale - *bptr_im * im_scale; *aptr_im += *bptr_re * im_scale + *bptr_im * re_scale; aptr_re += col_str; bptr_re += col_str; aptr_im += col_str; bptr_im += col_str; } } } return retval; } static int VI_ccholesky_upp_ai_d( const vsip_cmview_d *A) { int retval = 0; vsip_length n = A->row_length; vsip_length m0 = n - 1; vsip_length m = m0; vsip_length m_in =0; vsip_index j,k; double scale; vsip_offset a_kk_off = 2 * A->offset; vsip_scalar_d *a_kk_r = A->block->R->array + a_kk_off; vsip_stride A_diag_str = 2 * (A->row_stride + A->col_stride); vsip_scalar_d re_scale, im_scale; vsip_scalar_d *a_re_ptr, *a_re_ptr0; vsip_scalar_d *b_re_ptr, *b_re_ptr0; vsip_stride a_str = 2 * A->row_stride; vsip_stride b_str = a_str; for(k=0; k<n; k++){ /* for the diagonal a_kk must have zero imaginary */ if(*a_kk_r <= 0){ retval++; return retval; } else { scale = (double) *a_kk_r; scale = sqrt(scale); } *a_kk_r = (vsip_scalar_d) scale; *(a_kk_r + 1) = 0.0; a_re_ptr = a_kk_r + a_str; while(m-- > 0){ *a_re_ptr /= (vsip_scalar_d)scale; *(a_re_ptr + 1) /= (vsip_scalar_d)scale; a_re_ptr += a_str; } m0--; m=m0; a_re_ptr0 = a_kk_r + A_diag_str; b_re_ptr0 = a_kk_r + b_str; for(j=k+1; j<n; j++){ m_in = n-j; a_re_ptr = a_re_ptr0; b_re_ptr = b_re_ptr0; re_scale = - *(b_re_ptr); im_scale = *(b_re_ptr + 1); while(m_in-- >0){ vsip_scalar_d br = *b_re_ptr, bi = *(b_re_ptr + 1); *a_re_ptr += br * re_scale - bi * im_scale; *(a_re_ptr + 1) += br * im_scale + bi * re_scale; a_re_ptr += a_str; b_re_ptr += b_str; } a_re_ptr0 += A_diag_str; b_re_ptr0 += b_str; } a_kk_r += A_diag_str; } return retval; } static int VI_ccholesky_upp_d( const vsip_cmview_d *A) { int retval = 0; vsip_length n = A->row_length; vsip_length m0 = n - 1; vsip_length m = m0; vsip_length m_in =0; vsip_index j,k; double scale; vsip_offset a_kk_off = A->block->cstride * A->offset; vsip_scalar_d *a_kk_r = A->block->R->array + a_kk_off; vsip_scalar_d *a_kk_i = A->block->I->array + a_kk_off; vsip_stride A_diag_str = A->block->cstride * (A->row_stride + A->col_stride); vsip_scalar_d re_scale, im_scale; vsip_scalar_d *a_re_ptr, *a_re_ptr0; vsip_scalar_d *a_im_ptr, *a_im_ptr0; vsip_scalar_d *b_re_ptr, *b_re_ptr0; vsip_scalar_d *b_im_ptr, *b_im_ptr0; vsip_stride a_str = A->block->cstride * A->row_stride; vsip_stride b_str = a_str; for(k=0; k<n; k++){ /* for the diagonal a_kk must have zero imaginary */ if(*a_kk_r <= 0){ retval++; return retval; } else { scale = (double) *a_kk_r; scale = sqrt(scale); } *a_kk_r = (vsip_scalar_d) scale; *a_kk_i = 0.0; a_re_ptr = a_kk_r + a_str; a_im_ptr = a_kk_i + a_str; while(m-- > 0){ *a_re_ptr /= (vsip_scalar_d)scale; *a_im_ptr /= (vsip_scalar_d)scale; a_re_ptr += a_str; a_im_ptr += a_str; } m0--; m=m0; a_re_ptr0 = a_kk_r + A_diag_str; a_im_ptr0 = a_kk_i + A_diag_str; b_re_ptr0 = a_kk_r + b_str; b_im_ptr0 = a_kk_i + b_str; for(j=k+1; j<n; j++){ m_in = n-j; a_re_ptr = a_re_ptr0; a_im_ptr = a_im_ptr0; b_re_ptr = b_re_ptr0; b_im_ptr = b_im_ptr0; re_scale = - *(b_re_ptr); im_scale = *(b_im_ptr); while(m_in-- >0){ *a_re_ptr += *b_re_ptr * re_scale - *b_im_ptr * im_scale; *a_im_ptr += *b_re_ptr * im_scale + *b_im_ptr * re_scale; a_re_ptr += a_str; b_re_ptr += b_str; a_im_ptr += a_str; b_im_ptr += b_str; } a_re_ptr0 += A_diag_str; a_im_ptr0 += A_diag_str; b_re_ptr0 += b_str; b_im_ptr0 += b_str; } a_kk_r += A_diag_str; a_kk_i += A_diag_str; } return retval; } int vsip_cchold_d( vsip_cchol_d* chol, const vsip_cmview_d *A) { int retval = 0; chol->matrix = A; if(chol->uplo == VSIP_TR_LOW){ if(A->block->cstride == 2) retval = VI_ccholesky_low_ai_d(A); else retval = VI_ccholesky_low_d(A); } else { /* must be vsip_tr_upp */ if(A->block->cstride == 2) retval = VI_ccholesky_upp_ai_d(A); else retval = VI_ccholesky_upp_d(A); } return retval; } <file_sep>/* Created RJudd Sep 26, 2013 */ /* created using vsip_vcopy_vi_d.c as template*/ /* // Copyright (c) 2013 Independent Consultant. All rights reserved. */ /********************************************************************* // This code includes no warranty, express or implied, including / // the warranties of merchantability and fitness for a particular / // purpose. / // No person or entity assumes any legal liability or responsibility / // for the accuracy, completeness, or usefulness of any information, / // apparatus, product, or process disclosed, or represents that / // its use would not infringe privately owned rights. / *********************************************************************/ /********************************************************************* // The MIT License (see copyright for jvsip in top level directory) // http://opensource.org/licenses/MIT **********************************************************************/ #include"vsip.h" #include"vsip_vviewattributes_f.h" #include"vsip_vviewattributes_vi.h" void (vsip_vcopy_vi_f)( const vsip_vview_vi* a, const vsip_vview_f* r) { { vsip_length n = r->length; vsip_stride ast = a->stride, rst = r->stride * r->block->rstride; vsip_scalar_vi *ap = (a->block->array) + a->offset; vsip_scalar_f *rp = (r->block->array) + r->offset * r->block->rstride; /*end define*/ while(n-- > 0){ *rp = (vsip_scalar_f) *ap; ap += ast; rp += rst; } } } <file_sep>/* Created RJudd October 6, 2000 */ /* SPAWARSYSCEN D857 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: VI_mrealview_f.h,v 2.1 2003/03/09 22:41:18 judd Exp $ */ #ifndef _VI_MREALVIEW_F_H #define _VI_MREALVIEW_F_H #include"vsip_cmviewattributes_f.h" #include"vsip_mviewattributes_f.h" static vsip_mview_f* VI_mrealview_f( const vsip_cmview_f* X, vsip_mview_f* Y) { Y->block = X->block->R; Y->offset = X->offset; Y->row_length = X->row_length; Y->col_length = X->col_length; Y->row_stride = X->row_stride; Y->col_stride = X->col_stride; Y->markings = VSIP_VALID_STRUCTURE_OBJECT; return Y; } #endif /* _VI_MREALVIEW_F_H */
345b45dac0b414b1f568ab4cd5458c7afe979545
[ "Swift", "Markdown", "Makefile", "Python", "C", "C++", "Shell" ]
612
C
rrjudd/jvsip
f9ea05e0082acfeb3707b02e91a45f40008b7340
256b41924b78305c779b8356f2fb83a2f47b64ff
refs/heads/master
<repo_name>mmrysir/laravel-sanctum-api<file_sep>/app/Http/Controllers/AuthController.php <?php namespace App\Http\Controllers; use App\Models\User; use http\Message; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Http\Response; class AuthController extends Controller { /* |-------------------------------------------------------------------------- | Register Controller |-------------------------------------------------------------------------- | | This controller handles the registration of new users as well as their | validation and creation. By default this controller uses a trait to | provide this functionality without requiring any additional code. | */ public function register(Request $request) { $fields = $request->validate([ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'string', 'email', 'max:255', 'unique:users'], 'password' => ['required', 'string', '<PASSWORD>', '<PASSWORD>'], ]); $user = User::create([ 'name' => $fields['name'], 'email' => $fields['email'], 'password' => <PASSWORD>($fields['password']), ]); $token = $user->createToken('myapptoken')->plainTextToken; $response =[ 'user'=>$user, 'token'=>$token ]; return $response($response, 201); } }
7e22040cbf41818e32cf932d06b0f654ff32c2f6
[ "PHP" ]
1
PHP
mmrysir/laravel-sanctum-api
f5da4c99813aed5122c31be69c899cb425bef715
fdcc460d4310f42e0a7bb2ee8fa78269f699009e
refs/heads/master
<repo_name>chengs94/BioPET-shiny-server<file_sep>/.#BioPET.R jeremy@jeremy-ThinkPad-x230.2626:1466610776<file_sep>/README.md <<<<<<< HEAD # shiny-server ======= # BioPET >>>>>>> 8fe13665b668220ce6a93b8b9c552395dbf93b9a
7a876db08480c2335dc17fcee0c2340bcfd66b65
[ "Markdown", "R" ]
2
R
chengs94/BioPET-shiny-server
28f8bd607a597b1fac99865ff6c161a255809047
91e9a282cc40e176422183014a3bb7824335e302
refs/heads/master
<repo_name>dsingh87/snippets-app<file_sep>/snippets.py import sys import argparse import logging import csv # Set the log output file, and the log level logging.basicConfig(filename="output.log", level=logging.DEBUG) def put(name, snippet, filename): """ Store a snippet with an associated name in the CSV file """ logging.info("Writing {}:{} to {}".format(name, snippet, filename)) logging.debug("Opening file") with open(filename, "a") as f: writer = csv.writer(f) logging.debug("Writing snippet to file".format(name, snippet)) writer.writerow([name, snippet]) logging.debug("Write successful") return name, snippet def get(name, filename): """ Get a snippet with an associated name from the CSV file """ with open(filename, 'rb') as f: reader = csv.reader(f) for row in reader: if row[0] == name: snippet = row[1] else: snippet = "Name is not stored in file" return snippet def make_parser(): """ Construct the command line parser """ logging.info("Constructing parser") description = "Store and retrieve snippets of text" parser = argparse.ArgumentParser(description=description) subparsers = parser.add_subparsers(dest = "command",help="Available commands") # Subparser for the put command logging.debug("Constructing put subparser") put_parser = subparsers.add_parser("put", help = "Store a snippet") put_parser.add_argument("name", help = "The name of the snippet") put_parser.add_argument("snippet", help = "The snippet text") put_parser.add_argument("filename", default="snippets.csv", nargs="?", help="The snippet filename") # Subparser for the get command logging.debug("Constructing get subparser") get_parser = subparsers.add_parser("get", help="Get a snippet") get_parser.add_argument("name", help = "The name of the snippet") get_parser.add_argument("filename", default="snippets.csv", nargs="?", help = "The snippet filename") return parser def main(): """ Main function """ logging.info("Starting snippets") parser = make_parser() arguments = parser.parse_args(sys.argv[1:]) # Convert parsed agruments from Namespace to dictionary arguments = vars(arguments) command = arguments.pop("command") if command == "put": name, snippet = put(**arguments) print "Stored '{}' as '{}'".format(snippet, name) if command == "get": snippet = get(**arguments) print snippet if __name__ == "__main__": main()
11074adf570f7f88e1f7bfb949f5debc0aa0dceb
[ "Python" ]
1
Python
dsingh87/snippets-app
84574b37af7fd02a125d02c49b7fba8d3b5db216
0585604cbbfcbf199b4836e7a14fa2fc48bbdbfe
refs/heads/master
<repo_name>xieyiyu/AutoTestAppium<file_sep>/utils/adb_util.py import subprocess from utils.logging_util import log ''' adb 命令 ''' class AdbUtil(object): def __init__(self, device_id=""): if device_id == "": self.device_id = "" else: self.device_id = "-s %s" % device_id def adb(self, args): """ adb命令 :param args: :return: 执行结果 """ cmd = "adb %s %s" % (self.device_id, str(args)) # 单个设备可不传入device_id return subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def get_device_state(self): """ 获取设备当前状态: device | offline | 其它 :return: state 设备状态 """ return self.adb("get-state").stdout.read().strip().decode() def get_device_id(self): """ 获取设备id :return: serialNo 设备id """ return self.adb("get-serialno").stdout.read().strip().decode() def get_device_list(self): """ 获取连接的所有在线设备 :return: devices_list 设备id列表 """ devices_list = list() for b in self.adb("devices").stdout.readlines(): device = bytes.decode(b) if 'device' in device and 'devices' not in device: device = device.split('\t')[0] devices_list.append(device) return devices_list def get_android_version(self): """ 获取设备的Android版本号 :return: android_version 安卓版本号 """ return self.adb("shell getprop ro.build.version.release").stdout.read().strip().decode() def get_device_model(self): """ 获取设备型号 :return: device_model 设备型号 """ return self.adb("shell getprop ro.product.model").stdout.read().strip().decode() def get_device_brand(self): """ 获取设备品牌 :return: device_brand 设备品牌 """ return self.adb("shell getprop ro.product.brand").stdout.read().strip().decode() def get_device_name(self): """ 获取设备名称 :return: device_name 设备名称 """ return self.adb("shell getprop ro.product.device").stdout.read().strip().decode() def install_app(self, apk_path): """ 安装app :param apk_path: apk路径 :return: """ return self.adb("install -r %s" % apk_path) def is_app_installed(self, appPackage): """ 判断应用是否安装 :param appPackage: 包名 :return: 已安装返回true,否则返回false """ app_list = self.adb("shell pm list packages %s" % appPackage).stdout.read().strip().decode() if appPackage in app_list: return True else: return False def remove_app(self, appPackage): """ 卸载应用 :param appPackage: 包名 :return: """ return self.adb("uninstall %s" % appPackage) if __name__ == '__main__': if AdbUtil().is_app_installed("com.cma.launcher.lite"): AdbUtil().remove_app("com.cma.launcher.lite") <file_sep>/pageobejct/base_operate.py from utils.logging_util import log from time import sleep import selenium.common.exceptions from selenium.webdriver.support.ui import WebDriverWait from pageobejct.base_element import BaseElement """ 所有元素操作方法 """ class BaseOperate: def __init__(self, driver=""): self.driver = driver def find_element(self, case_operate): """ 重写元素定位方法 :param case_operate: 用例操作 :return: """ try: if type(case_operate) == list: # 多个元素 for item in case_operate: WebDriverWait(self.driver, BaseElement.WAIT_TIME).until(lambda x: self.find_element_by(item)) return True if type(case_operate) == dict: # 单个元素 WebDriverWait(self.driver, BaseElement.WAIT_TIME).until(lambda x: self.find_element_by(case_operate)) return True except selenium.common.exceptions.TimeoutException: return False except selenium.common.exceptions.NoSuchElementException: return False def operate(self, case_operate, test_info): """ 封装元素操作方法 :param case_operate: 用例操作 :param test_info: 测试套件信息 :return: """ log.info('----------------base_operate---------------') log.info('test_info: %s' % test_info) elements = { BaseElement.CLICK: lambda: self.click(case_operate), BaseElement.SET_VALUE: lambda: self.set_value(case_operate), BaseElement.SWIPE_LEFT: lambda: self.swipe_left(case_operate), BaseElement.SWIPE_RIGHT: lambda: self.swipe_right(case_operate), BaseElement.SWIPE_UP: lambda: self.swipe_up(case_operate), BaseElement.SWIPE_DOWN: lambda: self.swipe_down(case_operate), BaseElement.KEY_EVENT: lambda: self.key_event(case_operate), BaseElement.ZOOM: lambda: self.zoom_element(case_operate), BaseElement.PINCH: lambda: self.pinch_element(case_operate) } if case_operate.__contains__('element_info'): # 没有element_info这个键,不查找元素,直接执行 if self.find_element(case_operate): elements[case_operate['operate_type']]() return True return False else: elements[case_operate['operate_type']]() return True def find_element_by(self, case_operate): """ 封装常用元素定位方法 """ elements = { BaseElement.find_element_by_id: lambda: self.driver.find_element_by_id(case_operate['element_info']), BaseElement.find_element_by_name: lambda: self.driver.find_element_by_name(case_operate['element_info']), BaseElement.find_element_by_class_name: lambda: self.driver.find_element_by_class_name(case_operate['element_info']), BaseElement.find_element_by_xpath: lambda: self.driver.find_element_by_xpath(case_operate['element_info']) } return elements[case_operate['find_type']]() def click(self, case_operate): """ 元素点击事件 """ self.find_element_by(case_operate).click() # 此处应添加判断testcase['find_type']是否是BaseElement类中定义的类型之一 log.info("click %s" % case_operate) def set_value(self, case_operate): """ 设置值 """ self.find_element_by(case_operate).set_value(case_operate["text"]) log.info("set %s" % case_operate["text"]) def get_window_size(self): """ 获取屏幕分辨率 :return: width*height """ width = self.driver.get_window_size()['width'] height = self.driver.get_window_size()['height'] return width,height def swipe_to(self, x1, y1, x2, y2, times, swipe_time): """ 滑动屏幕 :param x1: 起点横坐标 :param y1: 起点纵坐标 :param x2: 重点横坐标 :param y2: 终点纵坐标 :param times: 滑动次数 :param swipe_time: 滑动时间 :return: """ width, height = self.get_window_size() for i in range(times): self.driver.swipe(width * x1, height * y1, width * x2, height * y2, swipe_time) sleep(1) def swipe_left(self, case_operate): """ 左滑 """ self.swipe_to(0.8, 0.5, 0.2, 0.5, case_operate['times'], case_operate['swipe_time']) def swipe_right(self, case_operate): """ 右滑 """ self.swipe_to(0.2, 0.5, 0.8, 0.5, case_operate['times'], case_operate['swipe_time']) def swipe_up(self, case_operate): """ 上滑 """ self.swipe_to(0.5, 0.8, 0.5, 0.2, case_operate['times'], case_operate['swipe_time']) def swipe_down(self, case_operate): """ 下滑 """ self.swipe_to(0.5, 0.2, 0.5, 0.8, case_operate['times'], case_operate['swipe_time']) def key_event(self, case_operate): """ 操作实体按键 按键码参考链接http://blog.csdn.net/qq_22795513/article/details/53169593 :return: """ log.info("key_event: " % case_operate) self.driver.keyevent(case_operate['key_code']) def zoom_element(self, case_operate): """ 在元素上执行放大操作 未能成功操作,待实现!!!!!!! :return: """ el = self.find_element_by(case_operate) self.driver.zoom(element=el) def pinch_element(self, case_operate): """ 在元素上执行模拟双指捏(缩小操作) 未能成功操作,待实现!!!!!!! :return: """ el = self.find_element_by(case_operate) self.driver.pinch(element=el) <file_sep>/utils/logging_util.py import logging.config import os from utils.yaml_util import get_yaml PATH = lambda p: os.path.abspath( os.path.join(os.path.dirname(__file__), p) ) logging_file = get_yaml(PATH("../yamls/config/log_config.yaml")) info_log = logging_file['handlers']['info_file_handler']['filename'] error_log = logging_file['handlers']['error_file_handler']['filename'] logging_file['handlers']['info_file_handler']['filename'] = PATH("../log/%s" %info_log) logging_file['handlers']['error_file_handler']['filename'] = PATH("../log/%s" %error_log) logging.config.dictConfig(logging_file) log = logging.getLogger("fileLogger") <file_sep>/testcase/folder_test.py import os from base.base_parametrize import ParametrizedTestCase from base.base_case_operate import * PATH = lambda p: os.path.abspath( os.path.join(os.path.dirname(__file__), p) ) class FolderTest(ParametrizedTestCase): def test_01_folder_rename(self): self.folder.operate(test_case_name='folder_rename') def test_02_folder_create(self): self.folder.operate(test_case_name='folder_create') def setUp(self): super(FolderTest, self).setUp() self.folder = BaseCase(driver=self.driver, path=PATH("../yamls/testyaml/folder.yaml"))<file_sep>/pageobejct/base_element.py """ 所有页面元素,用例操作按照此为标准 """ class BaseElement(object): # 元素定位方法 find_element_by_id = "id" find_element_by_name = "name" find_element_by_class_name = "class_name" find_element_by_xpath = "xpath" # 元素定位等待时间 WAIT_TIME = 5 # 操作 CLICK = "click" # 设置值 SET_VALUE = "set_value" # 左滑 SWIPE_LEFT = "swipe_left" # 右滑 SWIPE_RIGHT = "swipe_right" # 上滑 SWIPE_UP = "swipe_up" # 下滑 SWIPE_DOWN = "swipe_down" # 实体按键操作,用例中仍要写element_info、find_type KEY_EVENT = "key_event" # 在元素上执行放大操作 ZOOM = "zoom" # 在元素上执行模拟双指捏(缩小操作) PINCH = "pinch" TAP = "tap"<file_sep>/runner.py import time from datetime import datetime import unittest from multiprocessing import Pool from utils import HTMLTestRunner from utils.adb_util import * from base.base_appium import * from base.base_init import init_devices from base.base_parametrize import ParametrizedTestCase from testcase.first_open_test import FirstOpenTest from testcase.folder_test import FolderTest from utils.logging_util import log def runner_pool(devices_pool): """ 创建进程池,实现多设备执行用例 :param devices_pool: 设备信息 :return: """ log.info("---------------runner_pool---------------") log.info(devices_pool) pool = Pool(len(devices_pool)) # 创建进程池,批量创建子进程,设置最大进程数量 pool.map(runner_case_app, devices_pool) pool.close() # 等待进程池中的worker进程执行结束再关闭pool pool.join() # 等待进程池中的worker进程执行完毕,防止主进程在worker进程结束前结束,必须在close()或terminate()之后 def runner_case_app(devices_app): """ 执行case,并输出测试报告 :param devices_app: 设备信息 :return: """ log.info("---------------runner_case_app---------------") # start_time = datetime.now() testuite = unittest.TestSuite() testuite.addTest(ParametrizedTestCase.parametrize(FirstOpenTest, param=devices_app)) testuite.addTest(ParametrizedTestCase.parametrize(FolderTest, param=devices_app)) timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) fp = open(PATH("../report/" + timestr + "_report.html"), "wb") runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title=u'Clauncher自动化测试报告', description=u'用例执行详情') runner.STYLESHEET_TMPL = '<link rel="stylesheet" href="../utils/my_stylesheet.css" type="text/css">' runner.run(testuite) fp.close() if __name__ == '__main__': if AdbUtil().get_device_list(): get_devices = init_devices() appPackage = get_devices[0]['appPackage'] # 判断app是否安装,若已安装则卸载(仅单设备) if AdbUtil().is_app_installed(appPackage): AdbUtil().remove_app(appPackage) # 启动appium服务 appium_server = BaseAppium(get_devices) appium_server.start_server() while not appium_server.is_running(): time.sleep(5) # 执行用例 runner_pool(get_devices) appium_server.stop_server() else: log.error(u"设备不存在") <file_sep>/base/base_appium.py import os import threading from multiprocessing import Process import urllib.request from urllib.error import URLError from utils.logging_util import log """ 启动、关闭、重启Appium服务 """ PATH = lambda p: os.path.abspath( os.path.join(os.path.dirname(__file__), p) ) class BaseAppium: def __init__(self, devices): self.devices = devices def start_server(self): """ 启动appium服务 :return: """ for i in range(0, len(self.devices)): log.info("---------------appium_start_server---------------") log.info(self.devices) device_config = self.devices[i] log.info(device_config) appium_cmd = "appium -a 127.0.0.1 -p " + str(device_config['port']) \ + " -bp " + str(device_config['bsport']) \ + " -U " + str(device_config['udid']) \ + " --session-override" \ + " --no-reset" log.info(appium_cmd) run_server = RunServer(appium_cmd) p = Process(target=run_server.start()) p.start() @staticmethod def stop_server(): """ 关闭appium服务 :return: """ os.system('taskkill /f /im node.exe') log.info("---------------appium_stop_server---------------") def restart_server(self): """ 重启appium服务 :return: """ self.stop_server() self.start_server() log.info("---------------appium_restart_server---------------") def is_running(self): """ 判断appium服务是否开启 :return: """ response = None for i in range(0, len(self.devices)): url = "http://127.0.0.1:" + str(self.devices[i]['port']) + "/wd/hub" + "/status" log.info("waiting to connect: %s" % url) try: response = urllib.request.urlopen(url, timeout=5) print(response) log.info("---------------appium_is_running_server---------------") log.info("response: %s " % response) if str(response.getcode()).startswith("2"): return True else: return False except URLError: return False finally: if response: response.close() class RunServer(threading.Thread): def __init__(self, cmd): threading.Thread.__init__(self) self.cmd = cmd def run(self): os.system(self.cmd) if __name__ == '__main__': pass<file_sep>/base/base_case_operate.py from utils.logging_util import log from pageobejct.base_operate import BaseOperate from utils.yaml_util import get_yaml class BaseCase: def __init__(self, **kwargs): # **kwargs表示关键字参数,是一个dict self.driver = kwargs['driver'] self.path = kwargs['path'] self.operate_element = BaseOperate(self.driver) self.is_operate = True self.test_info = get_yaml(self.path)['testinfo'] self.test_case = get_yaml(self.path)['testcase'] def operate(self, test_case_name): """ 操作步骤 :param test_case_name: 用例名称 对应yaml中 :return: """ case = self.test_case[test_case_name] for item in case: result = self.operate_element.operate(item,self.test_info) if not result: log.error("operate %s failed" % item) self.is_operate = False break def check_point(self): """ 检查点 :return: """ result = False if not self.is_operate: log.error("operate failed,can't find check_point") else: check = get_yaml(self.path)['check'] result = self.operate_element.find_element(check) return result <file_sep>/utils/yaml_util.py import yaml def get_yaml(path): """ 获取yaml文件 :param path: yaml文件路径 :return: """ try: with open(path, encoding='utf-8') as f: return yaml.load(f) except FileNotFoundError: print(u"can't find yaml file:s% " %path)<file_sep>/testcase/first_open_test.py import os from base.base_parametrize import ParametrizedTestCase from base.base_case_operate import * PATH = lambda p: os.path.abspath( os.path.join(os.path.dirname(__file__), p) ) class FirstOpenTest(ParametrizedTestCase): def test_01_first_open(self): # 方法命名要以test_开头 self.first_open.operate(test_case_name='first_open') self.first_open.check_point() # def test_02(self): # self.first_open.operate(test_case_name='zoom_test') def setUp(self): super(FirstOpenTest, self).setUp() self.first_open = BaseCase(driver=self.driver, path=PATH("../yamls/testyaml/first_open.yaml"))<file_sep>/base/base_parametrize.py import unittest from appium import webdriver from utils.logging_util import log ''' 参数化测试用例 ''' class ParametrizedTestCase(unittest.TestCase): """ TestCase classes that want to be parametrized should inherit from this class. """ devices = dict() def __init__(self, methodName='runTest', param=None): super(ParametrizedTestCase, self).__init__(methodName) global devices devices = param @classmethod def setUpClass(cls): global devices desired_caps = dict() desired_caps['platformName'] = devices['platformName'] desired_caps['platformVersion'] = devices['platformVersion'] desired_caps['deviceName'] = devices['deviceName'] # 暂未添加获取deviceName方法,用udid替代 desired_caps['udid'] = devices['udid'] desired_caps['app'] = devices['app'] desired_caps['appPackage'] = devices['appPackage'] desired_caps['appActivity'] = devices['appActivity'] desired_caps['noReset'] = "true" desired_caps['fullReset'] = "false" remote = "http://127.0.0.1:" + str(devices['port']) + "/wd/hub" cls.driver = webdriver.Remote(remote, desired_caps) @staticmethod def parametrize(testcase_klass, param=None): log.info('testcase_klass: %s' % testcase_klass) testloader = unittest.TestLoader() testnames = testloader.getTestCaseNames(testcase_klass) suite = unittest.TestSuite() for name in testnames: suite.addTest(testcase_klass(name, param=param)) return suite<file_sep>/base/base_init.py from utils.apk_util import * from utils.adb_util import * from utils.yaml_util import get_yaml # 获取文件绝对路径, 待改进:写在公共方法中 # os.path.abspath返回绝对路径,os.path.dirname返回文件路径,os.path.join(path1[,path2])将目录和文件名合成一个路径 PATH = lambda p: os.path.abspath( os.path.join(os.path.dirname(__file__), p) ) def init_devices(): """ 初始化设备信息,添加指定apk路径,包名,主activity :return: device_config 设备信息 """ device_config = get_yaml(PATH("../yamls/config/config.yaml"))['devices'] apk_path = get_yaml(PATH("../yamls/config/config.yaml"))['apk'] print(apk_path) apk_info = ApkUtil(apk_path).get_apk_info() get_devices = AdbUtil().get_device_list() i = 0 for item in device_config: item['platformVersion'] = AdbUtil(get_devices[i]).get_android_version() item['deviceName'] = get_devices[i] item['udid'] = get_devices[i] item['app'] = apk_path item['appPackage'] = apk_info['appPackage'] item['appActivity'] = apk_info['appActivity'] i = i+ 1 return device_config if __name__ == '__main__': print(init_devices())<file_sep>/doc/test_case_writing.md ## 测试用例编写规范 * 熟悉yaml格式编写规范. [yaml语法学习地址](http://www.ruanyifeng.com/blog/2016/07/yaml.html) * 用例编写 /yamls/testyaml/*.yaml * 用例操作 /testcase/*_test.py ,与用例文件名称对应 文件中的每个测试用例方法以test_开头,名称与yaml中一致 ## 测试用例字段解释 #### 1. 查找元素 | find_type | 解释 | 对应元素 | element_info | -------------- | ------------------ | ----------------------- | ------------ | id | 根据id查找元素 | resource-id | com.cma.launcher.lite:id/preview_background | name | 根据name查找元素 | text | I'm Lucky | class_name | 根据class查找元素 | class | android.widget.ImageView | xpath | 根据xpath查找元素 | //class[@index='index'] | //android.widget.TextView[@index='2'] * 示例 ``` element_info: com.cma.launcher.lite:id/add_btn find_type: id ``` #### 2. 用例操作 | operate_type | 解释 | 配合字段 | element_info是否必须 | -------------- | ----------- | ----------------------- | ------------ | click | 点击 | resource-id | 是 | set_value | 设置值 | text 输入值 | 是 | swipe_left,swipe_right,swipe_up,swipe_down | 左滑,右滑,上滑,下滑 | times 滑动次数,swipe_time 滑动时间 | 是 | key_event | 实体按键 | key_code 按键码 | 否 * 常用[按键码](http://blog.csdn.net/qq_22795513/article/details/53169593) ``` KEYCODE_BACK 返回键 4 KEYCODE_HOME 按键Home 3 KEYCODE_MENU 菜单键 82 KEYCODE_POWER 电源键 26 KEYCODE_ENTER 回车键 66 ``` * 示例 ``` - element_info: com.cma.launcher.lite:id/preview_background find_type: id operate_type: click - operate_type: key_event key_code: 4 - element_info: com.cma.launcher.lite:id/search_button_container find_type: id operate_type: swipe_right times: 2 swipe_time: 600 ``` <file_sep>/utils/apk_util.py import re import subprocess import os import math from utils.logging_util import log ''' 获取apk信息 ''' class ApkUtil: def __init__(self, apk_path): self.apk_path = apk_path def aapt(self, args): """ aapt命令 :param args: :return: """ cmd = "aapt %s" % (str(args)) return subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def get_apk_info(self): """ 获取app包名,versionCode,versionName,应用名称 :return: apk_info """ args = "dump badging %s" % self.apk_path result = self.aapt(args).stdout.read().strip().decode() match_package = re.compile("package: name='(\S+)' versionCode='(\d+)' versionName='(\S+)'").match(result) if not match_package: raise Exception("can't get app_package_info") match_activity = re.compile("launchable-activity: name='(\S+)'").search(result) # 获取app主activity if not match_activity: raise Exception("can't get app_activity_info") match_name = re.compile("application-label:(\S+)").search(result) if not match_name: raise Exception("can't get app_name_info") apk_info = dict() apk_info['appPackage'] = match_package.group(1) apk_info['versionCode'] = match_package.group(2) apk_info['versionName'] = match_package.group(3) apk_info['appActivity'] = match_activity.group(1) apk_info['appName'] = match_name.group(1) return apk_info def get_apk_size(self): """ 获取apk大小 :return: apk_size """ apk_size = math.floor(os.path.getsize(self.apk_path) / (1024 * 1000)) return str(apk_size) + "M" if __name__ == '__main__': pass apk_info1 = ApkUtil(r"D:\uiTest\AutoTestAppium\yamls\config\CLauncher-release.apk").get_apk_info() print(apk_info1) log.info(apk_info1) #log.info(ApkUtil(r"D:\workspace\PycharmProjects\AutoTestAppium\yamls\config\CLauncher-release.apk").get_apk_size())
beae9ed58a8f718dae73ac2eeada58457793ef6f
[ "Markdown", "Python" ]
14
Python
xieyiyu/AutoTestAppium
5c5008d86d7480481b885cc3c6d4e58ec59e53af
31db4e559b43d7d9e4d303a8f78fafb43adb3900
refs/heads/master
<file_sep>using Syncfusion.SfSchedule.XForms; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using Xamarin.Forms; namespace ResourceView { public class SchedulerPageBehavior : Behavior<ContentPage> { SfSchedule schedule; protected override void OnAttachedTo(ContentPage bindable) { base.OnAttachedTo(bindable); this.schedule = bindable.Content.FindByName<SfSchedule>("schedule"); this.WireEvents(); var col = schedule.ViewHeaderStyle.DateTextColor; } private void WireEvents() { this.schedule.VisibleDatesChangedEvent += OnVisibleDatesChangedEvent; } private void OnVisibleDatesChangedEvent(object sender, VisibleDatesChangedEventArgs e) { var currentMonth = e.visibleDates[e.visibleDates.Count / 2].Month; var intern = schedule.ScheduleResources.FirstOrDefault(emp => (emp as Employee).Id.ToString() == "8600"); if (currentMonth == 2 || currentMonth == 7) { if (intern != null) return; Employee employee = new Employee(); employee.Name = "Sophiya"; employee.Id = "8600"; employee.Color = Color.FromHex("#FFE671B8"); employee.DisplayPicture = "employee0.png"; schedule.ScheduleResources.Add(employee); } else { if (intern == null) return; schedule.ScheduleResources.Remove(intern); } } protected override void OnDetachingFrom(ContentPage bindable) { base.OnDetachingFrom(bindable); this.UnWireEvents(); } private void UnWireEvents() { this.schedule.VisibleDatesChangedEvent -= OnVisibleDatesChangedEvent; } } } <file_sep># Resource-view ## Resource view in Xamarin Forms Scheduler Xamarin.Forms resource view is a discrete view integrated with the scheduler to display events in all types of schedule views. It allows users to select single or multiple resources and display the events associated with the selected resources with efficient and effective utilization. Each resource can be assigned a unique color to more easily identify the resource associated with an appointment. Its rich feature set includes data binding, customization and other features like globalization and localization. For more details about Resource view: https://www.syncfusion.com/xamarin-ui-controls/xamarin-scheduler/resource-view Resource view user guide: https://help.syncfusion.com/xamarin/sfschedule/resource-view <file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using Xamarin.Forms; namespace ResourceView { public class Event { /// <summary> /// Gets or sets event name /// </summary> public string EventName { get; set; } /// <summary> /// Gets or sets organizer /// </summary> public string Organizer { get; set; } /// <summary> /// Gets or sets contact ID /// </summary> public string ContactID { get; set; } /// <summary> /// Gets or sets capacity /// </summary> public int Capacity { get; set; } /// <summary> /// Gets or sets date /// </summary> public DateTime From { get; set; } /// <summary> /// Gets or sets date /// </summary> public DateTime To { get; set; } /// <summary> /// Gets or sets color /// </summary> public Color Color { get; set; } /// <summary> /// Gets or sets minimum height /// </summary> public double MinimumHeight { get; set; } /// <summary> /// Gets or sets all day /// </summary> public bool IsAllDay { get; set; } /// <summary> /// Gets or sets start time zone /// </summary> public string StartTimeZone { get; set; } /// <summary> /// Gets or sets end time zone /// </summary> public string EndTimeZone { get; set; } /// <summary> /// Gets or sets resources /// </summary> public ObservableCollection<object> Resources { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using Xamarin.Forms; namespace ResourceView { /// <summary> /// Represents custom data properties. /// </summary> public class Employee { /// <summary> /// Gets or sets name /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets id /// </summary> public object Id { get; set; } /// <summary> /// Gets or sets Color /// </summary> public Color Color { get; set; } /// <summary> /// Gets or sets display picture /// </summary> public string DisplayPicture { get; set; } } }
b388307bbc787a00c4625781698519e2c545124a
[ "Markdown", "C#" ]
4
C#
SyncfusionExamples/Resource-view
1431fc158ad7641d528095267b24f2cda8137760
00dc395053298bfa3a2c8177c1895fab68be9733
refs/heads/master
<file_sep># liri-node-app 1. LIRI is a Language Interpretation and Recognition Interface. LIRI will be a command line node app that takes in parameters and gives you back data. 2. App contains of variables to retrieve data from npm, a function to take user input, and js functions to search concerts, song, movie with user input. 3. Before start searching, run the following code in terminal: 1) npm install axios 2) npm install --save node-spotify-api 3) npm install moment --save 4) npm install dotenv * Make sure to register spotify ID and Secret. Then create a ".env" file and put API keys in there. 4. a) node liri.js concert-this "artist or band name here" Will show the following details: -Name of the venue -Venue location -Date of the Event (use moment to format this as "MM/DD/YYYY") b) node liri.js spotify-this-song "song name here" Will show the following details: -Artist(s) -The song's name -A preview link of the song from Spotify -The album that the song is from c) node liri.js movie-this "movie name here" Will show the following details: -Title of the movie. -Year the movie came out. -IMDB Rating of the movie. -Rotten Tomatoes Rating of the movie. -Country where the movie was produced. -Language of the movie. -Plot of the movie. -Actors in the movie. d) node liri.js do-what-it-says "whatever you want to search here" It should run spotify-this-song for "I Want it That Way," as follows the text in random.txt 5. Video Link: https://www.youtube.com/watch?v=kSxC1mwzt-c&feature=youtu.be 6. technologies used in the app: - npm - api (OMDB, Spotify, Bandsintown) - node - javascript 7. I am the sole developer of this app. <file_sep>require("dotenv").config(); var fs = require("fs"); var moment = require("moment"); var axios = require("axios"); var keys = require("./keys.js"); var Spotify = require('node-spotify-api'); var spotify = new Spotify(keys.spotify); var option = process.argv[2]; var input = process.argv[3]; UserInput(option, input); var log = [option, input] fs.appendFileSync("log.txt", log + '\n'); function UserInput (option, input) { switch (option) { case 'concert-this': showConcert(input); break; case 'spotify-this-song': showSpotify(input); break; case 'movie-this': showMoive(input); break; case 'do-what-it-says': showSomething(input); break; default: console.log("Invalid option." + "\nOption List: " + "\nconcert-this" + "\nspotify-this-song" + "\nmovie-this" + "\ndo-what-it-says"); }; }; function showConcert(input) { axios.get("https://rest.bandsintown.com/artists/" + input + "/events?app_id=codingbootcamp") .then(function (response) { for (var i = 0; i < response.data.length; i++) { console.log("----------------------------------------------------------"); console.log("Name of the venue : " + response.data[i].venue.name); console.log("Venue location : " + response.data[i].venue.city + response.data[i].venue.region + response.data[i].venue.country); console.log("Date of the event : " + moment(response.data[i].datetime).calendar()); console.log("----------------------------------------------------------"); } }).catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log("---------------Data---------------"); console.log(error.response.data); console.log("---------------Status---------------"); console.log(error.response.status); console.log("---------------Status---------------"); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an object that comes back with details pertaining to the error that occurred. console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log("Error", error.message); } console.log(error.config) }) } function showSpotify(input) { if (input === undefined) { input = "The Sign"; } spotify.search( { type: "track", query: input }, function(err, data) { if (err) { return console.log("Error occurred: " + err); }; for (var i = 0; i < data.tracks.items.length; i++) { console.log("----------------------------------------------------------"); console.log("Artist: " + data.tracks.items[i].artists[0].name); console.log("Song: " + data.tracks.items[i].name); console.log("Preview URL: " + data.tracks.items[i].preview_url); console.log("Album: " + data.tracks.items[i].album.name); console.log("----------------------------------------------------------"); }; }); }; function showMoive(input) { axios.get("http://www.omdbapi.com/?t=" + input + "&y=&plot=short&apikey=trilogy") .then(function(response) { if (response.data.Title === undefined) { showMoive("Mr. Nobody"); } else { console.log("----------------------------------------------------------"); console.log("Title : " + response.data.Title); console.log("Released : " + response.data.Released); console.log("IMDB Rating : " + response.data.imdbRating); if (response.data.Ratings[1] === undefined) { console.log("No Rotten Tomatoes Score Available."); } else { console.log("Rotten Tomatoes Score : " + response.data.Ratings[1].Value); } console.log("Country: " + response.data.Country); console.log("Language: " + response.data.Language); console.log("Plot: " + response.data.Plot); console.log("Actors: " + response.data.Actors); console.log("----------------------------------------------------------"); } }) .catch(function(error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log("---------------Data---------------"); console.log(error.response.data); console.log("---------------Status---------------"); console.log(error.response.status); console.log("---------------Status---------------"); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an object that comes back with details pertaining to the error that occurred. console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log("Error", error.message); } console.log(error.config); }); } function showSomething(input) { fs.readFile("random.txt", "utf8", function(error,data) { if (error) { return console.log(error); } var dataArr = data.split(","); UserInput(dataArr[0],dataArr[1]); }) }
8167f93e965657c53d7624d433d57fd9afd25eb9
[ "Markdown", "JavaScript" ]
2
Markdown
benfung1996/liri-node-app
05da1573bdaf0be508edcf067a7d15cbcdd0d000
8b537fa29a4c3818f9373d7a8dbe1b105699f0e3
refs/heads/main
<file_sep>package story; class Tortoise extends Thread{ public void run() { for(int distance = 1; distance <= 100; distance++) { System.out.println("Tortoise ran "+distance+" distance."); if(distance == 100) { System.out.println("------Tortoise wins the race!!!------"); } } } } class Hare extends Thread { public void run() { for(int distance = 1; distance <= 100; distance++) { System.out.println("Hare ran "+distance+" distance."); if(distance == 50) { try { System.out.println("------Hare goes to sleep.------"); Thread.sleep(3000); System.out.println("------Hare started the race again.------"); } catch(InterruptedException e) { } } } System.out.println("------Hare finished the race!!!------"); } } public class Race{ public static void main(String[] args) { Tortoise tortoise = new Tortoise(); Hare hare = new Hare(); tortoise.start(); hare.start(); System.out.println("------Race Started------"); } } <file_sep>package interest; import java.util.Scanner; public class RDAccount extends Account{ public int age=0,amount=0,months=0; public double rateOfInterest =0; public double interest=0; Scanner s= new Scanner(System.in); public void rda() { calculateInterest(); double I = (rateOfInterest * amount)/100; System.out.println("Interest Gained is "+Math.round(I)); Main.display(); } @Override double calculateInterest() { System.out.println("Enter the RD amount: "); amount = s.nextInt(); if(amount < 0) { try { System.out.println("Invalid amount entered. Please enter non-negative amount."); System.out.println("Starting the calculator again......"); calculateInterest(); } catch(Exception e) { e.printStackTrace(); } } System.out.println("Enter your age : "); age=s.nextInt(); if(age < 0) { try { System.out.println("Invalid age entered. Please enter non-negative age."); System.out.println("Starting the calculator again......"); calculateInterest(); } catch(Exception e) { e.printStackTrace(); } } System.out.println("Enter the number of months from(6,9,12,15,18,21)"); months=s.nextInt(); if(months < 0) { try { System.out.println("Invalid number of months entered. Please enter non-negative number of months from(6,9,12,15,18,21)."); System.out.println("Starting the calculator again......"); calculateInterest(); } catch(Exception e) { e.printStackTrace(); } } if(age > 60) { if(months == 6) { rateOfInterest = 8.00; } else if(months == 9) { rateOfInterest = 8.25; } else if(months == 12) { rateOfInterest = 8.50; } else if(months == 15) { rateOfInterest = 8.75; } else if(months == 18) { rateOfInterest = 9.00; } else if(months == 21) { rateOfInterest = 9.25; } else { System.out.println("Invalid number of months entered."); System.out.println("Starting the calculator again......"); calculateInterest(); } return (rateOfInterest/100)/12; } else { if(months == 6) { rateOfInterest = 7.50; } else if(months == 9) { rateOfInterest = 7.75; } else if(months == 12) { rateOfInterest = 8.00; } else if(months == 15) { rateOfInterest = 8.25; } else if(months == 18) { rateOfInterest = 8.50; } else if(months == 21) { rateOfInterest = 8.75; } else { System.out.println("Invalid number of months entered."); System.out.println("Starting the calculator again......"); calculateInterest(); } } return (rateOfInterest/100)/365; } } <file_sep>/*Design and implement a simple inventory control system for a small video rental store * This class contains VideoStoreLauncher*/ import java.util.Scanner; public class VideoStoreLauncher { public static void main(String[] args) { VideoStore vs = new VideoStore(); int ch, ch1, ch2; String title, choice; do { System.out.println("=========Menu========"); System.out.println("1. Login as User"); System.out.println("2. Login as Admin"); System.out.println("Enter your choice"); Scanner s = new Scanner(System.in); ch = s.nextInt(); do { switch(ch) { case 1: System.out.println("1. List Inventory"); System.out.println("2. Rent Video"); System.out.println("3. Enter the rating of video"); System.out.println("4. Return Video"); ch1 = s.nextInt(); if(ch1==1) { vs.listInventory(); } else if(ch1==2){ vs.listInventory(); System.out.println("Enter the video name you want"); title = s.next(); vs.checkOut(title); } else if(ch1==3) { vs.listInventory(); System.out.println("Enter the video name you want to give rating to"); title = s.next(); vs.receiveRating(title); } else if(ch1==4) { vs.listInventory(); System.out.println("Enter the video you want to return"); title = s.next(); vs.returnVideo(title); System.out.println("Video returned successfully."); } else { System.out.println("No such option is available."); }break; case 2: System.out.println("1. List Inventory"); System.out.println("2. Add Video"); ch2 = s.nextInt(); if(ch2==1) { vs.listInventory(); } if(ch2==2) { System.out.println("Enter the name of the video"); title = s.next(); vs.addVideo(title); }break; default: System.out.println("Sorry wrong choice."); } System.out.println("Do you want to repeat yes/no"); choice = s.next(); } while(choice.equalsIgnoreCase("yes")); System.out.println("Want to return to main menu yes/no"); choice = s.next(); }while(choice.equalsIgnoreCase("yes")); } } <file_sep>import java.util.Scanner; import java.sql.*; public class classA { public static void main(String[] args) { String JdbcURL = "jdbc:mysql://localhost:3306/music_store"; String Username = "root"; String Password = "<PASSWORD>"; Scanner s = new Scanner(System.in); Connection con = null; try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("Connecting to database.........................."); con = DriverManager.getConnection(JdbcURL, Username, Password); System.out.println("Connection is successful!!!"); Statement stmt = con.createStatement(); } catch(Exception e) { e.printStackTrace(); } boolean temp = true; while (temp) { System.out.println("1. Enter Inventory\n2. Show Inventory\n3. Sales\n4. Exit\nEnter your choice"); int choice = s.nextInt(); switch(choice) { case 1:{ System.out.println("Enter Name: "); String cd = s.next(); System.out.println("Enter quantity: "); int quantity = s.nextInt(); System.out.println("Enter price:"); String price = s.next(); try { PreparedStatement ps = con.prepareStatement("INSERT into inventory(Name, Quantity, Cost) values(?,?,?)"); ps.setString(1, cd); ps.setInt(2, quantity); ps.setString(3,price); int n = ps.executeUpdate(); System.out.println(n+" number of rows has been successfully executed."); break; } catch(Exception e) { e.printStackTrace(); } break; } case 2:{ try { PreparedStatement ps = con.prepareStatement("SELECT * FROM inventory;"); ResultSet rs = ps.executeQuery(); System.out.println("Id\tName\tQuantity\tCost"); while(rs.next()) { int id = rs.getInt(1); String name = rs.getString(2); int quantity = rs.getInt(3); int cost = rs.getInt(4); System.out.format("%s\t%s\t\t\t%s\t%s\n",id, name, quantity, cost); } } catch(Exception e) { e.printStackTrace(); } break; } case 3:{ try { PreparedStatement ps = con.prepareStatement("SELECT * FROM inventory;"); ResultSet rs = ps.executeQuery(); System.out.println("Id\tName\tQuantity\tCost"); while(rs.next()) { int id = rs.getInt(1); String name = rs.getString(2); int quantity = rs.getInt(3); int cost = rs.getInt(4); System.out.format("%s\t%s\t\t\t%s\t%s\n",id, name, quantity, cost); } } catch(Exception e) { e.printStackTrace(); } System.out.println("Enter the id of the music cd that you want to buy:"); int buy = s.nextInt(); try { PreparedStatement ps = con.prepareStatement("SELECT * FROM inventory;"); ResultSet rs = ps.executeQuery(); while(rs.next()) { int id = rs.getInt(1); String name = rs.getString(2); int quantity = rs.getInt(3); int cost = rs.getInt(4); if(buy == id) { quantity = quantity-1; ps = con.prepareStatement("UPDATE inventory SET Quantity = "+ quantity +" WHERE Id = "+buy+" "); ps.executeUpdate(); System.out.println("You bought "+ name + " of quantity 1 for price "+ cost); } } } catch(Exception e) { e.printStackTrace(); } break; } case 4:{ try { con.close(); } catch (SQLException e) { e.printStackTrace(); } temp = false; } } } } } <file_sep>package interest; import java.util.Scanner; public class FDAccount extends Account{ public int age=0,amount=0,days=0; public double rateOfInterest =0; public double interest=0; Scanner s= new Scanner(System.in); public void fda() { calculateInterest(); double I = (amount * rateOfInterest)/100; System.out.println("Interest Gained is "+Math.round(I)); Main.display(); } @Override double calculateInterest() { System.out.println("Enter the FD amount:"); amount = s.nextInt(); if(amount < 0) { try { System.out.println("Invalid amount entered. Please enter non-negative amount."); System.out.println("Starting the calculator again......"); calculateInterest(); } catch(Exception e) { e.printStackTrace(); } } System.out.println("Enter number of days:"); days = s.nextInt(); if(days < 0) { try { System.out.println("Invalid number of days entered. Please enter non-negative number of days."); System.out.println("Starting the calculator again......"); calculateInterest(); } catch(Exception e) { e.printStackTrace(); } } System.out.println("Enter your age:"); age = s.nextInt(); if(age < 0) { try { System.out.println("Invalid age entered. Please enter non-negative age."); System.out.println("Starting the calculator again......"); calculateInterest(); } catch(Exception e) { e.printStackTrace(); } } if(amount < 10000000) { if(age>60) { if(days>=7 && days<=14) { rateOfInterest = 5.00; } else if(days>=15 && days<=29) { rateOfInterest = 5.25; } else if(days>=30 && days<=45) { rateOfInterest = 6.00; } else if(days>=46 && days<=60) { rateOfInterest = 7.25; } else if(days>=61 && days<=184) { rateOfInterest = 8.00; } else if(days>=184 && days<=365) { rateOfInterest = 8.50; } else { System.out.println("Invalid number of days."); } } else { if(days>=7 && days<=14) { rateOfInterest = 4.50; } else if(days>=15 && days<=29) { rateOfInterest = 4.75; } else if(days>=30 && days<=45) { rateOfInterest = 5.50; } else if(days>=46 && days<=60) { rateOfInterest = 7.00; } else if(days>=61 && days<=184) { rateOfInterest = 7.50; } else if(days>=184 && days<=365) { rateOfInterest = 8.00; } else { System.out.println("Invalid number of days."); } } return (rateOfInterest/100)/365; } else { System.out.println("Enter the no. of days:"); days = s.nextInt(); if(days>=7 && days<=14) { rateOfInterest = 6.50; } else if(days>=15 && days<=29) { rateOfInterest = 6.75; } else if(days>=30 && days<=45) { rateOfInterest = 6.75; } else if(days>=46 && days<=60) { rateOfInterest = 8.00; } else if(days>=61 && days<=184) { rateOfInterest = 8.50; } else if(days>=184 && days<=365) { rateOfInterest = 10.00; } else { System.out.println("Invalid number of days."); } return (rateOfInterest/100)/365; } } } <file_sep>/* Create an application to save the employee information using arrays having following fields:- * empid[],depName[],empDes,empName[],dateJoin[],basic[],hra[],it[], DesCodes[]. Tasks:- (a) Salary should be calculated as (Basic+HRA+DA-IT) (b)Printing designation and da according to employee designation.*/ import java.util.Scanner; public class Employee { public static void main(String[] args) { Scanner s = new Scanner(System.in); String empid[] = {"1001","1002","1003","1004","1004","1005","1006","1007"}; String depName[] = {"R&D","PM","Acct","Front Desk","Engg","Manufacturing","PM"}; String empName[] = {"Ashish","Sushma","Rahul","Chahat","Ranjan","Suman","Tanmay"}; String dateJoin[] = {"01/04/2009","24/08/2012","12/11/2008","29/01/2013","16/07/2005","01/01/2000","12/06/2006"}; int basic[] = {20000,30000,10000,12000,50000,23000,29000}; int hra[] = {8000,12000,8000,6000,20000,9000,12000}; int it[] = {3000,9000,1000,2000,20000,4400,10000}; String desg = null; char DesCodes[] = {'e','c','k','r','m','e','c'}; int pos = -1; System.out.println("Enter the Employee Id between "+empid[0]+" and "+empid[7]); String id = s.nextLine(); for(int i=0;i<(empid.length);i++) { if(id.equals(empid[i])) { pos = i; } } if(pos==-1) { System.out.println("There is no employee id: "+id); return; } int da = 0; char empDes = DesCodes[pos]; switch(empDes) { case 'e': desg = "Engineer"; da = 20000; break; case 'c': desg = "Consulants"; da = 32000; break; case 'k': desg = "Clerk"; da = 12000; break; case 'r': desg = "Receptionist"; da = 15000; break; case 'm': desg = "Manager"; da = 40000; break; } int salary = basic[pos]+hra[pos]+da-it[pos]; System.out.println("Emp no.\t\tEmployee Name\t\tDepartment\t\tDesignation\t\tSalary"); System.out.println(empid[pos]+"\t\t\t"+empName[pos]+"\t\t\t\t"+depName[pos]+"\t\t\t\t"+desg+"\t\t\t"+salary); } } <file_sep>package interest; import java.util.Scanner; public class Main { public static void display() { Scanner s = new Scanner(System.in); System.out.println("---------------Main menu--------------"); System.out.println("------------------------------------------"); System.out.println("1. Interest Calculator -> SB"); System.out.println("2. Interest Calculator -> FD"); System.out.println("3. Interest Calculator -> RD"); System.out.println("4. Exit"); System.out.println("Enter your option from above"); int option = s.nextInt(); switch(option) { case 1: SBAccount sb = new SBAccount(); sb.sda(); break; case 2: FDAccount fd = new FDAccount(); fd.fda(); break; case 3: RDAccount rd = new RDAccount(); rd.rda(); break; case 4: System.exit(0); break; default: System.out.println("Enter a valid option."); } } public static void main(String[] args) { display(); } }<file_sep># Java-Projects #These are projects. Project 1: Create an application to save the employee information using arrays having following fields:- empid[],depName[],empDes,empName[],dateJoin[],basic[],hra[],it[], DesCodes[]. Tasks:- (a) Salary should be calculated as (Basic+HRA+DA-IT) Printing designation and da according to employee designation. Project 2: Design and implement a simple inventory control system for a small video rental store. Project 3: Create an application to calculate interest for FDs, RDs based on certain conditions using inheritance. Project 4: Create a menu based Java application with the following options.1.Add an Employee2.Display All3.Exit If option 1 is selected, the application should gather details of the employee like employee name, employee id, designation and salary and store it in a file. If option 2 is selected, the application should display all the employee details. If option 3 is selected the application should exit. Project 5: (a) Create a program to set view of Keys from Java Hash table. (b) Create a program to show the usage of Sets of Collection interface. Project 6: Write a Program to perform the basic operations like insert, delete, display and search in list. List contains String object items where these operations are to be performed Project 7: Write a Java multi threaded program to implement the tortoise and hare story. Make the hare sleep at the mid of the way and let the tortoise win. Project 8: Create a console based application using Java as frontend and Oracle as backend for their Inventory and Sales maintenance. <file_sep>package interest; import java.util.Scanner; public class SBAccount extends Account{ Scanner s = new Scanner(System.in); public int amount = 0; public double rateOfInterest = 0, interest = 0; public int choice = 0; public void sda() { System.out.println("Enter the average amount in your account:"); amount = s.nextInt(); if(amount < 0) { System.out.println("Invalid amount entered. Please enter non-negative amount."); sda(); } calculateInterest(); interest = amount*rateOfInterest; System.out.println("Interest gained is "+Math.round(interest)/100); Main.display(); } @Override double calculateInterest() { System.out.println("Enter your account type:"); System.out.println("1. Normal"); System.out.println("2. NRI"); System.out.println("Enter your choice"); choice = s.nextInt(); switch(choice) { case 1: rateOfInterest = 4; break; case 2: rateOfInterest = 6; break; default: System.out.println("Enter a valid type."); calculateInterest(); } return rateOfInterest; } } <file_sep>import java.util.*; public class Main { public static void fun() { LinkedHashMap<Integer, String[]> Stock= new LinkedHashMap<Integer, String[]>(); Scanner s = new Scanner(System.in); boolean flag = true; while(flag){ System.out.println("1. As Shopkeeper" + "\n" + "2. As Customer"); System.out.println("Enter Choice: "); int choice = s.nextInt(); switch(choice) { case 1:{ boolean con = true; while(con){ System.out.println(); System.out.println("1. Enter Stock" + "\n" + "2. Display Stock" +"\n" + "3. Go Back"); int ch = s.nextInt(); switch(ch){ case 1:{ String [] val = new String[2]; System.out.println("Enter Itemcode: "); int itemcode = s.nextInt(); System.out.println("Enter Name: "); String Name = s.next(); val[0] = Name; System.out.println("Enter Cost: "); String Cost = s.next(); val[1] = Cost; Stock.put(itemcode, val); break; } case 2:{ System.out.println("Itemcode Name Cost"); for (Map.Entry data: Stock.entrySet()){ String [] value = (String[]) data.getValue(); System.out.println(data.getKey()+" "+value[0]+" "+value[1]); } break; } case 3:{ con = false; } } } break; } case 2:{ boolean con = true; Integer totalAmount = 0; LinkedHashMap<Integer,String[]> Customer = new LinkedHashMap<Integer,String[]>(); while(con){ System.out.println(); System.out.println("1. Display Stock" + "\n" + "2. Purchase" +"\n" + "3. Bill"+"\n"+"4.Exit"); int ch = s.nextInt(); switch(ch){ case 1:{ System.out.println(); System.out.println("Itemcode Name Cost"); for (Map.Entry data: Stock.entrySet()){ String [] value = (String[]) data.getValue(); System.out.println(data.getKey()+" "+value[0]+" "+value[1]); } break; } case 2:{ System.out.println(); System.out.println("Enter Itemcode: "); int code = s.nextInt(); String [] value = (String[]) Stock.get(code); totalAmount = totalAmount + Integer.parseInt(value[1]); Customer.put(code,value); break; } case 3:{ System.out.println(); for (Map.Entry data: Customer.entrySet()){ String [] value = (String[]) data.getValue(); System.out.println(data.getKey()+" "+value[0]+" "+value[1]); } System.out.println("Total Amount: "+totalAmount); break; } case 4:{ System.exit(0); } } } } } } } public static void main(String[] args) { fun(); } } <file_sep>/*Design and implement a simple inventory control system for a small video rental store * This class contains VideoStore class which extends Video class*/ import java.util.Scanner; public class VideoStore extends Video{ Video v[] = new Video[100]; static int i = 0; void addVideo(String title) { v[i] = new Video(); this.title = title; v[i].title = title; i++; System.out.println("Video Added Successfully."); } void checkOut(String title) { for(int k=0; k<i; k++) { if(v[k].title.equalsIgnoreCase(title)) { if(v[k].checked()) { v[k].rent(); System.out.println("Video is rented."); } else { System.out.println("Sorry, video is not available."); } } } } void returnVideo(String title) { if(i==0) { System.out.println("You have no video to return."); } for(int k=0; k<i; k++) { if(v[k].title.equalsIgnoreCase(title)) { v[k].checked = true; } } } public void receiveRating(String title) { if(i==0) { System.out.println("No video inventory available."); } else { for(int k=0; k<i; k++) { System.out.println("Enter the rating for the video "+v[k].title); Scanner s = new Scanner(System.in); v[k].avgrating = s.nextInt(); } } } public void listInventory() { if(i==0) { System.out.println("No video in inventory."); } else { for(int k=0; k<i; k++) { System.out.println(k+1 +". "+v[k].title+" "+" Rating "+v[k].avgrating+" Availability "+v[k].checked()); } } } }
9f5cd950ca677a8f3fbc6d337cd1abd44f920ed1
[ "Markdown", "Java" ]
11
Java
prabhat2407/Java-Projects
4ec79712d2d38610c3a0d47945b6fe6a316f56d5
c1e4d2779c1baeb79b57b4bd2a5909d098da6db1
refs/heads/master
<file_sep>################################################################################ # Automatically-generated file. Do not edit! ################################################################################ SHELL = cmd.exe # Add inputs and outputs from these tool invocations to the build variables CMD_SRCS += \ ../msp432p401r.cmd C_SRCS += \ ../bump_switch.c \ ../distance_sensor.c \ ../line_sensor.c \ ../main.c \ ../motor.c \ ../startup_msp432p401r_ccs.c \ ../system_msp432p401r.c C_DEPS += \ ./bump_switch.d \ ./distance_sensor.d \ ./line_sensor.d \ ./main.d \ ./motor.d \ ./startup_msp432p401r_ccs.d \ ./system_msp432p401r.d OBJS += \ ./bump_switch.obj \ ./distance_sensor.obj \ ./line_sensor.obj \ ./main.obj \ ./motor.obj \ ./startup_msp432p401r_ccs.obj \ ./system_msp432p401r.obj OBJS__QUOTED += \ "bump_switch.obj" \ "distance_sensor.obj" \ "line_sensor.obj" \ "main.obj" \ "motor.obj" \ "startup_msp432p401r_ccs.obj" \ "system_msp432p401r.obj" C_DEPS__QUOTED += \ "bump_switch.d" \ "distance_sensor.d" \ "line_sensor.d" \ "main.d" \ "motor.d" \ "startup_msp432p401r_ccs.d" \ "system_msp432p401r.d" C_SRCS__QUOTED += \ "../bump_switch.c" \ "../distance_sensor.c" \ "../line_sensor.c" \ "../main.c" \ "../motor.c" \ "../startup_msp432p401r_ccs.c" \ "../system_msp432p401r.c" <file_sep>#include <stdint.h> #include "msp.h" void MotorInit(void){ // P1.7 Left Motor Direction, P1.6 Right Motor Direction. 0 for FWD, 1 for REV P1->DIR |= (BIT6|BIT7); P1->SEL0 &= ~(BIT6|BIT7); P1->SEL1 &= ~(BIT6|BIT7); P1->OUT &= ~(BIT6|BIT7); // P2.7 Left Motor PWM, P2.6 Right Motor PWM. 0 for off, 1 for on. P2->DIR |= (BIT6|BIT7); P2->SEL0 |= (BIT6|BIT7); P2->SEL1 &= ~(BIT6|BIT7); P2->OUT &= ~(BIT6|BIT7); // Enables P2.6 and P2.7 as TA0.3 and TA0.4 Function // P3.7 Left Motor Sleep, P3.6 Right Motor Sleep. 0 for off, 1 for on. P3->DIR |= (BIT6|BIT7); P3->SEL0 &= ~(BIT6|BIT7); P3->SEL1 &= ~(BIT6|BIT7); P3->OUT &= ~(BIT6|BIT7); TIMER_A0->CCTL[0] = 0x0080; // CCI0 toggle TIMER_A0->CCR[0] = 150; // PWM period of 150 clock cycles equates to 10KHz frequency. TIMER_A0->EX0 = 0x0000; // Divide by 1 TIMER_A0->CCTL[3] = 0x0040; // CCR1 toggle/reset TIMER_A0->CCR[3] = 0x00; // Duty cycle for motor1. Initially set to zero. TIMER_A0->CCTL[4] = 0x0040; // CCR1 toggle/reset TIMER_A0->CCR[4] = 0x00; // Duty cycle for motor2. Initially set to zero. TIMER_A0->CTL = 0x0230; // SMCLK=12MHz, divide by 1, up-down count mode. } // zero for disable motor, one for enable void Motor_Enable(int leftMotorPwr, int rightMotorPwr) { int x = (leftMotorPwr<<1)|(rightMotorPwr); switch(x){ case 00 : P3->OUT &= ~BIT7; //turn sleep low P3->OUT &= ~BIT6; //turn sleep low break; case 01 : P3->OUT &= ~BIT7; //turn sleep low P3->OUT |= BIT6; //turn sleep high break; case 2 : P3->OUT |= BIT7; //turn sleep high P3->OUT &= ~BIT6; //turn sleep low break; case 3 : P3->OUT |= BIT7; //turn sleep high P3->OUT |= BIT6; //turn sleep high break; } } // zero for forward, one for reverse void Motor_Direction(int leftMotorDir, int rightMotorDir) { int x = (leftMotorDir<<1)|(rightMotorDir); switch(x){ case 00 : P1->OUT &= ~BIT7; //turn sleep low P1->OUT &= ~BIT6; //turn sleep low break; case 01 : P1->OUT &= ~BIT7; //turn sleep low P1->OUT |= BIT6; //turn sleep high break; case 2 : P1->OUT |= BIT7; //turn sleep high P1->OUT &= ~BIT6; //turn sleep low break; case 3 : P1->OUT |= BIT7; //turn sleep high P1->OUT |= BIT6; //turn sleep high break; } } // 0 to 100 percent duty cycle. 0.0 to 1.0 void Motor_Speed(float leftMotorPWM, float rightMotorPWM) { if (leftMotorPWM > 1.0){leftMotorPWM = 1.0;} if (leftMotorPWM < 0.0){leftMotorPWM = 0.0;} if (rightMotorPWM > 1.0){rightMotorPWM = 1.0;} if (rightMotorPWM < 0.0){rightMotorPWM = 0.0;} int period = TIMER_A0->CCR[0]; TIMER_A0->CCR[3] = (int)(period*leftMotorPWM); TIMER_A0->CCR[4] = (int)(period*rightMotorPWM); } <file_sep>/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // ECEN 2440 Lab 0.X Using the XXX. // // Start Date: 10-XX-2018 // // Target: Texas Instruments MSP-EXP432P401 dev kit // // Author: // // This code is designed to // // #include "msp.h" #include <stdio.h> // Put global and static variables here // put additional helper functions here. //............................................ Start of main() .................................................. void main(void) { // Disable the Watchdog WDT_A->CTL = WDT_A_CTL_PW | WDT_A_CTL_HOLD; // Set up the ADC. These bits are all defined in the MSP432P4xx Technical Reference Manual... ADC14->CTL0 = 0x00000000 ; // Disable the ADC14 before changing any values. ADC14->CTL0 &= 0xFFFFFFFD ; // Note that in this bit mask, only bit 1 is a zero. ADC14->CTL0 |= 0x00000010 ; // ADC14 on ADC14->CTL0 |= 0x04000000 ; // Source signal from the sampling timer **** ADC14->CTL1 = 0x30 ; // ADC14MEM0, 14-bit, ref on, regular power ADC14->MCTL[0] = 0x0F ; // 0 to 3.3V, select channel here. ADC14->IER0 = 0 ; // no interrupts ADC14->IER1 = 0 ; // no interrupts //ADC14->CTL0 = 0x00000002 ; // Enables ADC. TIMER_A0->CCTL[0] = 0x0080; // CCI0 toggle TIMER_A0->CCR[0] = 150; // PWM period of 150 clock cycles equates to 10KHz frequency. TIMER_A0->EX0 = 0x0000; // Divide by 1 TIMER_A0->CCTL[3] = 0x0040; // CCR1 toggle/reset TIMER_A0->CCR[3] = 0x00; // Duty cycle for motor1. Initially set to zero. TIMER_A0->CCTL[4] = 0x0040; // CCR1 toggle/reset TIMER_A0->CCR[4] = 0x00; // Duty cycle for motor2. Initially set to zero. TIMER_A0->CTL = 0x0230; // SMCLK=12MHz, divide by 1, up-down count mode. // Configures SysTick to roll over once every three milliseconds. SysTick->CTRL = 5; SysTick->LOAD = 30000; SysTick->VAL = 0; // Title line verifies that the code has started to execute. // Diagnostic printing... printf("Say Something Meaningful About This Code\n") ; //..................................... Start of infinite loop ................................................... while(1) { if ((SysTick->CTRL) > 5) { } } } /////////////////////////////////////////////// end of main.c /////////////////////////////////////////////////////////
9fcdd4d8f0432b7ac31dda50dc129c8d537ae2fc
[ "C", "Makefile" ]
3
Makefile
nsharit/RSLK2
8558dbd3df034b7886a5a0aa9c86d0e9e7c6859f
a9f60c1e2248511b43664c8ff2da02d2c14fc527
refs/heads/master
<file_sep>import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class PlaneTest { private Plane plane; @Before public void setUp() { plane = new Plane(PlaneType.BOEING737); } @Test public void canGetPlaneType() { assertEquals(PlaneType.BOEING737, plane.getType()); } @Test public void canGetCapacity() { assertEquals(189, plane.getCapacity()); } @Test public void canGetTotalWeight() { assertEquals(70535, plane.getTotalWeight()); } } <file_sep>import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class FlightTest { private Flight flight; private Plane plane; private Passenger passenger1; @Before public void setUp() { plane = new Plane(PlaneType.BOEING737); flight = new Flight(plane, "FR 1159", "EDI", "WRO", "07:15"); passenger1 = new Passenger("Jurgen", 1); } @Test public void flightStartsOffEmpty() { assertEquals(0, flight.passengerCount()); } @Test public void canGetPlane() { assertEquals(plane, flight.getPlane()); } @Test public void canGetFlightNumber() { assertEquals("FR 1159", flight.getFlightNumber()); } @Test public void canGetDestination() { assertEquals("WRO", flight.getDestination()); } @Test public void canGetDepartureAirport() { assertEquals("EDI", flight.getDepartureAirport()); } @Test public void canGetDepartureTime() { assertEquals("07:15", flight.getDepartureTime()); } @Test public void canGetNumberOfAvailableSeats() { assertEquals(189, flight.noOfAvailableSeats()); } @Test public void canBookPassengerOnFlight() { flight.book(passenger1); assertEquals(1, flight.passengerCount()); } }
17175082cec1de57d9c7a5e6cac3633859ca61d9
[ "Java" ]
2
Java
mtyran/W11_D5
7b81fabea6ebfc7d6e97b149ffbe86128e45738b
6e4d819cab1dc6cd3c71c2c2915d0e70733a8cc6
refs/heads/master
<repo_name>patmccler/sql-crowdfunding-lab-pca-001<file_sep>/lib/insert.sql INSERT INTO users (name, age) VALUES ("Mark", 15), ("John", 20), ("Gary", 53), ("Juan", 78), ("Pat", 32), ("Jenna", 37), ("Pam", 19), ("Jimmy", 46), ("Brendan", 55), ("Richard", 54), ("Alena", 32), ("Jenn", 50), ("Patty", 21), ("William", 35), ("Greg", 62), ("Carlos", 24), ("Sara", 25), ("Genna", 34), ("Tisha", 24), ("Michael", 42); INSERT INTO projects (title, category, funding_goal, start_date, end_date) VALUES ("Save the Trees", "green", 2000.00, 58995, 59000), ("Cut Down the Trees", "not green", 5000.00, 58996, 59001), ("Cancer Research", "medical", 15000.00, 59000, 59005), ("Cancer Research Also", "medical", 55000.00, 58995, 59000), ("Go to Mars!", "science", 100000.00, 58995, 69000), ("Make a Wish", "medical", 200000.00, 58995, 59000), ("Alex's Lemonade", "medical", 25000.00, 59600, 59605), ("Recycle R Us", "green", 1000.00, 58995, 59000), ("AGDQ", "medical", 100000.00, 59250, 59255), ("SGDQ", "medical", 100000.00, 58995, 59000); INSERT INTO pledges (user_id, project_id) VALUES (19, 1), (19, 2), (18, 3), (17, 4), (16, 5), (15, 6), (14, 7), (13, 8), (12, 9), (11, 9), (10, 1), (9, 2), (8, 3), (7, 4), (6, 5), (5, 1), (4, 2), (3, 3), (2, 4), (1, 5), (1, 1), (1, 2), (1, 3), (2, 4), (2, 1), (3, 2), (4, 3), (5, 1), (4, 2), (4, 1);<file_sep>/lib/sql_queries.rb # Write your sql queries in this file in the appropriate method like the example below: # # def select_category_from_projects # "SELECT category FROM projects;" # end # Make sure each ruby method returns a string containing a valid SQL statement. def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title "SELECT title, SUM(pledges.amount) FROM projects LEFT JOIN pledges WHERE projects.id = pledges.project_id GROUP BY projects.id ORDER BY title ASC" end def selects_the_user_name_age_and_pledge_amount_for_all_pledges_alphabetized_by_name "SELECT name, age, SUM(pledges.amount) FROM users JOIN pledges WHERE users.id = pledges.user_id GROUP BY users.id ORDER BY name ASC" end def selects_the_titles_and_amount_over_goal_of_all_projects_that_have_met_their_funding_goal "SELECT title, SUM(pledges.amount) - funding_goal FROM projects JOIN pledges WHERE projects.id = pledges.project_id GROUP BY projects.id HAVING SUM(pledges.amount) >= funding_goal" end def selects_user_names_and_amounts_of_all_pledges_grouped_by_name_then_orders_them_by_the_summed_amount "SELECT name, SUM(amount) FROM users JOIN pledges WHERE users.id = pledges.user_id GROUP BY name ORDER BY SUM(amount)" end def selects_the_category_names_and_pledge_amounts_of_all_pledges_in_the_music_category "SELECT category, amount FROM pledges INNER JOIN projects ON category = 'music' AND projects.id = pledges.project_id" end def selects_the_category_name_and_the_sum_total_of_the_all_its_pledges_for_the_books_category "SELECT category, SUM(amount) FROM pledges JOIN projects ON projects.id = pledges.project_id AND category = 'books'" end
1b7a199ebfbe966b64fc9c69757a39eec1ac14ac
[ "SQL", "Ruby" ]
2
SQL
patmccler/sql-crowdfunding-lab-pca-001
6bcbad3d8f7fe68a708cc1abb7e1986e14980f80
728cb761f0cd3255ff20820aec80bf8b570b08a9
refs/heads/master
<repo_name>aycherr/pythommemo<file_sep>/Python.py import math print("****** Method Kern ********") #lES CONSTANTS #Les Constants de cote chaud Tce = float(71) Tcs = float(49) mc=float() cpc=float(2.38) kc = float(0.129) viscoc = float(0.0002) Rdc = float(0.000025) Sgc = float(0.685) mvc = float(685) #Les Constants de cote froid Tfe = float(24) Tfs = float(49) mf= float(67500) cpf=float(2) kf = float(0.143) Rdf = float(0.000049) Sgf = float(0.8) visco = float(input(0.0016)) mv = float(input(800)) #constants general R = float(0.88) P = float(0.529) A = float() do=float() Lt = float() np = float() di=float() visco=float() Re = float() #======================================================================================================================================================= #energy balance Q = mf*cpf*(Tfs-Tfe) mc= Q/(cpc*(Tce-Tcs)) print("La puissance = ",Q) print("Le debit de fluid chaud = ",mc) #factor de correction S1 = math.sqrt((math.pow(R,2) + 1 ))* math.log((1-P)/(1-R*P)) S2 = (R-1)*math.log((2-P*(R+1-(math.sqrt(math.pow(R,2)+1))))/(2-P*(R+1+math.sqrt(math.pow(R,2)+1)))) Ft = S1/S2 print("le facteur de correction = ",Ft) #DTLM DTa=Tce-Tfs DTb=Tcs-Tfe DTLM =(DTa-DTb)/(math.log(DTa/DTb)) print("DTLM = ",DTLM) #la surface d'echange print("Enter le coef d'echange assume :") Uass = float(input()) #variable A = ((Q/3600)/(Uass*Ft*DTLM))*(10**3) print("la surface d'echange = ",A) #le nombre des tubes print("do :") do = float(input()) #variable print("La Longueur :") Lt = float(input()) #variable nt = (A) /(3.14*do*10**(-3)*Lt) print("nombre du tubes",nt) #la vitesse de fluide print("le nombre des passes :") np = float(input()) #variable print("le diametre interieur :") di = float(input()) #variable print("le nombre des tubes assume :") nta = float(input()) #variable Re = (4*(mf/3600)*(np/nta))/(3.14*di*10**(-3)*visco) print("le nombre de RYNOLDS cote tubes = ",Re) V=(Re*visco)/(di*10**(-3)*mv) print("La vitesse de fluide cote tubes = ",V) #le coef d'echange cote tubes print("le coeficient convectif:") jH = float(input()) #variable cpt = cpf kt = kf viscot = visco pr3 = ((viscot*cpt*10**3)/kt)**(0.3333333) h = (kt*jH*(pr3))/(di*10**(-3)) print("pr=",pr3) print("le coeficient d'echange cote tubes h=",h) #le diametre interieur de calandre print("'square' or 'triangle' pitch ?") st = str(input()) ys = "S" nn = "T" print("le pitch = ") Pt = float(input()) if (st==ys) : De= (4*((Pt**2)-(((3.14)*(do**2))/4)))/(3.14*do) print("De = ",De) elif (st==nn): De = (4*((0.5*Pt*0.86*Pt)-(0.5*(3.14*do**2)/4)))/(0.5*3.14*do) print("De = ",De) #le coefcient d'echange cote calandre print("enter clearence = ") clr = float(input()) #variable print("enter baffle spacing = ") spacing = float(input()) #variable print("le diametre exterieur de la calandre = ") Ds = float(input()) #variable a=((clr*10**(-3))*(spacing*10**(-3))*(Ds*10**(-3)))/(Pt*10**(-3)) print("shell side cross flow area = ",a) Gs = (mc/3600)/a print("Gs = ",Gs) Vc = Gs/mvc print("la vitesse de fluide cote calandre = ",Vc) Re2 = (De*10**(-3)*Gs)/viscoc print("Re cote calansre = ",Re2) cpt = cpc kt = kc viscot = viscoc print("enter jH = ") jH2 = float(input()) #variable jH=jH2 pr3 = ((viscot*cpt*10**3)/kt)**(0.3333333) h2 = (kt*jH*(pr3))/(De*10**(-3)) print("coef d'echange cote calandre :",h2) #le coeficient d'echange globale print(" Conductivite de materiaux de tube = ") km = float(input()) #variable A0 = float(3.14 *(do**2)) Ai = float(3.14 *(di**2)) Ucal = 1/((1/h2)+(Rdc)+(A0/Ai)*((do-di)*10**(-3))/((2*km))+((A0/Ai)*(1/h))+((A0/Ai)*Rdf)) print("Ucal = ",Ucal) print("Uass",Uass) #error error = (Ucal - Uass)/(Uass) print("******* error = ",error ,"********") #les petes de charges print("\n \n \n ********* LES PERTES DE CHARGES ***********") print(" facteur de friction f = ") f = float(input()) #variable DPt = np*(((8*f)*(Lt/(di*10**(-3))))+2.5)*((mv*(V**2))/2) print("Les pertes de charges cote tube DPt = ", DPt*10**(-5)) #les pertes de charges cote calandre print(" facteur de friction cote calandre f = ") fs = float(input()) #variable DPs = 8*(fs)*(Ds/De)*(Lt/spacing*10**(-3))*(((mvc*Vc**2))/2) print("les pertes de charges cote calandre = ",DPs) #Over Surface hio = h*(di/do) print("hio = ",hio) Uc = (h2*hio)/(h2+hio) print("Uc = ", Uc) osc = (Uc - Ucal)/Uc print("over surface osc = ",osc) #over design Asup = 3.14*do*10**(-3)*Lt*nta ovd = (Asup - A)/A print("Over design ovd = ",ovd) input()
7e7513e9aca97124790733544fd26f5a108db194
[ "Python" ]
1
Python
aycherr/pythommemo
68810f84010ce78b53cd67390904b35146b565ad
91ad25a6c98ebb3afbe82e9234247736f810d9c9
refs/heads/master
<file_sep>using System; using System.Linq; namespace duplicateEntry { class program { static void Main() { int[] arr = { 1,2,3, 1, 1, 2, 2, 2, 3, 3,7,9,9, 4, 8, 5 }; arr = arr.Distinct().ToArray(); Array.ForEach(arr, x => Console.WriteLine(x)); } } }
8fb2633223e7fb8bc5021aa120c6ee2a2bda888f
[ "C#" ]
1
C#
lokendra43824/DuplicateRemoval
d063717b5f74b5cb7a8d4bb02e44e6f5b69072e2
05834f76621627bac28042a95933277bcc77b597
refs/heads/master
<repo_name>gfhack/another-php<file_sep>/new/app/shop/_remove.php <?php $cart = split_cart(searchCookie()); foreach ($cart['product'] as $key => $value) { if($_GET['id'] == $value) { unset($cart['product'][$key]); unset($cart['amount'][$key]); } } $cookie = attach_cart($cart); setCookie('cart', $cookie, time()+3600*24); redirect_to('cart'); ?><file_sep>/new/app/shop/cart.php <?php require('_header.php'); require('_products.php'); $cart = split_cart(searchCookie()); $total = 0; ?> <div class="span10"> <header class='page-header'> <h1>Carrinho de Compras</h1> </header> <table class="table table-bordered table-striped"> <thead> <th></th> <th>Nome</th> <th>Quantidade</th> <th>Preço unitário</th> <th>Preço Total</th> </thead> <tbody> <?php if (!empty($cart)) { foreach($cart['product'] as $key => $value){ ?> <tr> <td><a href="_remove?id=<?= $value ?>" class="btn btn-small">X</a></td> <td><?= $products[$value]['name'] ?></td> <td> <?php echo '<form class="form-search" action="_buy" method="POST"> <input type="hidden" name="id" value="' . $value . '" /> <input type="number" min="1" name="amount" value="' . $cart['amount'][$key] . '" class="input-small" placeholder="Quantidade" /> <input type="submit" class="btn btn-primary" value="Alterar" /> </form>'; ?> </td> <td><?= @$products[$value]['price'] ?></td> <td> <?php $total += $cart['amount'][$key] * $products[$value]['price']; echo @$cart['amount'][$key] * $products[$value]['price']; ?> </td> </tr> <?php }} ?> <tr> <td>Total:</td> <td></td> <td></td> <td> </td> <td><?= $total ?></td> </tr> </tbody> </table> <a href="finish" class="btn btn-success">Efetuar compra!</a> </div> <?php require('_footer.php'); ?><file_sep>/new/app/login/_form.php <?php notAutenticated(); ?> <div class="span5"> <section> <header class='page-header'> <h1>Login</h1> </header> <form class="form-horizontal" action='log_in.php' method='POST' > <div class="control-group <?= isset($errors['email']) ? 'error' : '' ?>"> <label class="control-label" for="inputEmail">Email</label> <div class="controls"> <input type="text" id="inputEmail" name="user[email]" placeholder="Email" value="<?= @$email ?>"> </div> </div> <div class="control-group <?= isset($errors['password']) ? 'error' : '' ?>"> <label class="control-label" for="inputPassword">Password</label> <div class="controls"> <input type="<PASSWORD>" id="inputPassword" name="user[password]" placeholder="<PASSWORD>"> </div> </div> <div class="control-group"> <div class="controls"> <label class="checkbox"> <input type="checkbox"> Remember me </label> <button type="submit" class="btn">Sign in</button> </div> </div> </form> </section> </div><file_sep>/new/app/models/contact.php <?php class Contact { private $name; private $email; private $body; private $errors = array(); public function __construct($data = array()){ foreach($data as $key => $value){ $method = "set{$key}"; $this->$method($value); } } public function setName($name){ $this->name = $name; } public function setBody($body){ $this->body = $body; } public function setEmail($email){ $this->email = $email; } public function getName(){ return $this->name; } public function getEmail(){ return $this->email; } public function getBody(){ return $this->body; } public function isValid(){ Validations::notEmpty($this->name, $this->errors['name']); Validations::email($this->email, $this->errors['email']); Validations::notEmpty($this->body, $this->errors['body']); $this->errors = array_filter($this->errors, 'Validations::notEmpty'); return empty($this->errors); } public function errors(){ return $this->errors; } } ?> <file_sep>/new/app/files/_form.php <?php if (!isset($file)){ $file = new File(); } ?> <div class="span10"> <section> <header class='page-header'> <h1>Formulário de Arquivos</h1> </header> </section> <form id='file' action='<?= $sendTo ?>' method='POST' class='form-vertical' novalidate> <div class="control-group <?= isset($file->errors()['name']) ? 'error' :'' ?> " > <label class='control-label' for='file_name'>Nome *</label> <div class="controls"> <?php if (!is_null(@$disabled)) { ?> <input type='hidden' id='file_name' name='file[name]' value="<?= @$files['name'] ?>" /> <?php } ?> <input type='text' placeholder="Nome do arquivo" id="file_name" name='file[name]' value='<?= @$files['name'] ?>' <?= @$disabled ?> /> <span class='help-inline'><?= @$file->errors()['name']?></span> </div> </div> <div class="control-group <?= isset($file->errors()['body']) ? 'error' :'' ?>" > <label class='control-label' for='file_body'>Texto *</label> <div class="controls"> <textarea id='file_body' name='file[body]' placeholder='Texto do arquivo'><?= @$files['body'] ?></textarea> <span class='help-inline'><?= @$file->errors()['body']?></span> </div> </div> <input type='submit' value='Enviar' class='btn btn-primary'/> </form> </div> <file_sep>/new/app/index.php <?php require('_header.php'); ?> <div class="span10"> <section> <header> <h1>Página Inicial</h1> </header> </section> </div> <?php require('_footer.php'); ?> <file_sep>/new/app/files/index.php <?php $file_search = new FileSearch(APP_ROOT . 'app/files/txt'); $files = $file_search->findAll(); $recent_searchs = new RecentSearchs('search'); require('list.php'); ?><file_sep>/new/app/contact/receive.php <?php $contact = new Contact($_POST['contact']); if ($contact->isValid()) { flash('success', 'Mensagem enviada com sucesso!'); redirect_to('/'); } else{ flash('error', 'Existe dados incorretos no seu formulário!'); require ('new.php'); } ?><file_sep>/index.php <?php header('location: new/'); ?> <file_sep>/new/lib/utils.php <?php function stylesheet_include_tag() { $params = func_get_args(); foreach($params as $param){ $path = SITE_ROOT . "/assets/css/" . $param; echo "<link href='{$path}' rel='stylesheet' type='text/css' /> "; } } function link_to($path, $name, $options = '') { if (substr($path, 0, 1) == '/') $link = SITE_ROOT . $path; else $link = $path; return "<a href='{$link}' {$options}> $name </a> "; } function redirect_to($address) { if (substr($address, 0, 1) == '/') header('location: ' . SITE_ROOT . $address); else header('location: ' . $address); } function back(){ if (isset($_SERVER['HTTP_REFERER'])){ return $_SERVER['HTTP_REFERER']; }else{ return '/'; } } function javascript_include_tag(){ $params = func_get_args(); foreach($params as $param){ $path = SITE_ROOT . "/assets/js/" . $param; echo "<script language='JavaScript' src='{$path}' type='text/JavaScript'></script> "; } } function currentUser($attr = null) { if (isset($_SESSION['user'])) return isset($attr) ? $_SESSION['user'][$attr] : $_SESSION['user']; else return false; } function autenticated(){ if(!(isset($_SESSION['user']))) { flash('error', 'Você deve estar logado para acessar está página!'); redirect_to('/login/log_in'); exit; } } function notAutenticated(){ if(isset($_SESSION['user'])) { flash('warning', 'Você deve estar deslogado para acessar está página!'); redirect_to(back()); exit; } } ?><file_sep>/new/app/models/file_search.php <?php class FileSearch { private $dir; public function __construct($dir) { $this->dir = $dir; } public function retrieve($file){ if (file_exists($this->dir . '/' . $file)) { return array("name" => $file, "body" => file_get_contents($this->dir . '/' . $file)); } } public function find($search) { $files = array(); foreach(glob($this->dir.'/*') as $file) { $content = file_get_contents($file); if (preg_match("/($search)/i", $content) || preg_match("/($search)/i", $file)) { $files[] = array('name' => $this->getFilename($file),'content' => $content); } } return $files; } public function findAll() { $files = array(); $files_path = glob($this->dir.'/*'); foreach($files_path as $file) { $content = file_get_contents($file); $files[] = array('name' => $this->getFilename($file),'content' => $content); } return $files; } private function getFilename($name){ $names = explode('/',$name); return $names[sizeof($names)-1]; } } ?> <file_sep>/new/app/login/sign_out.php <?php autenticated(); unset($_SESSION['user']); flash('info', 'Logout realizado com sucesso!'); redirect_to('/'); //header('location:' . SITE_ROOT); ?> <file_sep>/new/app/files/_delete.php <?php unlink(APP_ROOT . 'app/files/txt' . '/' . $_GET['id']); flash('info', 'Excluído com sucesso!'); redirect_to('/files/'); ?><file_sep>/new/app/layout/_menu.php <div class="navbar navbar-inverse navbar-static-top"> <div class="navbar-inner"> <div class="container"> <div id='logged-info' class='brand'> <?php if (isset($_SESSION['user']['name'])) { ?> Olá <?= $_SESSION['user']['name'] ?> <?= link_to('/login/sign_out', 'Logout'); ?> <?php } else { ?> <?= link_to('/login/log_in', 'Login'); ?> <?php } ?> </div> <a class="brand" href="/new/">GHack</a> <div class="menu-padd"> <ul class="nav"> <li> <a href="/new/shop/"> Loja </a> </li> <li> <a href="/new/shop/cart"> <i class="icon-shopping-cart icon-white"></i> <?= quantity() ?> </a> </li> <li> <a href="/new/contact/new"> Contato </a> </li> <li> <a href="/new/files/"> Arquivos </a> </li> </ul> </div> </div> </div> </div><file_sep>/new/app/contact/_form.php <?php if (!isset($contact)){ $contact = new Contact(); } ?> <div class="span10"> <section> <header class='page-header'> <h1>Formulário de Contato</h1> </header> </section> <form id='new_contact' action='receive' method='POST' class='form-vertical' novalidate> <div class="control-group <?= isset($contact->errors()['name']) ? 'error' :'' ?> " > <label class='control-label' for='contact_name'>Nome *</label> <div class="controls"> <input type='text' id='contact_name' name='contact[name]' placeholder='Seu nome' value='<?= $contact->getName() ?>' /> <span class='help-inline'><?= @$contact->errors()['name']?></span> </div> </div> <div class="control-group <?= isset($contact->errors()['email']) ? 'error' :'' ?>" > <label class='control-label' for='contact_email'>Email *</label> <div class="controls"> <input type='text' id='contact_email' name='contact[email]' placeholder='Seu email' value='<?= $contact->getEmail() ?>' /> <span class='help-inline'><?= @$contact->errors()['email']?></span> </div> </div> <div class="control-group <?= isset($contact->errors()['body']) ? 'error' :'' ?>" > <label class='control-label' for='contact_body'>Comentário *</label> <div class="controls"> <textarea id='contact_body' name='contact[body]' placeholder='Digite seu comentário'><?= $contact->getBody() ?></textarea> <span class='help-inline'><?= @$contact->errors()['name']?></span> </div> </div> <input type='submit' value='Enviar' class='btn btn-primary'/> </form> </div> <file_sep>/new/app/models/file.php <?php class File { private $name; private $body; private $dir = 'txt/'; private $errors = array(); public function __construct($data = array()){ foreach($data as $key => $value){ $method = "set{$key}"; $this->$method($value); } } public function setName($name){ if (Validations::isText($name) || empty($name)){ $this->name = $name; }else{ $this->name = $name . '.txt'; } } public function setBody($body){ $this->body = $body; } public function getName(){ return $this->name; } public function getBody(){ return $this->body; } public function isValid(){ Validations::uniqueFile($this->dir . $this->name, $this->errors['name']); Validations::notEmpty($this->name, $this->errors['name']); Validations::notEmpty($this->body, $this->errors['body']); $this->errors = array_filter($this->errors, "Validations::notEmpty"); return empty($this->errors); } public function isRewriteAble(){ Validations::notEmpty($this->name, $this->errors['name']); Validations::notEmpty($this->body, $this->errors['body']); $this->errors = array_filter($this->errors, "Validations::notEmpty"); return empty($this->errors); } public function errors(){ return $this->errors; } public function save(){ if ($this->isRewriteAble()) { $text = fopen($this->dir . $this->name, 'w+'); fwrite($text, $this->body); fclose($text); return true; } return false; } public function create(){ if ($this->isValid()) { $text = fopen($this->dir . $this->name, 'w+'); fwrite($text, $this->body); fclose($text); return true; } return false; } public function delete(){ return unlink($this->dir . $this->name); } public static function findByName($name, $dir){ $path = $dir . '/' . $name; if(file_exists($path)) { $file = new File(); $file->setName($name); $file->setBody(file_get_contents($path)); return $file; } } } ?><file_sep>/new/app/files/_save.php <?php $file = File::findByName($_POST['file']['name'], 'txt/'); if ($file != null){ $file->setBody($_POST['file']['body']); $file->save(); } flash('info', 'Editado!'); redirect_to('/files/'); ?><file_sep>/new/app/layout/_message.php <div class="span9"> <?php foreach(flash() as $key => $value){?> <div class='alert alert-<?= @$key ?>'> <a class='close' data-dismiss='alert'>x</a> <?= @$value ?> </div> <?php } ?><file_sep>/new/app/files/_create.php <?php $file = new File($_POST['file']); $files = array("name" => $_POST['file']['name'],"body" => $_POST['file']['body']); if ($file->create()) { flash('success', 'Arquivo criado!'); redirect_to('/files/'); } else{ flash('error', 'Existe dados incorretos no seu formulário!'); require ('new.php'); } ?><file_sep>/new/app/shop/_products.php <?php $products = array( array("name" => "HD externo IOMEGA 1TB", "img" => SITE_ROOT . "/assets/img/iomega.jpg", "price" => 300.00), array("name" => "Pendrive Kingston 101 16GB", "img" => SITE_ROOT . "/assets/img/kingston 101.jpg", "price" => 30.00), array("name" => "Pendrive Cruzer Blade 16GB", "img" => SITE_ROOT . "/assets/img/sandisk.jpg", "price" => 19.00), array("name" => "Pendrive Kingston 108 16GB", "img" => SITE_ROOT . "/assets/img/kingston 108.jpg", "price" => 35.00), array("name" => "HD externo Prestige 1TB", "img" => SITE_ROOT . "/assets/img/prestige.jpg", "price" => 700.00), array("name" => "Mouse DeathAdder", "img" => SITE_ROOT . "/assets/img/razer death adder.jpg", "price" => 230.00), array("name" => "Razer Epic", "img" => SITE_ROOT . "/assets/img/razer epic.jpg", "price" => 600.00), array("name" => "Razer Fone Mass Effect", "img" => SITE_ROOT . "/assets/img/razer fone n7.jpg", "price" => 430.00), array("name" => "<NAME>", "img" => SITE_ROOT . "/assets/img/razer naga molten.jpg", "price" => 400.00), );<file_sep>/new/app/files/search.php <?php $file_search = new FileSearch(APP_ROOT . 'app/files/txt'); $recent_searchs = new RecentSearchs('search'); if (!$_GET['search'] == '') { $files = array(); $_GET['search'] = trim($_GET['search']); $files = $file_search->find($_GET['search']); $recent_searchs->add($_GET['search']); } else { $files = $file_search->findAll(); flash('warning', 'Não foi encontrado!'); } ?> <?php require('_header.php'); ?> <div class="span10"> <section> <header class='page-header'> <h1>Lista de Arquivos</h1> </header> </section> <div class='span5'> <form id="files-search-form" class='form-search' action='search' method='GET'> <div class="input-prepend input-append"> <a class="btn btn-inverse" href="new">Criar novo arquivo</a> <input type='text' name='search' value='<?= @$_GET['search']?>' class='span3 '> <button type='submit' class='btn'>Procurar</button> </div> </form> <span>Buscas recentes:</span> <ul class='breadcrumb'> <?php foreach($recent_searchs->getRecents() as $recent){ ?> <li> <span class="divider"></span> <a href="search?search=<?= $recent; ?>"><?= $recent; ?></a> <span class="divider"></span> </li> <?php } ?> </ul> </div> <table class='table table-bordered table-striped'> <thead> <tr> <th>Arquivo</th> <th>Conteúdo</th> <th>Opções</th> </tr> </thead> <tbody> <?php foreach($files as $file) {?> <tr> <td><?= $file['name']; ?></td> <td><?= $file['content']; ?></td> <td> <a href="_edit?id=<?= $file['name'] ?>" class="btn btn-info">Editar</a> <a href="_delete?id=<?= $file['name'] ?>" class="btn btn-danger" data-confirm="Deseja excluir o arquivo?" >Excluir</a> </td> </tr> <?php } ?> </tbody> </table> </div> <?php require('_footer.php'); ?><file_sep>/new/app/shop/_load.php <?php require('_products.php'); ?> <div class="span10"> <ul class="thumbnails"> <?php foreach($products as $key => $value){ ?> <li class="spname"> <div class="thumbnail"> <img src="<?= $value['img'] ?>" alt="<?= $value['name'] ?>" class="product"> <div class="caption"> <h3><?= $value['name'] ?></h3> <p>R$ <?= $value['price'] ?></p> <p> <form class="form-search" action="_buy" method="POST"> <input type="hidden" name="id" value="<?= $key ?>" /> <input type="number" min="1" name="amount" class="input-small" value="1" placeholder="Quantidade" /> <input type="submit" class="btn btn-primary" value="Comprar!" /> </form> <a class="btn" href="_add?id=<?= $key ?>">Adicionar ao carrinho</a> </p> </div> </div> </li> <?php } ?> </ul> </div><file_sep>/new/app/models/recent_searchs.php <?php class RecentSearchs { private $cookieName; private $limit; private $recents = array(); public function __construct($cookieName, $limit = 5) { $this->cookieName = $cookieName; $this->limit = $limit; $this->recents = $this->searchs(); } public function add($value) { $value = str_replace(';','', trim($value)); if (!empty($value) && !in_array($value, $this->recents)) { if (sizeof($this->recents) >= $this->limit){ array_pop($this->recents); } array_unshift($this->recents, $value); setCookie($this->cookieName, implode(';', $this->recents), time()+24*60*60); } } private function searchs() { if (isset( $_COOKIE[$this->cookieName] )) return explode(';', $_COOKIE[$this->cookieName]); else return array(); } public function getRecents(){ return $this->recents; } } ?> <file_sep>/new/app/layout/_header.php <!DOCTYPE HTML> <html lang="pt-BR"> <head> <meta charset="UTF-8"> <title>Loja GHack</title> <link rel="shortcut icon" type="image/x-ico" href="<?= SITE_ROOT . IMAGE_PATH . 'shop_cart.ico' ?>"> <?php stylesheet_include_tag('bootstrap.min.css', 'bootstrap-responsive.min.css', 'application.css'); ?> </head> <body> <?php require '_menu.php'; require('_subhead.php'); require '_message.php'; ?><file_sep>/new/app/login/sign_in.php <?php notAutenticated(); $email = $_POST['email']; $password = $_POST['<PASSWORD>']; $email_db = '<EMAIL>'; $password_db = '<PASSWORD>'; if ($email_db === $email && $password_db == $password) { $_SESSION['user']['name'] = 'Hack'; flash('success', 'Login realizado com sucesso!'); redirect_to('/'); }else{ flash('error', 'Dados incorretos!'); redirect_to('/login/log_in'); } ?><file_sep>/new/lib/validations.php <?php function redirect_if_not_a_post() { $location = '/'; $params = func_get_args(); $last_element = $params[sizeof($params)-1]; if (strpos($last_element, 'location:') !== false) $location = array_pop($params); foreach($params as $param){ if (!isset($_POST[$param])){ header($location); exit(); } } } function notEmpty($value, $key = null, &$errors = null){ if (empty($value)){ if ($key !== null && $errors !== null) { $msg = 'não deve ser vazio'; $errors[$key] = $msg; } return false; } return true; } function validEmail($email, $key = null, $errors = null){ $pattern = '/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+/'; if (preg_match($pattern, $email)) return true; if ($key !== null && $errors !== null) $errors[$key] = 'não é válido'; return false; } class Validations { public static function uniqueFile($path, &$msg) { if (!file_exists($path)) { unset($msg); return true; } $msg = 'já existe um arquivo com esse nome'; return false; } public static function isText($name){ $pattern = '/^.+\.txt$/'; if (preg_match($pattern, $name)) { return true; } return false; } public static function notEmpty($value, &$msg = ''){ if (empty($value)){ $msg = 'não deve ser vazio'; return false; } unset($msg); return true; } public static function email($email, &$msg = ''){ $pattern = '/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+/'; if (preg_match($pattern, $email)) { unset($msg); return true; } $msg = 'não é valido'; return false; } } ?><file_sep>/new/app/contact/new.php <?php require('_header.php'); ?> <?php require('_form.php'); ?> <?php require('_footer.php'); ?><file_sep>/new/app/layout/_footer.php </div> </div> <?php javascript_include_tag('jquery-1.9.1.min.js', 'bootstrap.min.js', 'bootbox.min.js', 'application.js'); ?> </body> </html> <file_sep>/new/lib/cookie.php <?php function quantity(){ return sizeof(searchCookie()) / 2; } function searchCookie() { if (isset( $_COOKIE['cart'] )){ return explode(';', $_COOKIE['cart']); }else{ return array(); } } function split_cart() { $cookies = searchCookie(); $cart = array(); if(!empty($cookies)){ for($i = 0; $i < sizeof($cookies); $i++){ if($i % 2 == 0){ $cart['product'][] = $cookies[$i]; }else{ $cart['amount'][] = $cookies[$i]; } } } return $cart; } function attach_cart($cart){ $cookie = array(); foreach ($cart['product'] as $key => $value) { $cookie[] = $cart['product'][$key]; $cookie[] = $cart['amount'][$key]; } return implode(';', $cookie); } function add($id, $amount) { $cart = split_cart(); if(!empty($cart)){ if(sizeof($cart['product']) == 1) $pos = 0; else $pos = array_search($id, $cart['product']); if($id == $cart['product'][$pos]){ $cart['amount'][$pos] = $amount; }else{ $cart['amount'][] = $amount; $cart['product'][] = $id; } $cookie = attach_cart($cart); }else{ $cookie = implode(';', array($id, $amount)); } setCookie('cart', $cookie, time()+3600*24); } function del_cookie($cookie){ setcookie($cookie); } ?><file_sep>/new/app/shop/_add.php <?php require('_cart.php'); $cart['id'] = $_GET['id']; $cart['amount'] = 1; add($cart['id'], $cart['amount']); flash('success', 'Adicionado com sucesso!'); redirect_to(back()); ?><file_sep>/new/config/application.php <?php define('APP_NAME', 'new' ); define('APP_ROOT', $_SERVER['DOCUMENT_ROOT'] . '/' . APP_NAME . '/'); define('SITE_ROOT', '/new/app' ); define('IMAGE_PATH', '/assets/img/'); /* Adicionar pastas defaults para inclução de arquivos com as funções require e include */ set_include_path(get_include_path() . PATH_SEPARATOR . APP_ROOT); set_include_path(get_include_path() . PATH_SEPARATOR . APP_ROOT . 'config/'); set_include_path(get_include_path() . PATH_SEPARATOR . APP_ROOT . 'app/'); set_include_path(get_include_path() . PATH_SEPARATOR . APP_ROOT . 'app/layout/'); set_include_path(get_include_path() . PATH_SEPARATOR . APP_ROOT . 'lib/'); session_start(); date_default_timezone_set('America/Sao_Paulo'); require 'flash_message.php'; require 'utils.php'; require 'cookie.php'; require '_auto_load_class.php'; ?> <file_sep>/new/app/shop/_buy.php <?php autenticated(); if (empty($_POST['amount'])) { flash('info', 'Adicione quantos produtos deseja comprar!'); redirect_to('/shop/'); exit; } $cart['id'] = $_POST['id']; $cart['amount'] = $_POST['amount']; add($cart['id'], $cart['amount']); redirect_to('cart'); ?><file_sep>/new/app/files/new.php <?php require ('_header.php'); $sendTo = '_create'; require ('_form.php'); require ('_footer.php'); ?><file_sep>/new/app/files/_edit.php <?php require ('_header.php'); $file_search = new FileSearch(APP_ROOT . 'app/files/txt'); $files = $file_search->retrieve($_GET['id']); $disabled = 'disabled = "disabled"'; $sendTo = '_save'; require ('_form.php'); require ('_footer.php'); ?><file_sep>/new/app/shop/finish.php <?php setcookie('cart', "", time() - 3600); flash('success', 'Compra Efetuada!'); redirect_to('/'); ?>
02574d0e044bfa654eede2861bbca323c219cb7f
[ "PHP" ]
35
PHP
gfhack/another-php
4d43cb71d233cddd5e85675565e29626158edc22
3d8e45b25cf231e9b35cc52a440aac3062a5aa87
refs/heads/master
<file_sep>// // ViewController.swift // Todo // // Created by <NAME> on 3/9/17. // Copyright © 2017 ustwo. All rights reserved. // import UIKit import SnapKit struct TodoViewModel { private let datasource = ["Walk dog", "Take out the trash", "Call Mom"] func transformedDatasource() -> [String] { var temp = [String]() for item in datasource { temp.append(item + ":") } return temp } } class ViewController: UIViewController { //MARK: Property private let tableView = UITableView(frame: .zero) fileprivate let identifier = "Cell" let viewModel = TodoViewModel() fileprivate lazy var datasource: [String] = { return self.viewModel.transformedDatasource() }() //MARK: Method override func viewDidLoad() { super.viewDidLoad() setup() } private func setup() { setupTableView() setupDatabase() setupNetworking() } private func setupTableView() { //frame layout // tableView.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height) //good to set background on views to identify // tableView.backgroundColor = .purple view.addSubview(tableView) tableView.register(UITableViewCell.self, forCellReuseIdentifier: identifier) tableView.snp.makeConstraints { make in make.edges.equalTo(view) } tableView.dataSource = self } private func setupNetworking() { //fill in } private func setupDatabase() { //fill in } } //MARK: UITableViewDataSource extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) cell.textLabel?.text = datasource[indexPath.row] return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return datasource.count } } <file_sep>// // XTests.swift // Todo // // Created by <NAME> on 3/9/17. // Copyright © 2017 ustwo. All rights reserved. // import XCTest @testable import Todo //DONT FORGET class XTests: XCTestCase { func testThatSomething() { } }
3832c25ece16ee4add680dd612926677bdda577d
[ "Swift" ]
2
Swift
alonecuzzo/Todo
acd6aaf265965cf1109f243832fb103ee72606d9
f91fde00e9e38cd31aad09a4a3f2a0ee46a378ce
refs/heads/master
<repo_name>candy9410/FireBaseChat<file_sep>/app/src/main/java/com/lsh2017/firebasechat/RecyclerAdapter.java package com.lsh2017.firebasechat; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; /** * Created by 이소희 on 2017-09-22. */ public class RecyclerAdapter extends RecyclerView.Adapter { Context context; ArrayList<ChatData> items; @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view= LayoutInflater.from(context).inflate(R.layout.recycler_item,parent,false); Holder holder=new Holder(view); return holder; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { Holder holder1=(Holder) holder; holder1.userName.setText(items.get(position).getUserName()); holder1.message.setText((items.get(position).getMessage())); holder1.date.setText(items.get(position).getDate()); } @Override public int getItemCount() { return items.size(); } class Holder extends RecyclerView.ViewHolder{ TextView userName; TextView message; TextView date; public Holder(View itemView) { super(itemView); userName=(TextView) itemView.findViewById(R.id.text_name); message=(TextView) itemView.findViewById(R.id.text_content); date=(TextView)itemView.findViewById(R.id.text_date); } } } <file_sep>/app/src/main/java/com/lsh2017/firebasechat/MainActivity.java package com.lsh2017.firebasechat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.ArrayList; import java.util.Random; public class MainActivity extends AppCompatActivity { EditText editText; Button btnSend; RecyclerView recyclerView; ArrayList<ChatData> items; RecyclerAdapter adapter; String userName; String date=""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText=(EditText)findViewById(R.id.edit_text); btnSend=(Button)findViewById(R.id.btn_send); items=new ArrayList<>(); recyclerView=(RecyclerView)findViewById(R.id.recycler_view); recyclerView.setAdapter(adapter); FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance(); final DatabaseReference databaseReference = firebaseDatabase.getReference(); userName = "user" + new Random().nextInt(10000); btnSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ChatData chatData = new ChatData(userName, editText.getText().toString(),date); // 유저 이름과 메세지로 chatData 만들기 databaseReference.child("message").push().setValue(chatData); // 기본 database 하위 message라는 child에 chatData를 list로 만들기 editText.setText(""); } }); } }
7905b280bff49b8dfaf0d8ae64df12e47653d58b
[ "Java" ]
2
Java
candy9410/FireBaseChat
8b614c775da62f97c6f58296832a2a6c366cc1a0
54d668fca09d07f6eadcc991b0fa6af4676a95f3
refs/heads/master
<repo_name>alhusseinsamy/My-Portfolio<file_sep>/app/models/Image.js var mongoose = require('mongoose'); var imageSchema = mongoose.Schema({ title:{ type:String, required:false, unique:false }, img: { data: Buffer, contentType: String }, imgPath: String, username:{ type:String, required:true, unique:false } }) var Image = mongoose.model("image", imageSchema); module.exports = Image; module.exports.createImage = function(newImage, callback){ newImage.save(callback); } module.exports.findImageByUsername = function(username, callback){ var query = {username: username}; Image.find(query, callback); } <file_sep>/app/models/test.js var mongoose = require('mongoose'); // example schema var schema = mongoose.Schema({ img: { data: Buffer, contentType: String } }); // our model var A = mongoose.model('A', schema); module.exports = A;<file_sep>/app/models/Project.js var mongoose = require('mongoose'); var projectSchema = mongoose.Schema({ title:{ type:String, required:false, unique:false }, URL:String, username:{ type:String, required:false, unique:false } }) var Project = mongoose.model("project", projectSchema); module.exports = Project; module.exports.createProject1 = function(newProject, callback){ newProject.save(callback); } module.exports.getProjectByUsername = function(username, callback){ var query = {username: username}; Project.find(query, callback); } //module.exports.createPortfolio = function(){ //}<file_sep>/app/models/Portfolio.js var mongoose = require('mongoose'); var portfolioSchema = mongoose.Schema({ username:{ type:String, required:true, unique:false }, name:{ type:String, required:true, unique:false }, img: { data: Buffer, contentType: String }, imgPath: String }) var Portfolio = mongoose.model("portfolio", portfolioSchema); module.exports = Portfolio; module.exports.createPortfolio = function(newPortfolio, callback){ newPortfolio.save(callback); } module.exports.findPortfolioByUsername = function(username, callback){ var query = {username: username}; Portfolio.find(query, callback); } module.exports.findPortfolioByUsername1 = function(projects, callback){ for(var i =0; i<projects.length; i++){ var query = {username: projects[i].username}; Portfolio.findOne(query, callback); } } /*module.exports.getAllPortfolios = function(req, res){ Portfolio.find(function(err, portfolios){ if(err) res.send(err.message); else res.render('loggedin', {projects, 'success_msg': req.flash('success') }); //console.log(projects); //console.log(req.body); }) }, */
74304f1c78867dedb75ff2f6b4eb3894a520f236
[ "JavaScript" ]
4
JavaScript
alhusseinsamy/My-Portfolio
00b74d62e8c5c99b819adf0277519098779b3322
97c5b48aaea61086d792662eb90510eadf693976
refs/heads/master
<file_sep>/* Copyright (c) 2016 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef GLTF_BASTARD_H #define GLTF_BASTARD_H #include <string> #include <vector> #include <unordered_map> namespace glTFBastard { struct Camera { enum Type { TYPE_PERSPECTIVE, TYPE_ORTHOGRAPHIC }; struct Perspective { float aspectRatio; float yfov; float zfar; float znear; }; struct Orthographic { float xmag; float ymag; float zfar; float znear; }; union Data { Perspective perspective; Orthographic orthographic; }; Type type; Data typeData; Camera() : type(TYPE_PERSPECTIVE) { memset(static_cast<void*>(&typeData), 0, sizeof(typeData)); } }; struct Buffer { enum Type { TYPE_ARRAY_BUFFER, TYPE_TEXT }; long long byteLength; Type type; std::string uri; Buffer() : type(TYPE_ARRAY_BUFFER), byteLength(0) { } }; struct BufferView { enum Target { TARGET_OTHER = 0, TARGET_ARRAY_BUFFER = 34962, TARGET_ELEMENT_ARRAY_BUFFER = 34963 }; std::string buffer; long long byteLength; long long byteOffset; Target target; BufferView() : byteLength(0), byteOffset(0), target(TARGET_OTHER) { } }; struct Accessor { enum ComponentType { COMPONENT_TYPE_BYTE = 5120, COMPONENT_TYPE_UNSIGNED_BYTE = 5121, COMPONENT_TYPE_SHORT = 5122, COMPONENT_TYPE_UNSIGNED_SHORT = 5123, COMPONENT_TYPE_FLOAT = 5126 }; enum Type { TYPE_SCALAR, TYPE_VEC2, TYPE_VEC3, TYPE_VEC4, TYPE_MAT2, TYPE_MAT3, TYPE_MAT4 }; std::string bufferView; long long byteOffset; long long byteStride; long long count; ComponentType componentType; Type type; std::vector<float> min; std::vector<float> max; Accessor() : byteOffset(0), byteStride(0), count(0), componentType(COMPONENT_TYPE_BYTE), type(TYPE_SCALAR) { } }; struct Mesh { struct Primitive { enum Mode { TYPE_POINTS = 0, TYPE_LINES = 1, TYPE_LINE_LOOP = 2, TYPE_LINE_STRIP = 3, TYPE_TRIANGLES = 4, TYPE_TRIANGLE_STRIP = 5, TYPE_TRIANGLE_FAN = 6 }; std::unordered_map<std::string, std::string> attributes; std::string indices; std::string material; Mode mode; Primitive(): mode(TYPE_TRIANGLES) { } }; std::vector<std::unique_ptr<Primitive>> primitives; }; struct Shader { enum Type { TYPE_FRAGMENT_SHADER = 35632, TYPE_VERTEX_SHADER = 35633 }; Type type; std::string uri; Shader() : type(TYPE_FRAGMENT_SHADER) { } }; struct Program { std::vector<std::string> attributes; std::string fragmentShader; std::string vertexShader; }; struct ParameterValue { enum Type { TYPE_UNKNOWN, TYPE_NUMBER, TYPE_BOOLEAN, TYPE_STRING, TYPE_NUMBER_ARRAY, TYPE_BOOLEAN_ARRAY, TYPE_STRING_ARRAY, }; Type type; std::vector<float> numberData; std::vector<bool> booleanData; std::vector<std::string> stringData; ParameterValue() : type(TYPE_UNKNOWN) { } }; struct Technique { struct Parameter { enum Type { TYPE_BYTE = 5120, TYPE_UNSIGNED_BYTE = 5121, TYPE_SHORT = 5122, TYPE_UNSIGNED_SHORT = 5123, TYPE_INT = 5124, TYPE_UNSIGNED_INT = 5125, TYPE_FLOAT = 5126, TYPE_FLOAT_VEC2 = 35664, TYPE_FLOAT_VEC3 = 35665, TYPE_FLOAT_VEC4 = 35666, TYPE_INT_VEC2 = 35667, TYPE_INT_VEC3 = 35668, TYPE_INT_VEC4 = 35669, TYPE_BOOL = 35670, TYPE_BOOL_VEC2 = 35671, TYPE_BOOL_VEC3 = 35672, TYPE_BOOL_VEC4 = 35673, TYPE_FLOAT_MAT2 = 35674, TYPE_FLOAT_MAT3 = 35675, TYPE_FLOAT_MAT4 = 35676, TYPE_SAMPLER_2D = 35678 }; Type type; std::string semantic; std::string node; std::unique_ptr<ParameterValue> value; Parameter() : type(TYPE_BYTE) { } }; std::unordered_map<std::string, std::unique_ptr<Parameter>> parameters; std::unordered_map<std::string, std::string> attributes; std::unordered_map<std::string, std::string> uniforms; std::string program; // TODO: States. }; struct Sampler { enum FilterType { FILTER_TYPE_NEAREST = 9728, FILTER_TYPE_LINEAR = 9729, FILTER_TYPE_NEAREST_MINMAP_NEAREST = 9984, FILTER_TYPE_LINEAR_MINMAP_NEAREST = 9985, FILTER_TYPE_NEAREST_MINMAP_LINEAR = 9986, FILTER_TYPE_LINEAR_MINMAP_LINEAR = 9987 }; enum WrapType { WRAP_TYPE_CLAMP_TO_EDGE = 33071, WRAP_TYPE_MIRRORED_REPEAT = 33648, WRAP_TYPE_REPEAT = 10497 }; FilterType magFilter; FilterType minFilter; WrapType wrapS; WrapType wrapT; Sampler() : magFilter(FILTER_TYPE_LINEAR), minFilter(FILTER_TYPE_NEAREST_MINMAP_LINEAR), wrapS(WRAP_TYPE_REPEAT), wrapT(WRAP_TYPE_REPEAT) { } }; struct Material { std::string technique; std::unordered_map<std::string, std::unique_ptr<ParameterValue>> values; }; struct Image { std::string uri; }; struct Texture { enum Format { FORMAT_ALPHA = 6406, FORMAT_RGB = 6407, FORMAT_RGBA = 6408, FORMAT_LUMINANCE = 6409, FORMAT_LUMINANCE_ALPHA = 6410 }; enum Type { TYPE_UNSIGNED_BYTE = 5121, TYPE_UNSIGNED_SHORT_5_6_5 = 33635, TYPE_UNSIGNED_SHORT_4_4_4_4 = 32819, TYPE_UNSIGNED_SHORT_5_5_5_1 = 32820 }; enum Target { TARGET_TEXTURE_2D = 3553 }; Format format; Format internalFormat; std::string sampler; std::string source; Target target; Type type; Texture() : type(TYPE_UNSIGNED_BYTE), target(TARGET_TEXTURE_2D), internalFormat(FORMAT_RGBA), format(FORMAT_RGBA) { }; }; struct Animation { struct Channel { struct Target { std::string id; std::string path; }; std::string sampler; Target target; }; struct Sampler { enum Interpolation { INTERPOLATION_LINEAR }; Interpolation interpolation; std::string input; std::string output; Sampler() : interpolation(INTERPOLATION_LINEAR) { } }; std::vector<std::unique_ptr<Channel>> channels; std::unordered_map<std::string, std::string> parameters; std::unordered_map<std::string, std::unique_ptr<Sampler>> samplers; }; struct Skin { float bindShapeMatrix[16]; std::string inverseBindMatrices; std::vector<std::string> jointNames; }; struct Node { enum TransformType { TRANSFORM_TYPE_MATRIX, TRANSFORM_TYPE_COMPOSITE }; struct Composite { float rotation[4]; float scale[3]; float translation[3]; }; union Transform { Composite composite; float matrix[16]; }; std::string camera; std::string skin; std::vector<std::string> children; std::vector<std::string> skeletons; std::vector<std::string> meshes; std::string jointName; Transform transform; TransformType transformType; Node() : transformType(TRANSFORM_TYPE_MATRIX) { memset(static_cast<void*>(&transform), 0, sizeof(transform)); }; }; struct Scene { std::vector<std::string> nodes; }; struct glTF { std::unordered_map<std::string, std::unique_ptr<Camera>> cameras; std::unordered_map<std::string, std::unique_ptr<Buffer>> buffers; std::unordered_map<std::string, std::unique_ptr<BufferView>> bufferViews; std::unordered_map<std::string, std::unique_ptr<Accessor>> accessors; std::unordered_map<std::string, std::unique_ptr<Mesh>> meshes; std::unordered_map<std::string, std::unique_ptr<Shader>> shaders; std::unordered_map<std::string, std::unique_ptr<Program>> programs; std::unordered_map<std::string, std::unique_ptr<Material>> materials; std::unordered_map<std::string, std::unique_ptr<Technique>> techniques; std::unordered_map<std::string, std::unique_ptr<Sampler>> samplers; std::unordered_map<std::string, std::unique_ptr<Texture>> textures; std::unordered_map<std::string, std::unique_ptr<Image>> images; std::unordered_map<std::string, std::unique_ptr<Animation>> animations; std::unordered_map<std::string, std::unique_ptr<Skin>> skins; std::unordered_map<std::string, std::unique_ptr<Node>> nodes; std::unordered_map<std::string, std::unique_ptr<Scene>> scenes; std::string scene; }; std::unique_ptr<const glTF> Parse(const char* jsonString, size_t size, std::string& outErr); } #endif<file_sep># glTFBastard A simple C++ [glTF](https://github.com/KhronosGroup/glTF) document parser. It takes in a string representing the json document and returns a glTF document structure. * MIT licensed. * Requires C++11 and STL. * Uses [json-parser](https://github.com/udp/json-parser). * I currently use it to load glTF scenes on Android and Windows. ![AndroidDemo](https://github.com/rcashie/glTFBastard/blob/master/images/Android.png) ![WindowsDemo](https://github.com/rcashie/glTFBastard/blob/master/images/Windows.png) ## Example ````c++ std::string source = ReadEntireFile("/Duck/glTF/Duck.gltf"); std::string error; std::unique_ptr<const glTFBastard::glTF> doc = glTFBastard::Parse(source.c_str(), source.size(), error); if (!doc) { PrintError("glTF load error: %s", error.c_str()); abort(); } ```` ## Features still to be implemented. * Asset parsing. * Technique state parsing. <file_sep>/* Copyright (c) 2016 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <memory> #include <sstream> #include "json-parser/json.h" #include "glTFBastard.h" namespace glTFBastard { // Declaration of a templated function responsible for parsing a json element into it's respective type. template<typename T> bool ParseElement( const json_value& jsonElement, const std::string& elementName, T* out, std::string& outErr); // Parses an array of elements of the specified type. template<typename T> bool ParseElement( const json_value& jsonElement, const std::string& elementName, std::vector<T>* outArray, std::string& outErr) { if (jsonElement.type != json_array) { outErr = "Could not parse element '" + elementName + "' as an array."; return false; } int count = jsonElement.u.array.length; outArray->clear(); outArray->reserve(count); auto elements = jsonElement.u.array.values; for (int i = 0; i < count; ++i) { std::stringstream ss; ss << elementName << "[" << i << "]"; T result; if (!ParseElement(*elements[i], ss.str(), &result, outErr)) { return false; } outArray->push_back(std::move(result)); } return true; } // Parses child elements of a json element that are of the same type. template<typename T> bool ParseElement( const json_value& jsonElement, const std::string& elementName, std::unordered_map<std::string, T>* outMap, std::string& outErr) { if (jsonElement.type != json_object) { outErr = "Could not parse children of element '" + elementName + "'. It is not an object."; return false; } int childCount = jsonElement.u.object.length; outMap->clear(); outMap->reserve(childCount); auto children = jsonElement.u.object.values; for (int i = 0; i < childCount; ++i) { auto child = children[i]; T result; std::string childName(child.name, child.name_length); if (!ParseElement(*child.value, elementName + "." + childName, &result, outErr)) { return false; } outMap->insert( std::pair<std::string, T>(childName, std::move(result))); } return true; } // Verifies that the element exists before parsing it into it's respective type. template<typename T> inline bool ParseRequiredElement( const json_value& jsonElement, const std::string& elementName, T* out, std::string& outErr) { if (jsonElement.type == json_none) { outErr = "The required element '" + elementName + "' does not exist."; return false; } return ParseElement(jsonElement, elementName, out, outErr); } // Parses an element into it's respective type only if it exists; returns true if the element does not exist. template<typename T> inline bool ParseOptionalElement( const json_value& jsonElement, const std::string& elementName, T* out, std::string& outErr) { // Just return true if it does exist. if (jsonElement.type == json_none) { return true; } return ParseElement(jsonElement, elementName, out, outErr); } // Parses an element only if it exists; returns true if the element does not exist. // It then maps the parsed result to another value using the specified map. // Handy for validating input against acceptable values. template<typename T, typename K> bool ParseAndMapOptionalElement( const json_value& jsonElement, const std::string& elementName, const std::unordered_map<K, T>& map, T* out, std::string& outErr) { // Just return true if it does exist. if (jsonElement.type == json_none) { return true; } K elementValue; if (!ParseElement(jsonElement, elementName, &elementValue, outErr)) { return false; } auto itr = map.find(elementValue); if (itr == map.end()) { std::stringstream ss; ss << "Unexpected value '" << elementValue << "' for element '" << elementName << "'."; outErr = ss.str(); return false; } *out = itr->second; return true; } // Verifies that the element exists before parsing an element. // It then maps the parsed result to another value using the specified map. // Handy for validating input against acceptable values. template<typename T, typename K> bool ParseAndMapRequiredElement( const json_value& jsonElement, const std::string& elementName, const std::unordered_map<K, T>& map, T* out, std::string& outErr) { K elementValue; if (!ParseRequiredElement(jsonElement, elementName, &elementValue, outErr)) { return false; } auto itr = map.find(elementValue); if (itr == map.end()) { std::stringstream ss; ss << "Unexpected value '" << elementValue << "' for element '" << elementName << "'."; outErr = ss.str(); return false; } *out = itr->second; return true; } // Parses a fixed sized array of elements of the specified type. template<typename T> bool ParseFixedSizeArrayElement( const json_value& jsonElement, const std::string& elementName, size_t outArraySize, T* outArray, std::string& outErr) { if (jsonElement.type != json_array) { outErr = "Could not parse element '" + elementName + "' as an array."; return false; } size_t count = outArraySize < jsonElement.u.array.length ? outArraySize : jsonElement.u.array.length; auto elements = jsonElement.u.array.values; for (int i = 0; i < count; ++i) { std::stringstream ss; ss << elementName << "[" << i << "]"; if (!ParseElement(*elements[i], ss.str(), &outArray[i], outErr)) { return false; } } return true; } // Parses a boolean element. template<> bool ParseElement<bool>( const json_value& jsonElement, const std::string& elementName, bool* out, std::string& outErr) { if (jsonElement.type != json_boolean) { outErr = "Could not parse element '" + elementName + "' as a boolean."; return false; } *out = jsonElement.u.boolean != 0; return true; } // Parses a float element. template<> bool ParseElement<float>( const json_value& jsonElement, const std::string& elementName, float* out, std::string& outErr) { if (jsonElement.type == json_double) { *out = static_cast<float>(jsonElement.u.dbl); } else if (jsonElement.type == json_integer) { *out = static_cast<float>(jsonElement.u.integer); } else { outErr = "Could not parse element '" + elementName + "' as a float."; return false; } return true; } // Parses an integer element. template<> bool ParseElement<long long>( const json_value& jsonElement, const std::string& elementName, long long* out, std::string& outErr) { if (jsonElement.type != json_integer) { outErr = "Could not parse element '" + elementName + "' as an integer."; return false; } *out = jsonElement.u.integer; return true; } // Parses a string element. template<> bool ParseElement<std::string>( const json_value& jsonElement, const std::string& elementName, std::string* out, std::string& outErr) { if (jsonElement.type != json_string) { outErr = "Could not parse element '" + elementName + "' as a string."; return false; } (*out).assign(jsonElement.u.string.ptr, jsonElement.u.string.length); return true; } // Parses a Camera element. template<> bool ParseElement<std::unique_ptr<Camera>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<Camera>* out, std::string& outErr) { static const std::unordered_map<std::string, Camera::Type> typeMap = { { "orthographic", Camera::TYPE_ORTHOGRAPHIC }, { "perspective", Camera::TYPE_PERSPECTIVE } }; std::unique_ptr<Camera> result(new Camera()); if (!ParseAndMapRequiredElement(jsonElement["type"], elementName + ".type", typeMap, &result->type, outErr)) { return false; } if (result->type == Camera::TYPE_ORTHOGRAPHIC) { auto child = jsonElement["orthographic"]; auto orthographic = &result->typeData.orthographic; if (!ParseRequiredElement(child["xmag"], elementName + "orthographic.xmag", &orthographic->xmag, outErr)) { return false; } if (!ParseRequiredElement(child["ymag"], elementName + "orthographic.ymag", &orthographic->ymag, outErr)) { return false; } if (!ParseRequiredElement(child["zfar"], elementName + "orthographic.zfar", &orthographic->zfar, outErr)) { return false; } if (!ParseRequiredElement(child["znear"], elementName + "orthographic.znear", &orthographic->znear, outErr)) { return false; } } else if (result->type == Camera::TYPE_PERSPECTIVE) { auto child = jsonElement["perspective"]; auto perspective = &result->typeData.perspective; if (!ParseRequiredElement(child["yfov"], elementName + "perspective.yfov", &perspective->yfov, outErr)) { return false; } if (!ParseRequiredElement(child["zfar"], elementName + "perspective.zfar", &perspective->zfar, outErr)) { return false; } if (!ParseRequiredElement(child["znear"], elementName + "perspective.znear", &perspective->znear, outErr)) { return false; } if (!ParseOptionalElement(child["aspectRatio"], elementName + "perspective.aspectRatio", &perspective->aspectRatio, outErr)) { return false; } } *out = std::move(result); return true; } // Parses a Buffer element. template<> bool ParseElement<std::unique_ptr<Buffer>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<Buffer>* out, std::string& outErr) { static const std::unordered_map<std::string, Buffer::Type> typeMap = { { "arraybuffer", Buffer::TYPE_ARRAY_BUFFER }, { "text", Buffer::TYPE_TEXT } }; std::unique_ptr<Buffer> result(new Buffer()); if (!ParseRequiredElement(jsonElement["uri"], elementName + ".uri", &result->uri, outErr)) { return false; } if (!ParseOptionalElement(jsonElement["byteLength"], elementName + ".byteLength", &result->byteLength, outErr)) { return false; } if (!ParseAndMapOptionalElement(jsonElement["type"], elementName + ".type", typeMap, &result->type, outErr)) { return false; } *out = std::move(result); return true; } // Parses a BufferView element. template<> bool ParseElement<std::unique_ptr<BufferView>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<BufferView>* out, std::string& outErr) { static const std::unordered_map<long long, BufferView::Target> targetMap = { { 34962, BufferView::TARGET_ARRAY_BUFFER }, { 34963, BufferView::TARGET_ELEMENT_ARRAY_BUFFER } }; std::unique_ptr<BufferView> result(new BufferView()); if (!ParseRequiredElement(jsonElement["buffer"], elementName + ".buffer", &result->buffer, outErr)) { return false; } if (!ParseRequiredElement(jsonElement["byteOffset"], elementName + ".byteOffset", &result->byteOffset, outErr)) { return false; } if (!ParseOptionalElement(jsonElement["byteLength"], elementName + ".byteLength", &result->byteLength, outErr)) { return false; } if (!ParseAndMapOptionalElement( jsonElement["target"], elementName + ".target", targetMap, &result->target, outErr)) { return false; } *out = std::move(result); return true; } // Parses an Accessor element. template<> bool ParseElement<std::unique_ptr<Accessor>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<Accessor>* out, std::string& outErr) { static const std::unordered_map<std::string, Accessor::Type> typeMap = { { "SCALAR", Accessor::TYPE_SCALAR }, { "VEC2", Accessor::TYPE_VEC2 }, { "VEC3", Accessor::TYPE_VEC3 }, { "VEC4", Accessor::TYPE_VEC4 }, { "MAT2", Accessor::TYPE_MAT2 }, { "MAT3", Accessor::TYPE_MAT3 }, { "MAT4", Accessor::TYPE_MAT4 } }; static const std::unordered_map<long long, Accessor::ComponentType> componentTypeMap = { { 5120, Accessor::COMPONENT_TYPE_BYTE }, { 5121, Accessor::COMPONENT_TYPE_UNSIGNED_BYTE }, { 5122, Accessor::COMPONENT_TYPE_SHORT }, { 5123, Accessor::COMPONENT_TYPE_UNSIGNED_SHORT }, { 5126, Accessor::COMPONENT_TYPE_FLOAT } }; std::unique_ptr<Accessor> result(new Accessor()); if (!ParseRequiredElement(jsonElement["bufferView"], elementName + ".bufferView", &result->bufferView, outErr)) { return false; } if (!ParseRequiredElement(jsonElement["byteOffset"], elementName + ".byteOffset", &result->byteOffset, outErr)) { return false; } if (!ParseAndMapRequiredElement( jsonElement["componentType"], elementName + ".componentType", componentTypeMap, &result->componentType, outErr)) { return false; } if (!ParseAndMapRequiredElement(jsonElement["type"], elementName + ".type", typeMap, &result->type, outErr)) { return false; } if (!ParseRequiredElement(jsonElement["count"], elementName + ".count", &result->count, outErr)) { return false; } if (!ParseOptionalElement(jsonElement["byteStride"], elementName + ".byteStride", &result->byteStride, outErr)) { return false; } if (!ParseOptionalElement(jsonElement["min"], elementName + ".min", &result->min, outErr)) { return false; } if (!ParseOptionalElement(jsonElement["max"], elementName + ".max", &result->max, outErr)) { return false; } *out = std::move(result); return true; } // Parses a Mesh::Primitive element. template<> bool ParseElement<std::unique_ptr<Mesh::Primitive>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<Mesh::Primitive>* out, std::string& outErr) { static const std::unordered_map<long long, Mesh::Primitive::Mode> modeMap = { { 0, Mesh::Primitive::TYPE_POINTS }, { 1, Mesh::Primitive::TYPE_LINES }, { 2, Mesh::Primitive::TYPE_LINE_LOOP }, { 3, Mesh::Primitive::TYPE_LINE_STRIP }, { 4, Mesh::Primitive::TYPE_TRIANGLES }, { 5, Mesh::Primitive::TYPE_TRIANGLE_STRIP }, { 6, Mesh::Primitive::TYPE_TRIANGLE_FAN } }; std::unique_ptr<Mesh::Primitive> result(new Mesh::Primitive()); if (!ParseOptionalElement(jsonElement["attributes"], elementName + ".attributes", &result->attributes, outErr)) { return false; } if (!ParseOptionalElement(jsonElement["indices"], elementName + ".indices", &result->indices, outErr)) { return false; } if (!ParseRequiredElement(jsonElement["material"], elementName + ".material", &result->material, outErr)) { return false; } if (!ParseAndMapOptionalElement(jsonElement["mode"], elementName + ".indicies", modeMap, &result->mode, outErr)) { return false; } *out = std::move(result); return true; } // Parses a Mesh element. template<> bool ParseElement<std::unique_ptr<Mesh>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<Mesh>* out, std::string& outErr) { std::unique_ptr<Mesh> result(new Mesh()); if (!ParseOptionalElement(jsonElement["primitives"], elementName + ".primitives", &result->primitives, outErr)) { return false; } *out = std::move(result); return true; } // Parses a Shader element. template<> bool ParseElement<std::unique_ptr<Shader>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<Shader>* out, std::string& outErr) { static const std::unordered_map<long long, Shader::Type> typeMap = { { 35632, Shader::TYPE_FRAGMENT_SHADER }, { 35633, Shader::TYPE_VERTEX_SHADER } }; std::unique_ptr<Shader> result(new Shader()); if (!ParseRequiredElement(jsonElement["uri"], elementName + ".uri", &result->uri, outErr)) { return false; } if (!ParseAndMapRequiredElement(jsonElement["type"], elementName + ".type", typeMap, &result->type, outErr)) { return false; } *out = std::move(result); return true; } // Parses a Program element. template<> bool ParseElement<std::unique_ptr<Program>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<Program>* out, std::string& outErr) { std::unique_ptr<Program> result(new Program()); if (!ParseOptionalElement(jsonElement["attributes"], elementName + ".attributes", &result->attributes, outErr)) { return false; } if (!ParseRequiredElement(jsonElement["fragmentShader"], elementName + ".fragmentShader", &result->fragmentShader, outErr)) { return false; } if (!ParseRequiredElement(jsonElement["vertexShader"], elementName + ".vertexShader", &result->vertexShader, outErr)) { return false; } *out = std::move(result); return true; } // Parses a Parameter Value element. template<> bool ParseElement<std::unique_ptr<ParameterValue>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<ParameterValue>* out, std::string& outErr) { std::unique_ptr<ParameterValue> result(new ParameterValue()); if (jsonElement.type == json_array) { // Assume the type of array based on the first element. json_type valueType = jsonElement.u.array.length ? jsonElement.u.array.values[0]->type : json_none; switch (valueType) { case json_integer: case json_double: { if (!ParseElement(jsonElement, elementName, &result->numberData, outErr)) { return false; } result->type = ParameterValue::TYPE_NUMBER_ARRAY; break; } case json_string: { if (!ParseElement(jsonElement, elementName, &result->stringData, outErr)) { return false; } result->type = ParameterValue::TYPE_STRING_ARRAY; break; } case json_boolean: { if (!ParseElement(jsonElement, elementName, &result->booleanData, outErr)) { return false; } result->type = ParameterValue::TYPE_BOOLEAN_ARRAY; break; } default: { outErr = "Could not parse parameter value element '" + elementName + "'. Unsupported array type."; return false; } } } else { switch (jsonElement.type) { case json_integer: case json_double: { float numberValue; if (!ParseElement(jsonElement, elementName, &numberValue, outErr)) { return false; } result->type = ParameterValue::TYPE_NUMBER; result->numberData.push_back(numberValue); break; } case json_string: { std::string stringValue; if (!ParseElement(jsonElement, elementName, &stringValue, outErr)) { return false; } result->type = ParameterValue::TYPE_STRING; result->stringData.push_back(stringValue); break; } case json_boolean: { bool booleanValue; if (!ParseElement(jsonElement, elementName, &booleanValue, outErr)) { return false; } result->type = ParameterValue::TYPE_BOOLEAN; result->booleanData.push_back(booleanValue); break; } default: { outErr = "Could not parse parameter value element '" + elementName + "'. Unsupported type."; return false; } } } *out = std::move(result); return true; } // Parses a Technique::Parameter element. template<> bool ParseElement<std::unique_ptr<Technique::Parameter>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<Technique::Parameter>* out, std::string& outErr) { static const std::unordered_map<long long, Technique::Parameter::Type> typeMap = { { 5120, Technique::Parameter::TYPE_BYTE }, { 5121, Technique::Parameter::TYPE_UNSIGNED_BYTE }, { 5122, Technique::Parameter::TYPE_SHORT }, { 5123, Technique::Parameter::TYPE_UNSIGNED_SHORT }, { 5124, Technique::Parameter::TYPE_INT }, { 5125, Technique::Parameter::TYPE_UNSIGNED_INT }, { 5126, Technique::Parameter::TYPE_FLOAT }, { 35664, Technique::Parameter::TYPE_FLOAT_VEC2 }, { 35665, Technique::Parameter::TYPE_FLOAT_VEC3 }, { 35666, Technique::Parameter::TYPE_FLOAT_VEC4 }, { 35667, Technique::Parameter::TYPE_INT_VEC2 }, { 35668, Technique::Parameter::TYPE_INT_VEC3 }, { 35669, Technique::Parameter::TYPE_INT_VEC4 }, { 35670, Technique::Parameter::TYPE_BOOL }, { 35671, Technique::Parameter::TYPE_BOOL_VEC2 }, { 35672, Technique::Parameter::TYPE_BOOL_VEC3 }, { 35673, Technique::Parameter::TYPE_BOOL_VEC4 }, { 35674, Technique::Parameter::TYPE_FLOAT_MAT2 }, { 35675, Technique::Parameter::TYPE_FLOAT_MAT3 }, { 35676, Technique::Parameter::TYPE_FLOAT_MAT4 }, { 35678, Technique::Parameter::TYPE_SAMPLER_2D } }; std::unique_ptr<Technique::Parameter> result(new Technique::Parameter()); if (!ParseOptionalElement(jsonElement["node"], elementName + ".node", &result->node, outErr)) { return false; } if (!ParseAndMapRequiredElement(jsonElement["type"], elementName + ".type", typeMap, &result->type, outErr)) { return false; } if (!ParseOptionalElement(jsonElement["semantic"], elementName + ".semantic", &result->semantic, outErr)) { return false; } if (!ParseOptionalElement(jsonElement["value"], elementName + ".value", &result->value, outErr)) { return false; } *out = std::move(result); return true; } // Parses a Technique element. template<> bool ParseElement<std::unique_ptr<Technique>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<Technique>* out, std::string& outErr) { std::unique_ptr<Technique> result(new Technique()); if (!ParseOptionalElement(jsonElement["parameters"], elementName + ".parameters", &result->parameters, outErr)) { return false; } if (!ParseOptionalElement(jsonElement["attributes"], elementName + ".attributes", &result->attributes, outErr)) { return false; } if (!ParseOptionalElement(jsonElement["uniforms"], elementName + ".uniforms", &result->uniforms, outErr)) { return false; } if (!ParseRequiredElement(jsonElement["program"], elementName + ".program", &result->program, outErr)) { return false; } // TODO: States. *out = std::move(result); return true; } // Parses a Sampler element. template<> bool ParseElement<std::unique_ptr<Sampler>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<Sampler>* out, std::string& outErr) { static const std::unordered_map<long long, Sampler::FilterType> magFilterTypeMap = { { 9728, Sampler::FILTER_TYPE_NEAREST }, { 9729, Sampler::FILTER_TYPE_LINEAR } }; static const std::unordered_map<long long, Sampler::FilterType> minFilterTypeMap = { { 9728, Sampler::FILTER_TYPE_NEAREST }, { 9729, Sampler::FILTER_TYPE_LINEAR }, { 9984, Sampler::FILTER_TYPE_NEAREST_MINMAP_NEAREST }, { 9985, Sampler::FILTER_TYPE_LINEAR_MINMAP_NEAREST }, { 9986, Sampler::FILTER_TYPE_NEAREST_MINMAP_LINEAR }, { 9987, Sampler::FILTER_TYPE_LINEAR_MINMAP_LINEAR } }; static const std::unordered_map<long long, Sampler::WrapType> wrapTypeMap = { { 33071, Sampler::WRAP_TYPE_CLAMP_TO_EDGE }, { 33648, Sampler::WRAP_TYPE_MIRRORED_REPEAT }, { 10497, Sampler::WRAP_TYPE_REPEAT } }; std::unique_ptr<Sampler> result(new Sampler()); if (!ParseAndMapOptionalElement(jsonElement["magFilter"], elementName + ".magFilter", magFilterTypeMap, &result->magFilter, outErr)) { return false; } if (!ParseAndMapOptionalElement(jsonElement["minFilter"], elementName + ".minFilter", minFilterTypeMap, &result->minFilter, outErr)) { return false; } if (!ParseAndMapOptionalElement(jsonElement["wrapS"], elementName + ".wrapS", wrapTypeMap, &result->wrapS, outErr)) { return false; } if (!ParseAndMapOptionalElement(jsonElement["wrapT"], elementName + ".wrapT", wrapTypeMap, &result->wrapT, outErr)) { return false; } *out = std::move(result); return true; } // Parses a Material element. template<> bool ParseElement<std::unique_ptr<Material>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<Material>* out, std::string& outErr) { std::unique_ptr<Material> result(new Material()); if (!ParseOptionalElement(jsonElement["technique"], elementName + ".technique", &result->technique, outErr)) { return false; } if (!ParseOptionalElement(jsonElement["values"], elementName + ".values", &result->values, outErr)) { return false; } *out = std::move(result); return true; } // Parses an Image element. template<> bool ParseElement<std::unique_ptr<Image>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<Image>* out, std::string& outErr) { std::unique_ptr<Image> result(new Image()); if (!ParseRequiredElement(jsonElement["uri"], elementName + ".uri", &result->uri, outErr)) { return false; } *out = std::move(result); return true; } // Parses a Texture element. template<> bool ParseElement<std::unique_ptr<Texture>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<Texture>* out, std::string& outErr) { static const std::unordered_map<long long, Texture::Format> formatMap = { { 6406, Texture::FORMAT_ALPHA }, { 6407, Texture::FORMAT_RGB }, { 6408, Texture::FORMAT_RGBA }, { 6409, Texture::FORMAT_LUMINANCE }, { 6410, Texture::FORMAT_LUMINANCE_ALPHA } }; static const std::unordered_map<long long, Texture::Type> typeMap = { { 5121, Texture::TYPE_UNSIGNED_BYTE }, { 33635, Texture::TYPE_UNSIGNED_SHORT_5_6_5 }, { 32819, Texture::TYPE_UNSIGNED_SHORT_4_4_4_4 }, { 32820, Texture::TYPE_UNSIGNED_SHORT_5_5_5_1 } }; std::unique_ptr<Texture> result(new Texture()); if (!ParseRequiredElement(jsonElement["sampler"], elementName + ".sampler", &result->sampler, outErr)) { return false; } if (!ParseRequiredElement(jsonElement["source"], elementName + ".source", &result->source, outErr)) { return false; } if (!ParseAndMapOptionalElement(jsonElement["format"], elementName + ".format", formatMap, &result->format, outErr)) { return false; } if (!ParseAndMapOptionalElement( jsonElement["internalFormat"], elementName + ".internalFormat", formatMap, &result->internalFormat, outErr)) { return false; } if (!ParseAndMapOptionalElement(jsonElement["type"], elementName + ".type", typeMap, &result->type, outErr)) { return false; } *out = std::move(result); return true; } // Parses an Animation::Sampler element. template<> bool ParseElement<std::unique_ptr<Animation::Sampler>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<Animation::Sampler>* out, std::string& outErr) { std::unique_ptr<Animation::Sampler> result(new Animation::Sampler()); if (!ParseRequiredElement(jsonElement["input"], elementName + ".input", &result->input, outErr)) { return false; } if (!ParseRequiredElement(jsonElement["output"], elementName + ".output", &result->output, outErr)) { return false; } // NOTE: Not parsing interpolation here due to LINEAR being the only thing supported in glTF 1.0 *out = std::move(result); return true; } // Parses an Animation::Channel element. template<> bool ParseElement<std::unique_ptr<Animation::Channel>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<Animation::Channel>* out, std::string& outErr) { std::unique_ptr<Animation::Channel> result(new Animation::Channel()); if (!ParseRequiredElement(jsonElement["sampler"], elementName + ".sampler", &result->sampler, outErr)) { return false; } auto targetElement = jsonElement["target"]; if (targetElement.type == json_none) { outErr = "The required element '" + elementName + ".taget' does not exist."; return false; } if (!ParseRequiredElement(targetElement["id"], elementName + ".target.id", &result->target.id, outErr)) { return false; } if (!ParseRequiredElement(targetElement["path"], elementName + ".target.path", &result->target.path, outErr)) { return false; } *out = std::move(result); return true; } // Parses an Animation element. template<> bool ParseElement<std::unique_ptr<Animation>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<Animation>* out, std::string& outErr) { std::unique_ptr<Animation> result(new Animation()); if (!ParseOptionalElement(jsonElement["parameters"], elementName + ".parameters", &result->parameters, outErr)) { return false; } if (!ParseOptionalElement(jsonElement["channels"], elementName + ".channels", &result->channels, outErr)) { return false; } if (!ParseOptionalElement(jsonElement["samplers"], elementName + ".samplers", &result->samplers, outErr)) { return false; } *out = std::move(result); return true; } // Parses a Skin element. template<> bool ParseElement<std::unique_ptr<Skin>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<Skin>* out, std::string& outErr) { // Default value for the bindShapeMatrix; static const float defaultBindShapeMatrix[] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; std::unique_ptr<Skin> result(new Skin()); // Bind shape matrix. auto bindShapeMatrixElement = jsonElement["bindShapeMatrix"]; if (bindShapeMatrixElement.type == json_none) { memcpy( static_cast<void*>(&result->bindShapeMatrix[0]), static_cast<const void*>(&defaultBindShapeMatrix[0]), sizeof(defaultBindShapeMatrix)); } else if (!ParseFixedSizeArrayElement( bindShapeMatrixElement, elementName + ".bindShapeMatix", sizeof(result->bindShapeMatrix) / sizeof(result->bindShapeMatrix[0]), &result->bindShapeMatrix[0], outErr)) { return false; } if (!ParseRequiredElement(jsonElement["inverseBindMatrices"], elementName + ".inverseBindMatrices", &result->inverseBindMatrices, outErr)) { return false; } if (!ParseRequiredElement(jsonElement["jointNames"], elementName + ".jointNames", &result->jointNames, outErr)) { return false; } *out = std::move(result); return true; } // Parses a Node element. template<> bool ParseElement<std::unique_ptr<Node>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<Node>* out, std::string& outErr) { // Default values for the transform properties. static const float defaultRotation[] = { 0.0f, 0.0f, 0.0f, 1.0f }; static const float defaultScale[] = { 1.0f, 1.0f, 1.0f }; static const float defaultTranslation[] = { 0.0f, 0.0f, 0.0f }; static const float defaultMatrix[] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; std::unique_ptr<Node> result(new Node()); if (!ParseOptionalElement(jsonElement["camera"], elementName + ".camera", &result->camera, outErr)) { return false; } if (!ParseOptionalElement(jsonElement["children"], elementName + ".children", &result->children, outErr)) { return false; } if (!ParseOptionalElement(jsonElement["skeletons"], elementName + ".skeletons", &result->skeletons, outErr)) { return false; } if (!ParseOptionalElement(jsonElement["skin"], elementName + ".skin", &result->skin, outErr)) { return false; } if (!ParseOptionalElement(jsonElement["jointName"], elementName + ".jointName", &result->jointName, outErr)) { return false; } if (!ParseOptionalElement(jsonElement["meshes"], elementName + ".meshes", &result->meshes, outErr)) { return false; } // Parse the node transform. // If any one of these elements are set we assume it's a component-based transform. auto rotationElement = jsonElement["rotation"]; auto scaleElement = jsonElement["scale"]; auto transElement = jsonElement["translation"]; if (rotationElement.type != json_none || scaleElement.type != json_none || transElement.type != json_none) { result->transformType = Node::TRANSFORM_TYPE_COMPOSITE; auto composite = &result->transform.composite; // Rotation. if (rotationElement.type == json_none) { memcpy(static_cast<void*>(&composite->rotation[0]), static_cast<const void*>(&defaultRotation[0]), sizeof(defaultRotation)); } else if (!ParseFixedSizeArrayElement( rotationElement, elementName + ".rotation", sizeof(composite->rotation) / sizeof(composite->rotation[0]), &composite->rotation[0], outErr)) { return false; } // Scale. if (scaleElement.type == json_none) { memcpy(static_cast<void*>(&composite->scale[0]), static_cast<const void*>(&defaultScale[0]), sizeof(defaultScale)); } else if (!ParseFixedSizeArrayElement( scaleElement, elementName + ".scale", sizeof(composite->scale) / sizeof(composite->scale[0]), &composite->scale[0], outErr)) { return false; } // Translation. if (transElement.type == json_none) { memcpy(static_cast<void*>(&composite->translation[0]), static_cast<const void*>(&defaultTranslation[0]), sizeof(defaultTranslation)); } else if (!ParseFixedSizeArrayElement( transElement, elementName + ".translation", sizeof(composite->translation) / sizeof(composite->translation[0]), &composite->translation[0], outErr)) { return false; } } else { // Otherwise we assume it's a matrix. result->transformType = Node::TRANSFORM_TYPE_MATRIX; auto matrixElement = jsonElement["matrix"]; if (matrixElement.type == json_none) { memcpy(static_cast<void*>(&result->transform.matrix[0]), static_cast<const void*>(&defaultMatrix[0]), sizeof(defaultMatrix)); } else if (!ParseFixedSizeArrayElement( matrixElement, elementName + ".matrix", sizeof(result->transform.matrix) / sizeof(result->transform.matrix[0]), &result->transform.matrix[0], outErr)) { return false; } } *out = std::move(result); return true; } // Parses a Scene element. template<> bool ParseElement<std::unique_ptr<Scene>>( const json_value& jsonElement, const std::string& elementName, std::unique_ptr<Scene>* out, std::string& outErr) { std::unique_ptr<Scene> result(new Scene()); if (!ParseOptionalElement(jsonElement["nodes"], elementName + ".scenes", &result->nodes, outErr)) { return false; } *out = std::move(result); return true; } // Parses an entire glTF json document. std::unique_ptr<const glTF> Parse(const char* jsonString, size_t size, std::string& outErr) { // Parse the json string. json_value* rootElement; { char parseError[128]; json_settings settings = { 0 }; rootElement = json_parse_ex( &settings, static_cast<const json_char*>(jsonString), size, parseError); if (!rootElement) { outErr.assign(parseError); return nullptr; } } std::unique_ptr<glTF> result(new glTF()); if (!ParseOptionalElement((*rootElement)["cameras"], "glTF.cameras", &result->cameras, outErr)) { return nullptr; } if (!ParseOptionalElement((*rootElement)["buffers"], "glTF.buffers", &result->buffers, outErr)) { return nullptr; } if (!ParseOptionalElement((*rootElement)["bufferViews"], "glTF.bufferViews", &result->bufferViews, outErr)) { return nullptr; } if (!ParseOptionalElement((*rootElement)["accessors"], "glTF.accessors", &result->accessors, outErr)) { return nullptr; } if (!ParseOptionalElement((*rootElement)["meshes"], "glTF.meshes", &result->meshes, outErr)) { return nullptr; } if (!ParseOptionalElement((*rootElement)["shaders"], "glTF.shaders", &result->shaders, outErr)) { return nullptr; } if (!ParseOptionalElement((*rootElement)["programs"], "glTF.programs", &result->programs, outErr)) { return nullptr; } if (!ParseOptionalElement((*rootElement)["materials"], "glTF.materials", &result->materials, outErr)) { return nullptr; } if (!ParseOptionalElement((*rootElement)["techniques"], "glTF.techniques", &result->techniques, outErr)) { return nullptr; } if (!ParseOptionalElement((*rootElement)["samplers"], "glTF.samplers", &result->samplers, outErr)) { return nullptr; } if (!ParseOptionalElement((*rootElement)["images"], "glTF.images", &result->images, outErr)) { return nullptr; } if (!ParseOptionalElement((*rootElement)["textures"], "glTF.textures", &result->textures, outErr)) { return nullptr; } if (!ParseOptionalElement((*rootElement)["animations"], "glTF.animations", &result->animations, outErr)) { return nullptr; } if (!ParseOptionalElement((*rootElement)["skins"], "glTF.skins", &result->skins, outErr)) { return nullptr; } if (!ParseOptionalElement((*rootElement)["nodes"], "glTF.nodes", &result->nodes, outErr)) { return nullptr; } if (!ParseOptionalElement((*rootElement)["scenes"], "glTF.scenes", &result->scenes, outErr)) { return nullptr; } if (!ParseOptionalElement((*rootElement)["scene"], "glTF.scene", &result->scene, outErr)) { return nullptr; } return std::move(result); } }
1e8e7c292a602a9bdebf6253fc6384a6bc6084f0
[ "Markdown", "C++" ]
3
C++
rcashie/glTFBastard
8838e392a38b4782c6b2371b752e7e1e0263bbfa
143dd8f5a3656a21fd72444b5e6784048ebe9c23
refs/heads/master
<file_sep>if GetLocale() ~= 'ruRU' then return end module 'aux.locale.ruRU' local aux = require 'aux' local L = aux.L -- Russian localization by Lichery L['h'] = 'ч' -- hour L["Close"] = "Закрыть" L['Auto Buy'] = 'авто покупку' L['% Hist.\nValue'] = '%' L['2 Hours'] = '2 часа' L['24 Hours'] = '24 часа' L['24h'] = '24ч' L['2h'] = '2ч' L['30m'] = '30м' L['8 Hours'] = '8 часов' L['8h'] = '8ч' L['Auction Bid\n(per item)'] = 'Ставка\n(за предмет)' L['Auction Bid\n(per stack)'] = 'Ставка\n(за связку)' L['Auction Buyout\n(per item)'] = 'Выкуп\n(за предмет)' L['Auction Buyout\n(per stack)'] = 'Выкуп\n(за связку)' L['Auction found'] = 'Аукцион найден' L['Auction not found'] = 'Аукцион не найден' L['Auctions'] = 'Аукционы' L['Auto Buy'] = 'Авто покупка' L['AUX_AUCTIONS'] = 'Аук-ы' L['AUX_CMD_1'] = 'Масштаб' L['AUX_CMD_2'] = 'Игнорировать владельца' L['AUX_CMD_3'] = 'Дополнительная информация о ставках за предметы во вкладке "Лоты" (требуется перезапуск /reload)' L['AUX_CMD_4'] = 'Длительность аукционов' L['AUX_CMD_5'] = 'Стоимость изготовления предмета в окне профессии' L['AUX_CMD_6'] = 'Стоимость предмета на аукционе в подсказке' L['AUX_CMD_7'] = 'Ежедневная стоимость в подсказке' L['AUX_CMD_8'] = 'Стоимость покупки у торговца в подсказке' L['AUX_CMD_9'] = 'Стоимость продажи торговцу в подсказке' L['AUX_CMD_10'] = 'Стоимость распыления в подсказке' L['AUX_CMD_11'] = 'Результат распыления в подсказке' L['AUX_CMD_12'] = 'Очистка кэша предметов' L['AUX_CMD_13'] = 'Наполнение кэша' L['AUX_POST_BTN'] = 'Объявить аукцион' L['Bid'] = 'Ставка' L['Bids'] = 'Ставки' L['Buyout'] = 'Выкуп' L['Cache populated'] = 'Кэш наполнен' L['Cancel'] = 'Отмена' L['Clear'] = 'Очистить' L['Component'] = 'Компонент' L['Currently Equipped'] = 'На персонаже:' L['Delete'] = 'Удалить' L['Deposit: '] = 'Залог: ' L['Disable'] = 'Отключить' L['Disenchant'] = 'Распыление' L['Disenchants into'] = 'Распыляется на' L['Double-click to collapse this item and show only the cheapest auction.'] = 'Дважды щелкните, чтобы свернуть этот пункт и показать только самый дешевый аукцион.' L['Double-click to expand this item and show all the auctions.'] = 'Дважды щелкните, чтобы раскрыть этот элемент и показать все аукционы.' L['Duration'] = 'Длительность' L['Empty modifier'] = 'Пустой модификатор' L['Enable'] = 'Включить' L['Error: Auto Buy does not support Blizzard filters'] = 'Ошибка: Авто покупка не поддерживает фильтры Blizzard' L['Error: Auto Buy does not support multi-queries'] = 'Ошибка: Авто покупка не поддерживает мульти-запросы' L['Error: The real time mode does not support multi-queries'] = 'Ошибка: Режим реального времени не поддерживает мульти-запросы' L['Error: The real time mode does not support page ranges'] = 'Ошибка: Режим реального времени не поддерживает диапазоны страниц' L['Exact'] = 'Точное название' L['Expecting'] = 'Ожидается' L['Export'] = 'Экспорт' L['Favorite Searches'] = 'Избранные поиски' L['Favorite'] = 'Избранный' L['Fetching item'] = 'Получение предмета' L['Filter Builder'] = 'Фильтры поиска' L['Hide this item'] = 'Скрыть этот предмет' L['High Bidder'] = 'Покупатель' L['Import'] = 'Импорт' L['Invalid auto buy filter'] = 'Неверный фильтр авто покупки' L['Invalid choice for'] = 'Неверный выбор для' L['Invalid filter'] = 'Неверный фильтр' L['Invalid input for'] = 'Неверный ввод для' L['Invalid item name'] = 'Неверное имя предмета' L['Invalid schema'] = 'Неверная схема' L['is already hooked into'] = 'уже подключен' L['Item cache cleared'] = 'Кэш предметов очищен' L['Item Class'] = 'Класс предмета' L['Item Slot'] = 'Ячейка предмета' L['Item Subclass'] = 'Подкласс предмета' L['Item'] = 'Предмет' L['Level Range'] = 'Диапазон уровней' L['limited'] = 'ограниченно' L['loaded - /aux'] = 'загружен. Введите /aux для помощи' L['Lvl'] = 'Ур.' L['Malformed expression'] = 'Неправильно сформированное выражение' L['Min Quality'] = 'Минимальное качество' L['Move Down'] = 'Переместить вниз' L['Move Up'] = 'Переместить вверх' L['Name'] = 'Имя' L['No Bids'] = 'Ставок нет' L['No item selected'] = 'Ни один предмет не выбран' L['off'] = 'выкл.' L['on'] = 'вкл.' L['Outbid'] = 'Ставка перебита' L['Pause'] = 'Пауза' L['Post Filter'] = 'Фильтры лота' L['Post'] = 'Лоты' L['Range'] = 'Страницы' L['Real Time'] = 'Все' L['Recent Searches'] = 'Недавние поиски' L['Refresh'] = 'Обновить' L['Resume'] = 'Возобновить' L['Resuming scan...'] = 'Возобновление сканирования ...' L['Saved Searches'] = 'Сохраненные поиски' L['Scan aborted'] = 'Сканирование прервано' L['Scan complete'] = 'Сканирование завершено' L['Scan paused'] = 'Сканирование приостановлено' L['Scanning %d / %d (Page %d / %d)'] = 'Сканирование %d / %d (Страница %d / %d)' L['Scanning (Page %d / %d)'] = 'Сканирование (Страница %d / %d)' L['Scanning auctions...'] = 'Сканирование аукционов ...' L['Scanning last page ...'] = 'Сканирование последней страницы ...' L['Search Results'] = 'Результаты поиска' L['Search'] = 'Поиск' L['Searching auction...'] = 'Поиск аукционов...' L['Seller'] = 'Продавец' L['Show hidden items'] = 'Показать скрытые предметы' L['Stack Count'] = 'Количество связок' L['Stack Size'] = 'Размер связки' L['Stack\nSize'] = 'Размер\nсвязки' L['Status'] = 'Статус' L['Table full!\nFurther results from this search will still be processed but no longer displayed in the table.'] = 'Таблица полна!\nДальнейшие результаты этого поиска будут обработаны, но уже не будет отображаться в таблице.' L['Time\nLeft'] = 'Срок' L['Today'] = 'Сегодня' L['Total Cost'] = 'Общая стоимость' L['Unit Buyout Price'] = 'Выкупная цена за единицу' L['Unit Starting Price'] = 'Начальная цена за единицу' L['Usable'] = 'Подходящее' L['Usage'] = 'Использование' L['Value'] = 'Стоимость' L['Vendor Buy'] = 'Купить' L['Vendor'] = 'Продать'<file_sep>module 'aux.locale.enUS' local aux = require 'aux' local L = aux.L L['h'] = 'h' -- hour L["Close"] = "Close" L['Auto Buy'] = 'Auto Buy' L['% Hist.\nValue'] = '% Hist.\nValue' L['2 Hours'] = '2 Hours' L['24 Hours'] = '24 Hours' L['24h'] = '24h' L['2h'] = '2h' L['30m'] = '30m' L['8 Hours'] = '8 Hours' L['8h'] = '8h' L['Auction Bid\n(per item)'] = 'Auction Bid\n(per item)' L['Auction Bid\n(per stack)'] = 'Auction Bid\n(per stack)' L['Auction Buyout\n(per item)'] = 'Auction Buyout\n(per item)' L['Auction Buyout\n(per stack)'] = 'Auction Buyout\n(per stack)' L['Auction found'] = 'Auction found' L['Auction not found'] = 'Auction not found' L['Auctions'] = 'Auctions' L['Auto Buy'] = 'Auto Buy' L['AUX_AUCTIONS'] = 'Auctions' L['AUX_CMD_1'] = '' -- CMD_1 - CMD_12 - descriptions chat commands L['AUX_CMD_2'] = '' L['AUX_CMD_3'] = '' L['AUX_CMD_4'] = '' L['AUX_CMD_5'] = '' L['AUX_CMD_6'] = '' L['AUX_CMD_7'] = '' L['AUX_CMD_8'] = '' L['AUX_CMD_9'] = '' L['AUX_CMD_10'] = '' L['AUX_CMD_11'] = '' L['AUX_CMD_12'] = '' L['AUX_CMD_13'] = '' L['AUX_POST_BTN'] = 'Post' L['Bid'] = 'Bid' L['Bids'] = 'Bids' L['Buyout'] = 'Buyout' L['Cache populated'] = 'Cache populated' L['Cancel'] = 'Cancel' L['Clear'] = 'Clear' L['Component'] = 'Component' L['Currently Equipped'] = 'Currently Equipped' L['Delete'] = 'Delete' L['Deposit: '] = 'Deposit: ' L['Disable'] = 'Disable' L['Disenchant'] = 'Disenchant' L['Disenchants into'] = 'Disenchants into' L['Double-click to collapse this item and show only the cheapest auction.'] = 'Double-click to collapse this item and show only the cheapest auction.' L['Double-click to expand this item and show all the auctions.'] = 'Double-click to expand this item and show all the auctions.' L['Duration'] = 'Duration' L['Empty modifier'] = 'Empty modifier' L['Enable'] = 'Enable' L['Error: Auto Buy does not support Blizzard filters'] = 'Error: Auto Buy does not support Blizzard filters' L['Error: Auto Buy does not support multi-queries'] = 'Error: Auto Buy does not support multi-queries' L['Error: The real time mode does not support multi-queries'] = 'Error: The real time mode does not support multi-queries' L['Error: The real time mode does not support page ranges'] = 'Error: The real time mode does not support page ranges' L['Exact'] = 'Exact' L['Expecting'] = 'Expecting' L['Export'] = 'Export' L['Favorite Searches'] = 'Favorite Searches' L['Favorite'] = 'Favorite' L['Fetching item'] = 'Fetching item' L['Filter Builder'] = 'Filter Builder' L['Hide this item'] = 'Hide this item' L['High Bidder'] = 'High Bidder' L['Import'] = 'Import' L['Invalid auto buy filter'] = 'Invalid auto buy filter' L['Invalid choice for'] = 'Invalid choice for' L['Invalid filter'] = 'Invalid filter' L['Invalid input for'] = 'Invalid input for' L['Invalid item name'] = 'Invalid item name' L['Invalid schema'] = 'Invalid schema' L['is already hooked into'] = 'is already hooked into' L['Item cache cleared'] = 'Item cache cleared' L['Item Class'] = 'Item Class' L['Item Slot'] = 'Item Slot' L['Item Subclass'] = 'Item Subclass' L['Item'] = 'Item' L['Level Range'] = 'Level Range' L['limited'] = 'limited' L['loaded - /aux'] = 'loaded - /aux' L['Lvl'] = 'Lvl' L['Malformed expression'] = 'Malformed expression' L['Min Quality'] = 'Min Quality' L['Move Down'] = 'Move Down' L['Move Up'] = 'Move Up' L['Name'] = 'Name' L['No Bids'] = 'No Bids' L['No item selected'] = 'No item selected' L['off'] = 'off' L['on'] = 'on' L['Outbid'] = 'Outbid' L['Pause'] = 'Pause' L['Post Filter'] = 'Post Filter' L['Post'] = 'Post' L['Range'] = 'Range' L['Real Time'] = 'Real Time' L['Recent Searches'] = 'Recent Searches' L['Refresh'] = 'Refresh' L['Resume'] = 'Resume' L['Resuming scan...'] = 'Resuming scan...' L['Saved Searches'] = 'Saved Searches' L['Scan aborted'] = 'Scan aborted' L['Scan complete'] = 'Scan complete' L['Scan paused'] = 'Scan paused' L['Scanning %d / %d (Page %d / %d)'] = 'Scanning %d / %d (Page %d / %d)' L['Scanning (Page %d / %d)'] = 'Scanning (Page %d / %d)' L['Scanning auctions...'] = 'Scanning auctions...' L['Scanning last page ...'] = "Scanning last page ..." L['Search Results'] = 'Search Results' L['Search'] = 'Search' L['Searching auction...'] = 'Searching auction...' L['Seller'] = 'Seller' L['Show hidden items'] = 'Show hidden items' L['Stack Count'] = 'Stack Count' L['Stack Size'] = 'Stack Size' L['Stack\nSize'] = 'Stack\nSize' L['Status'] = 'Status' L['Table full!\nFurther results from this search will still be processed but no longer displayed in the table.'] = 'Table full!\nFurther results from this search will still be processed but no longer displayed in the table.' L['Time\nLeft'] = 'Time\nLeft' L['Today'] = 'Today' L['Total Cost'] = 'Total Cost' L['Unit Buyout Price'] = 'Unit Buyout Price' L['Unit Starting Price'] = 'Unit Starting Price' L['Usable'] = 'Usable' L['Usage'] = 'Usage' L['Value'] = 'Value' L['Vendor Buy'] = 'Vendor Buy' L['Vendor'] = 'Vendor'
38aa689b06560685cb59757be4bc9ff8ef057853
[ "Lua" ]
2
Lua
WoWruRU-ClassicAddons/aux-addon
5153fb2615d624ea877ff2552141e57d0b6fda85
ae7110a7d3ce0303e27be9ac8ac2f4c75580cf2c
refs/heads/main
<file_sep>Instructions How to Run 1.Launch cmd window, cd to the folder contains main.py. 2.Type in following command in cmd window: python main.py 3.Or you can just double click main.py. How to Control 1.After the game starts is a fixed view, use W/S/A/D to move the car, the camera will follow. 2.Press 'B' will switch to orbit camera mode. 3.Press the middle mouse button and move the mouse can fly around the car. 4.Mouse wheel used to change fov(zoom in / out). 5.Number keys 1, 2 used to rotate the star. 6.Number keys 3, 4 used to scale the star. 7.Right click in the viewport will fire up a popup menu, use to switch between point light, spot light and directional light and ajust ambient color, diffuse color and light position properties. 8.Press "X will fire up a window let you change window resolution, switch to full screen.<file_sep>from collada import Collada import collada from OpenGL.GL import * from OpenGL.GLUT import * from ctypes import c_float, c_void_p, sizeof import numpy as np from .transformations import quaternion_from_matrix, quaternion_matrix, quaternion_slerp class Joint: def __init__(self, id, inverse_transform_matrix): self.id = id self.children = [] self.inverse_transform_matrix = inverse_transform_matrix class KeyFrame: def __init__(self, time, joint_transform): self.time = time self.init_transform(joint_transform) def init_transform(self, joint_transform): self.joint_transform = dict() for key, value in joint_transform.items(): translation_matrix = np.identity(4) translation_matrix[0, 3], translation_matrix[1, 3], translation_matrix[2, 3] = value[0, 3], value[1, 3], \ value[2, 3] rotation_matrix = quaternion_from_matrix(value) self.joint_transform[key] = [translation_matrix, rotation_matrix] class ColladaModel: def __init__(self, collada_file_path): model = Collada(collada_file_path) self.vao = [] self.inverse_transform_matrices = [value for _, value in model.controllers[0].joint_matrices.items()] self.joints_order = {"Armature_" + joint_name: index for index, joint_name in enumerate(np.squeeze(model.controllers[0].weight_joints.data))} self.joint_count = len(self.joints_order) for node in model.scenes[0].nodes: if node.id == 'Armature': self.root_joint = Joint(node.children[0].id, self.inverse_transform_matrices[self.joints_order.get(node.children[0].id)]) self.root_joint.children.extend(self.__load_armature(node.children[0])) del self.inverse_transform_matrices if node.id == "Cube": self.__load_mesh_data(node.children[0]) self.render_static_matrices = [np.identity(4) for _ in range(len(self.joints_order))] self.render_animation_matrices = [i for i in range(len(self.joints_order))] self.__load_keyframes(model.animations) self.doing_animation = False self.frame_start_time = None self.animation_keyframe_pointer = 0 def __load_keyframes(self, animation_node): self.keyframes = [] keyframes_times = np.squeeze(animation_node[0].sourceById.get(animation_node[0].id + "-input").data).tolist() for index, time in enumerate(keyframes_times): joint_dict = dict() for animation in animation_node: joint_dict[animation.id] = animation.sourceById.get(animation.id + "-output").data[ index * 16:(index + 1) * 16].reshape((4, 4)) self.keyframes.append(KeyFrame(time, joint_dict)) def __load_armature(self, node): children = [] for child in node.children: if type(child) == collada.scene.Node: joint = Joint(child.id, self.inverse_transform_matrices[self.joints_order.get(child.id)]) joint.children.extend(self.__load_armature(child)) children.append(joint) return children def __load_mesh_data(self, node): self.ntriangles = [] self.texture = [] weights_data = np.squeeze(node.controller.weights.data) for index, mesh_data in enumerate(node.controller.geometry.primitives): vertex = [] self.ntriangles.append(mesh_data.ntriangles) try: material = node.materials[index] diffuse = material.target.effect.diffuse texture_type = "v_color" if type(diffuse) == tuple else "sampler" except: texture_type = None for i in range(mesh_data.ntriangles): v = mesh_data.vertex[mesh_data.vertex_index[i]] n = mesh_data.normal[mesh_data.normal_index[i]] if texture_type == "sampler": t = mesh_data.texcoordset[0][mesh_data.texcoord_indexset[0][i]] elif texture_type == "v_color": t = np.array(diffuse[:-1]).reshape([1, -1]).repeat([3], axis=0) j_index_ = [node.controller.joint_index[mesh_data.vertex_index[i, 0]], node.controller.joint_index[mesh_data.vertex_index[i, 1]], node.controller.joint_index[mesh_data.vertex_index[i, 2]]] w_index = [node.controller.weight_index[mesh_data.vertex_index[i, 0]], node.controller.weight_index[mesh_data.vertex_index[i, 1]], node.controller.weight_index[mesh_data.vertex_index[i, 2]]] w_ = [weights_data[w_index[0]], weights_data[w_index[1]], weights_data[w_index[2]]] j_index = [] w = [] for j in range(3): if j_index_[j].size < 3: j_index.append( np.pad(j_index_[j], (0, 3 - j_index_[j].size), 'constant', constant_values=(0, 0))[:3]) w.append( np.pad(w_[j], (0, 3 - j_index_[j].size), 'constant', constant_values=(0, 0))[:3]) else: j_index.append(j_index_[j][:3]) w.append(w_[j][:3] / np.sum(w_[j][:3])) if not texture_type: vertex.append(np.concatenate((v, n, j_index, w), axis=1)) else: vertex.append(np.concatenate((v, n, j_index, w, t), axis=1)) self.__set_vao(np.row_stack(vertex), texture_type) if texture_type == "sampler": self.texture.append(self.__set_texture(diffuse.sampler.surface.image)) else: self.texture.append(-1) def __set_vao(self, points, texture_type): points = np.squeeze(points).astype(np.float32) self.vao.append(glGenVertexArrays(1)) vbo = glGenBuffers(1) glBindVertexArray(self.vao[-1]) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, points, GL_STATIC_DRAW) step = 14 if texture_type == "sampler" else 15 if texture_type == "v_color" else 12 glVertexAttribPointer(0, 3, GL_FLOAT, False, step * sizeof(c_float), c_void_p(0 * sizeof(c_float))) glEnableVertexAttribArray(0) glVertexAttribPointer(1, 3, GL_FLOAT, False, step * sizeof(c_float), c_void_p(3 * sizeof(c_float))) glEnableVertexAttribArray(1) glVertexAttribPointer(2, 3, GL_FLOAT, False, step * sizeof(c_float), c_void_p(6 * sizeof(c_float))) glEnableVertexAttribArray(2) glVertexAttribPointer(3, 3, GL_FLOAT, False, step * sizeof(c_float), c_void_p(9 * sizeof(c_float))) glEnableVertexAttribArray(3) if texture_type: glVertexAttribPointer(4, 2 if texture_type == "sampler" else 3, GL_FLOAT, False, step * sizeof(c_float), c_void_p((12 if texture_type == "sampler" else 13) * sizeof(c_float))) glEnableVertexAttribArray(4) glBindBuffer(GL_ARRAY_BUFFER, 0) glBindVertexArray(0) def __set_texture(self, image): texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) image = image.pilimage try: ix, iy, image = image.size[0], image.size[1], image.tobytes("raw", "RGBA", 0, -1) except: ix, iy, image = image.size[0], image.size[1], image.tobytes("raw", "RGBX", 0, -1) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image) glGenerateMipmap(GL_TEXTURE_2D) return texture def render(self, shader_program): shader_program.use() for index, m in enumerate(self.render_static_matrices): shader_program.set_matrix("jointTransforms[" + str(index) + "]", m, transpose=GL_TRUE) for index, vao in enumerate(self.vao): if self.texture[index] != -1: glUniform1i(glGetUniformLocation(shader_program.id, "texture1"), index) glActiveTexture(GL_TEXTURE0 + index) glBindTexture(GL_TEXTURE_2D, self.texture[index]) glBindVertexArray(vao) glDrawArrays(GL_TRIANGLES, 0, self.ntriangles[index] * 3) if self.texture[index] != -1: glBindTexture(GL_TEXTURE_2D, 0) def animation(self, shader_program, loop_animation=False): if not self.doing_animation: self.doing_animation = True self.frame_start_time = glutGet(GLUT_ELAPSED_TIME) pre_frame, next_frame = self.keyframes[self.animation_keyframe_pointer:self.animation_keyframe_pointer + 2] frame_duration_time = (next_frame.time - pre_frame.time) * 1000 current_frame_time = glutGet(GLUT_ELAPSED_TIME) frame_progress = (current_frame_time - self.frame_start_time) / frame_duration_time if frame_progress >= 1: self.animation_keyframe_pointer += 1 if self.animation_keyframe_pointer == len(self.keyframes) - 1: self.animation_keyframe_pointer = 0 self.frame_start_time = glutGet(GLUT_ELAPSED_TIME) pre_frame, next_frame = self.keyframes[self.animation_keyframe_pointer:self.animation_keyframe_pointer + 2] frame_duration_time = (next_frame.time - pre_frame.time) * 1000 current_frame_time = glutGet(GLUT_ELAPSED_TIME) frame_progress = (current_frame_time - self.frame_start_time) / frame_duration_time # interpolating; pre_frame, next_frame, frame_progress self.interpolation_joint = dict() for key, value in pre_frame.joint_transform.items(): t_m = self.interpolating_translation(value[0], next_frame.joint_transform.get(key)[0], frame_progress) r_m = self.interpolating_rotation(value[1], next_frame.joint_transform.get(key)[1], frame_progress) matrix = np.matmul(t_m, r_m) self.interpolation_joint[key] = matrix self.load_animation_matrices(self.root_joint, np.identity(4)) self.render(shader_program) def interpolating_translation(self, translation_a, translation_b, progress): i_translation = np.identity(4) i_translation[0, 3] = translation_a[0, 3] + (translation_b[0, 3] - translation_a[0, 3]) * progress i_translation[1, 3] = translation_a[1, 3] + (translation_b[1, 3] - translation_a[1, 3]) * progress i_translation[2, 3] = translation_a[2, 3] + (translation_b[2, 3] - translation_a[2, 3]) * progress return i_translation def interpolating_rotation(self, rotation_a, rotation_b, progress): return quaternion_matrix(quaternion_slerp(rotation_a, rotation_b, progress)) def load_animation_matrices(self, joint, parent_matrix): p = np.matmul(parent_matrix, self.interpolation_joint.get(joint.id + "_pose_matrix")) for child in joint.children: self.load_animation_matrices(child, p) self.render_static_matrices[self.joints_order.get(joint.id)] = np.matmul(p, joint.inverse_transform_matrix) if __name__ == "__main__": # scene = ColladaModel("/home/shuai/human.dae") # a = np.array([[3], [14], [15], [12], [111], [134]]) # # a_sque = np.squeeze(a) pass <file_sep># CS4182-course-project A simple car game built by openGL The course project of CS4182 Computer Graphics <file_sep>from OpenGL.GL import * import PIL.Image as Image #----------------------------------------------texture development----------- def loadTexture(imageName): texturedImage = Image.open(imageName) try: imgX = texturedImage.size[0] imgY = texturedImage.size[1] img = texturedImage.tobytes("raw","RGBX",0,-1)#tostring("raw", "RGBX", 0, -1) except Exception as e: print("Error:", e) print("Switching to RGBA mode.") imgX = texturedImage.size[0] imgY = texturedImage.size[1] img = texturedImage.tobytes("raw","RGB",0,-1)#tostring("raw", "RGBA", 0, -1) textureID = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, textureID) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexImage2D(GL_TEXTURE_2D, 0, 3, imgX, imgY, 0, GL_RGBA, GL_UNSIGNED_BYTE, img) return textureID<file_sep>import OpenGL.GL as GL import OpenGL.GLUT as GLUT import OpenGL.GLU as GLU ## Avoid conflict with Python open from PIL.Image import open as imageOpen ## This class is used to create an object from geometry and materials ## saved to a file in WaveFront object format. The object exported ## from Blender must have the normals included. class ImportedObject: ## Constructor that includes storage for geometry and materials ## for an object. def __init__(self, fileName, setAmbient = 0.9, verbose = False): self.faces = [] self.verts = [] self.norms = [] self.texCoords = [] self.materials = [] self.fileName = fileName self.setAmbient = False self.hasTex = False ## Set this value to False before loading if the model is flat self.isSmooth = True self.verbose = verbose ## Load the material properties from the file def loadMat(self): ## Open the material file with open((self.fileName + ".mtl"), "r") as matFile: ## Load the material properties into tempMat tempMat = [] for line in matFile: ## Break the line into its components vals = line.split() ## Make sure there's something in the line (not blank) if len(vals) > 0 : ## Record that a new material is being applied if vals[0] == "newmtl": n = vals[1] tempMat.append(n) ## Load the specular exponent elif vals[0] == "Ns": n = vals[1] tempMat.append(float(n)) ## Load the diffuse values elif vals[0] == "Kd": n = map(float, vals[1:4]) tempMat.append(n) ## if self.setAmbient is False, ignore ambient values ## and load diffuse values twice to set the ambient ## equal to diffuse if self.setAmbient: tempMat.append(n) ## load the ambient values (if not overridden) elif vals[0] == "Ka" and not self.setAmbient: n = map(float, vals[1:4]) tempMat.append(n) ## load the specular values elif vals[0] == "Ks": n = map(float, vals[1:4]) tempMat.append(n) tempMat.append(None) ## specular is the last line loaded for the material self.materials.append(tempMat) tempMat = [] ## load texture file info elif vals[0] == "map_Kd": ## record the texture file name fileName = vals[1] self.materials[-1][5]=(self.loadTexture(fileName)) self.hasTex = True if self.verbose: print("Loaded " + self.fileName + \ ".mtl with " + str(len(self.materials)) + " materials") ## Load the object geometry. def loadOBJ(self): ## parse the materials file first so we know when to apply materials ## and textures self.loadMat() numFaces = 0 with open((self.fileName + ".obj"), "r") as objFile: for line in objFile: ## Break the line into its components vals = line.split() if len(vals) > 0: ## Load vertices if vals[0] == "v": v = map(float, vals[1:4]) self.verts.append(v) ## Load normals elif vals[0] == "vn": n = map(float, vals[1:4]) self.norms.append(n) ## Load texture coordinates elif vals[0] == "vt": t = map(float, vals[1:3]) self.texCoords.append(t) ## Load materials. Set index to -1! elif vals[0] == "usemtl": m = vals[1] self.faces.append([-1, m, numFaces]) ## Load the faces elif vals[0] == "f": tempFace = [] for f in vals[1:]: ## face entries have vertex/tex coord/normal w = f.split("/") ## Vertex required, but should work if texture or ## normal is missing if w[1] != '' and w[2] != '': tempFace.append([int(w[0])-1, int(w[1])-1, int(w[2])-1]) elif w[1] != '': tempFace.append([int(w[0])-1, int(w[1])-1], -1) elif w[2] != '': tempFace.append([int(w[0])-1, -1, int(w[2])-1]) else : tempFace.append([int(w[0])-1,-1, -1]) self.faces.append(tempFace) if self.verbose: print("Loaded " + self.fileName + ".obj with " + \ str(len(self.verts)) + " vertices, " + \ str(len(self.norms)) + " normals, and " + \ str(len(self.faces)) + " faces") ## Draws the object def drawObject(self): if self.hasTex: GL.glEnable(GL.GL_TEXTURE_2D) ## Use GL.GL_MODULATE instead of GL.GL_DECAL to retain lighting GL.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_MODULATE) ## ***************************************************************** ## Change GL.GL_FRONT to GL.GL_FRONT_AND_BACK if faces are missing ## (or fix the normals in the model so they point in the correct ## direction) ## ***************************************************************** GL.glPolygonMode(GL.GL_FRONT, GL.GL_FILL) for face in self.faces: ## Check if a material if face[0] == -1: self.setModelColor(face[1]) else: GL.glBegin(GL.GL_POLYGON) ## drawing normal, then texture, then vertice coords. for f in face: if f[2] != -1: GL.glNormal3f(self.norms[f[2]][0], self.norms[f[2]][1], self.norms[f[2]][2]) if f[1] != -1: GL.glTexCoord2f(self.texCoords[f[1]][0], self.texCoords[f[1]][1]) GL.glVertex3f(self.verts[f[0]][0], self.verts[f[0]][1], self.verts[f[0]][2]) GL.glEnd() ## Turn off texturing (global state variable again) GL.glDisable(GL.GL_TEXTURE_2D) ## Finds the matching material properties and sets them. def setModelColor(self, material): mat = [] for tempMat in self.materials: if tempMat[0] == material: mat = tempMat ## found it, break out. break ## Set the color for the case when lighting is turned off. Using ## the diffuse color, since the diffuse component best describes ## the object color. GL.glColor3f(mat[3][0], mat[3][1],mat[3][2]) ## Set the model to smooth or flat depending on the attribute setting if self.isSmooth: GL.glShadeModel(GL.GL_SMOOTH) else: GL.glShadeModel(GL.GL_FLAT) ## The RGBA values for the specular light intesity. The alpha value ## (1.0) is ignored unless blending is enabled. mat_specular = [mat[4][0], mat[4][1], mat[4][2], 1.0] ## The RGBA values for the diffuse light intesity. The alpha value ## (1.0) is ignored unless blending is enabled. mat_diffuse = [mat[3][0], mat[3][1],mat[3][2], 1.0] ## The value for the specular exponent. The higher the value, the ## "tighter" the specular highlight. Valid values are [0.0, 128.0] mat_ambient = [mat[2][0], mat[2][1], mat[2][2],1.0] ## The value for the specular exponent. The higher the value, the ## "tighter" the specular highlight. Valid values are [0.0, 128.0] mat_shininess = 0.128*mat[1] ## Set the material specular values for the polygon front faces. GL.glMaterialfv(GL.GL_FRONT, GL.GL_SPECULAR, mat_specular) ## Set the material shininess values for the polygon front faces. GL.glMaterialfv(GL.GL_FRONT, GL.GL_SHININESS, mat_shininess) ## Set the material diffuse values for the polygon front faces. GL.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, mat_diffuse) ## Set the material ambient values for the polygon front faces. GL.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, mat_ambient) ## See if there is a texture and bind it if it's there if mat[5] != None: GL.glBindTexture(GL.GL_TEXTURE_2D, mat[5]) ## Load a texture from the provided image file name def loadTexture(self, texFile): if self.verbose: print("Loading " + texFile) ## Open the image file texImage = imageOpen(texFile) try: ix, iy, image = texImage.size[0], \ texImage.size[1], \ texImage.tobytes("raw", "RGBA", 0, -1) except SystemError: ix, iy, image = texImage.size[0], \ texImage.size[1], \ texImage.tobytes("raw", "RGBX", 0, -1) ## GL.glGenTextures() and GL.glBindTexture() name and create a texture ## object for a texture image tempID = GL.glGenTextures(1) GL.glBindTexture(GL.GL_TEXTURE_2D, tempID) ## The four calls to GL.glTexParameter*() specify how the texture is to ## be wrapped and how the colors are to be filtered if there isn't an ## exact match between pixels in the texture and pixels on the screen ## Values for GL.GL_TEXTURE_WRAP_S and GL.GL_TEXTURE_WRAP_T are ## GL.GL_REPEAT and GL.GL_CLAMP GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT) ## The MAG_FILTER has values of GL.GL_NEAREST and GL.GL_LINEAR. There ## are many choices for values for the MIN_FILTER. GL.GL_NEAREST has ## more pixelation, but is the fastest GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) ## Store the pixel data GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT,1) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, image) return tempID import OpenGL.GL as GL import OpenGL.GLUT as GLUT import OpenGL.GLU as GLU ## Avoid conflict with Python open from PIL.Image import open as imageOpen ## This class is used to create an object from geometry and materials ## saved to a file in WaveFront object format. The object exported ## from Blender must have the normals included. class ImportedObject: ## Constructor that includes storage for geometry and materials ## for an object. def __init__(self, fileName, setAmbient = 0.9, verbose = False): self.faces = [] self.verts = [] self.norms = [] self.texCoords = [] self.materials = [] self.fileName = fileName self.setAmbient = False self.hasTex = False ## Set this value to False before loading if the model is flat self.isSmooth = True self.verbose = verbose ## Load the material properties from the file def loadMat(self, texturePath = ""): ## Open the material file with open((self.fileName + ".mtl"), "r") as matFile: ## Load the material properties into tempMat tempMat = [] for line in matFile: ## Break the line into its components vals = line.split() ## Make sure there's something in the line (not blank) if len(vals) > 0 : ## Record that a new material is being applied if vals[0] == "newmtl": n = vals[1] tempMat.append(n) ## Load the specular exponent elif vals[0] == "Ns": n = vals[1] tempMat.append(float(n)) ## Load the diffuse values elif vals[0] == "Kd": n = map(float, vals[1:4]) tempMat.append(n) ## if self.setAmbient is False, ignore ambient values ## and load diffuse values twice to set the ambient ## equal to diffuse if self.setAmbient: tempMat.append(n) ## load the ambient values (if not overridden) elif vals[0] == "Ka" and not self.setAmbient: n = map(float, vals[1:4]) tempMat.append(n) ## load the specular values elif vals[0] == "Ks": n = map(float, vals[1:4]) tempMat.append(n) tempMat.append(None) ## specular is the last line loaded for the material self.materials.append(tempMat) tempMat = [] ## load texture file info elif vals[0] == "map_Kd": ## record the texture file name fileName = vals[1] self.materials[-1][5]=(self.loadTexture(texturePath +fileName)) self.hasTex = True if self.verbose: print("Loaded " + self.fileName + \ ".mtl with " + str(len(self.materials)) + " materials") ## Load the object geometry. def loadOBJ(self, texturePath = ""): ## parse the materials file first so we know when to apply materials ## and textures self.loadMat(texturePath) numFaces = 0 with open((self.fileName + ".obj"), "r") as objFile: for line in objFile: ## Break the line into its components vals = line.split() if len(vals) > 0: ## Load vertices if vals[0] == "v": v = map(float, vals[1:4]) self.verts.append(v) ## Load normals elif vals[0] == "vn": n = map(float, vals[1:4]) self.norms.append(n) ## Load texture coordinates elif vals[0] == "vt": t = map(float, vals[1:3]) self.texCoords.append(t) ## Load materials. Set index to -1! elif vals[0] == "usemtl": m = vals[1] self.faces.append([-1, m, numFaces]) ## Load the faces elif vals[0] == "f": tempFace = [] for f in vals[1:]: ## face entries have vertex/tex coord/normal w = f.split("/") ## Vertex required, but should work if texture or ## normal is missing if w[1] != '' and w[2] != '': tempFace.append([int(w[0])-1, int(w[1])-1, int(w[2])-1]) elif w[1] != '': tempFace.append([int(w[0])-1, int(w[1])-1], -1) elif w[2] != '': tempFace.append([int(w[0])-1, -1, int(w[2])-1]) else : tempFace.append([int(w[0])-1,-1, -1]) self.faces.append(tempFace) if self.verbose: print("Loaded " + self.fileName + ".obj with " + \ str(len(self.verts)) + " vertices, " + \ str(len(self.norms)) + " normals, and " + \ str(len(self.faces)) + " faces") ## Draws the object def drawObject(self): if self.hasTex: GL.glEnable(GL.GL_TEXTURE_2D) ## Use GL.GL_MODULATE instead of GL.GL_DECAL to retain lighting GL.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_MODULATE) ## ***************************************************************** ## Change GL.GL_FRONT to GL.GL_FRONT_AND_BACK if faces are missing ## (or fix the normals in the model so they point in the correct ## direction) ## ***************************************************************** GL.glPolygonMode(GL.GL_FRONT, GL.GL_FILL) for face in self.faces: ## Check if a material if face[0] == -1: self.setModelColor(face[1]) else: GL.glBegin(GL.GL_POLYGON) ## drawing normal, then texture, then vertice coords. for f in face: if f[2] != -1: GL.glNormal3f(self.norms[f[2]][0], self.norms[f[2]][1], self.norms[f[2]][2]) if f[1] != -1: GL.glTexCoord2f(self.texCoords[f[1]][0], self.texCoords[f[1]][1]) GL.glVertex3f(self.verts[f[0]][0], self.verts[f[0]][1], self.verts[f[0]][2]) GL.glEnd() ## Turn off texturing (global state variable again) GL.glDisable(GL.GL_TEXTURE_2D) ## Finds the matching material properties and sets them. def setModelColor(self, material): mat = [] for tempMat in self.materials: if tempMat[0] == material: mat = tempMat ## found it, break out. break ## Set the color for the case when lighting is turned off. Using ## the diffuse color, since the diffuse component best describes ## the object color. GL.glColor3f(mat[3][0], mat[3][1],mat[3][2]) ## Set the model to smooth or flat depending on the attribute setting if self.isSmooth: GL.glShadeModel(GL.GL_SMOOTH) else: GL.glShadeModel(GL.GL_FLAT) ## The RGBA values for the specular light intesity. The alpha value ## (1.0) is ignored unless blending is enabled. mat_specular = [mat[4][0], mat[4][1], mat[4][2], 1.0] ## The RGBA values for the diffuse light intesity. The alpha value ## (1.0) is ignored unless blending is enabled. mat_diffuse = [mat[3][0], mat[3][1],mat[3][2], 1.0] ## The value for the specular exponent. The higher the value, the ## "tighter" the specular highlight. Valid values are [0.0, 128.0] mat_ambient = [mat[2][0], mat[2][1], mat[2][2],1.0] ## The value for the specular exponent. The higher the value, the ## "tighter" the specular highlight. Valid values are [0.0, 128.0] mat_shininess = 0.128*mat[1] ## Set the material specular values for the polygon front faces. GL.glMaterialfv(GL.GL_FRONT, GL.GL_SPECULAR, mat_specular) ## Set the material shininess values for the polygon front faces. GL.glMaterialfv(GL.GL_FRONT, GL.GL_SHININESS, mat_shininess) ## Set the material diffuse values for the polygon front faces. GL.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, mat_diffuse) ## Set the material ambient values for the polygon front faces. GL.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, mat_ambient) ## See if there is a texture and bind it if it's there if mat[5] != None: GL.glBindTexture(GL.GL_TEXTURE_2D, mat[5]) ## Load a texture from the provided image file name def loadTexture(self, texFile): if self.verbose: print("Loading " + texFile) ## Open the image file texImage = imageOpen(texFile) try: ix, iy, image = texImage.size[0], \ texImage.size[1], \ texImage.tobytes("raw", "RGBX", 0, -1) except SystemError: ix, iy, image = texImage.size[0], \ texImage.size[1], \ texImage.tobytes("raw", "RGBA", 0, -1) ## GL.glGenTextures() and GL.glBindTexture() name and create a texture ## object for a texture image tempID = GL.glGenTextures(1) GL.glBindTexture(GL.GL_TEXTURE_2D, tempID) ## The four calls to GL.glTexParameter*() specify how the texture is to ## be wrapped and how the colors are to be filtered if there isn't an ## exact match between pixels in the texture and pixels on the screen ## Values for GL.GL_TEXTURE_WRAP_S and GL.GL_TEXTURE_WRAP_T are ## GL.GL_REPEAT and GL.GL_CLAMP GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT) ## The MAG_FILTER has values of GL.GL_NEAREST and GL.GL_LINEAR. There ## are many choices for values for the MIN_FILTER. GL.GL_NEAREST has ## more pixelation, but is the fastest GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) ## Store the pixel data GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT,1) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, image) return tempID <file_sep>ca-certificates==2021.4.13 certifi==2020.12.5 numpy==1.20.2 openssl==1.1.1k Pillow==8.2.0 pycollada==0.7.1 pyglm==2.1.0 pyopengl==3.1.5 pyopengl-accelerate==3.1.5 Python-dateutil==2.8.1 setuptools==52.0.0 six==1.15.0 sqlite==3.35.4 vc==14.2 vs2015_runtime==14.27.29016 wheel==0.36.2 wincertstore==0.2<file_sep>from OpenGL.GL import * from OpenGL.GLUT import * import datetime import numpy as np class ShaderProgram(): def __init__(self, vertex_shader_path, fragment_shader_path): self.vertex_shader_path = vertex_shader_path self.fragment_shader_path = fragment_shader_path self.id = glCreateProgram() def init(self): # vertex shader vertex_shader = glCreateShader(GL_VERTEX_SHADER) self.compile(vertex_shader, self.load_shader_source(self.vertex_shader_path)) # fragment shader fragment_shader = glCreateShader(GL_FRAGMENT_SHADER) self.compile(fragment_shader, self.load_shader_source(self.fragment_shader_path)) self.link(vertex_shader, fragment_shader) def load_shader_source(self, path): try: with open(path, "r") as f: return f.read() except: print("shader file open error!") def use(self): glUseProgram(self.id) def un_use(self): glUseProgram(0) def set_uniform(self, uniform_name): temp = np.sin(datetime.datetime.now().timestamp()) glUniform4f(glGetUniformLocation(self.id, uniform_name), (temp + 1) / 2, 0.0, 0.0, 1.0) def set_matrix(self, uniform_name, value, transpose=GL_FALSE): glUniformMatrix4fv(glGetUniformLocation(self.id, uniform_name), 1, transpose, value) def compile(self, shader, source): glShaderSource(shader, source) glCompileShader(shader) self.check_error(shader, "SHADER") def link(self, vertex_shader, fragment_shader): glAttachShader(self.id, vertex_shader) glAttachShader(self.id, fragment_shader) glLinkProgram(self.id) self.check_error(self.id, "PROGRAM") glDeleteShader(vertex_shader) glDeleteShader(fragment_shader) def check_error(self, o, type): if type == "SHADER": message = glGetShaderInfoLog(o) print("shader compile error: ", message)# if message else print("") elif type == "PROGRAM": message = glGetProgramInfoLog(o) print("program link error: ", message) # if message else print("") else: pass <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*-‘ from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * import math, time, csv, datetime # import ImportObject import PIL.Image as Image # import jeep, cone, utils # from skybox import * # ImportObject.py import OpenGL.GL as GL import OpenGL.GLUT as GLUT import OpenGL.GLU as GLU ## Avoid conflict with Python open from PIL.Image import open as imageOpen import random from win32ui import IDD_SET_TABSTOPS from win32ui import IDC_EDIT_TABS from win32ui import IDC_PROMPT_TABS from win32con import IDOK from win32con import IDCANCEL import win32ui import win32con from pywin.mfc import dialog import six import appdirs import packaging windowWidth = 800 windowHeight = 600 lastWindowWidth = 0 lastWindowHeight = 0 isFullScreen = False aspect = float(windowWidth) / windowHeight; class SettingDialog(dialog. Dialog): # 通过继承dialog Dialog生成对话框类 def __init__(self): style = (win32con.DS_MODALFRAME | #定义对话框样式 win32con.WS_POPUP | win32con.WS_VISIBLE | win32con.WS_CAPTION | win32con.WS_SYSMENU | win32con.DS_SETFONT) childstyle =(win32con. WS_CHILD | #定义控件样式 win32con.WS_VISIBLE) buttonstyle = win32con.WS_TABSTOP | childstyle di = ['Python', (0, 0, 200, 90), style, None,(8, "MS Sans Serif")] ButoK =(['Button', #设置OK按钮属性 "OK", win32con.IDOK, (50, 50, 50, 14), buttonstyle | win32con.BS_PUSHBUTTON]) ButCancel =(['Button', #设置Cancel按钮属性 "Cancel", win32con.IDCANCEL, (110, 50, 50, 14), buttonstyle | win32con.BS_PUSHBUTTON]) Stadic =(['Static', #设置标签属性 'Resolution:', 12, (10, 30, 60, 14), childstyle]) Width =(['Edit', #设置文本框属性 '1280', 13, (50, 30, 50, 14), childstyle | win32con.ES_LEFT | win32con.WS_BORDER | win32con.WS_TABSTOP]) Height =(['Edit', #设置文本框属性 '720', 14, (110, 30, 50, 14), childstyle | win32con.ES_LEFT | win32con.WS_BORDER | win32con.WS_TABSTOP]) FullScreen =(['Button', #设置Cancel按钮属性 "Full Screen", 15, (50, 70, 50, 14), buttonstyle | win32con.BS_AUTOCHECKBOX]) init = [] #初始化信息列表 init.append(di) init.append(ButoK) init.append(ButCancel) init.append(Stadic) init.append(Width) init.append(Height) init.append(FullScreen) dialog.Dialog.__init__(self, init) def OnInitDialog(self): #重载对话框初始化方法 dialog.Dialog.OnInitDialog(self) #调用父类的对话框初始化方法 self.width = self.GetDlgItem(13) self.height = self.GetDlgItem(14) self.checkBox = self.GetDlgItem(15) def OnOK(self): #重载OnOK方法 global windowWidth, windowHeight, isFullScreen windowWidth = int(self.width.GetWindowText()) windowHeight = int(self.height.GetWindowText()) isFullScreen = self.checkBox.GetCheck() self.EndDialog(1) def OnCancel(self):#重载OnCancel方法 win32ui. MessageBox('Press Cancel', 'Python'. win32con.MB_OK) windowWidth = 800 windowHeight = 600; self.EndDialog() ## This class is used to create an object from geometry and materials ## saved to a file in WaveFront object format. The object exported ## from Blender must have the normals included. class ImportedObject: ## Constructor that includes storage for geometry and materials ## for an object. def __init__(self, fileName, setAmbient = 0.9, verbose = False): self.faces = [] self.verts = [] self.norms = [] self.texCoords = [] self.materials = [] self.fileName = fileName self.setAmbient = False self.hasTex = False ## Set this value to False before loading if the model is flat self.isSmooth = True self.verbose = verbose ## Load the material properties from the file def loadMat(self): ## Open the material file with open((self.fileName + ".mtl"), "r") as matFile: ## Load the material properties into tempMat tempMat = [] for line in matFile: ## Break the line into its components vals = line.split() ## Make sure there's something in the line (not blank) if len(vals) > 0 : ## Record that a new material is being applied if vals[0] == "newmtl": n = vals[1] tempMat.append(n) ## Load the specular exponent elif vals[0] == "Ns": n = vals[1] tempMat.append(float(n)) ## Load the diffuse values elif vals[0] == "Kd": n = map(float, vals[1:4]) tempMat.append(n) ## if self.setAmbient is False, ignore ambient values ## and load diffuse values twice to set the ambient ## equal to diffuse if self.setAmbient: tempMat.append(n) ## load the ambient values (if not overridden) elif vals[0] == "Ka" and not self.setAmbient: n = map(float, vals[1:4]) tempMat.append(n) ## load the specular values elif vals[0] == "Ks": n = map(float, vals[1:4]) tempMat.append(n) tempMat.append(None) ## specular is the last line loaded for the material self.materials.append(tempMat) tempMat = [] ## load texture file info elif vals[0] == "map_Kd": ## record the texture file name fileName = vals[1] self.materials[-1][5]=(self.loadTexture(fileName)) self.hasTex = True if self.verbose: print("Loaded " + self.fileName + \ ".mtl with " + str(len(self.materials)) + " materials") ## Load the object geometry. def loadOBJ(self): ## parse the materials file first so we know when to apply materials ## and textures self.loadMat() numFaces = 0 with open((self.fileName + ".obj"), "r") as objFile: for line in objFile: ## Break the line into its components vals = line.split() if len(vals) > 0: ## Load vertices if vals[0] == "v": v = map(float, vals[1:4]) self.verts.append(v) ## Load normals elif vals[0] == "vn": n = map(float, vals[1:4]) self.norms.append(n) ## Load texture coordinates elif vals[0] == "vt": t = map(float, vals[1:3]) self.texCoords.append(t) ## Load materials. Set index to -1! elif vals[0] == "usemtl": m = vals[1] self.faces.append([-1, m, numFaces]) ## Load the faces elif vals[0] == "f": tempFace = [] for f in vals[1:]: ## face entries have vertex/tex coord/normal w = f.split("/") ## Vertex required, but should work if texture or ## normal is missing if w[1] != '' and w[2] != '': tempFace.append([int(w[0])-1, int(w[1])-1, int(w[2])-1]) elif w[1] != '': tempFace.append([int(w[0])-1, int(w[1])-1], -1) elif w[2] != '': tempFace.append([int(w[0])-1, -1, int(w[2])-1]) else : tempFace.append([int(w[0])-1,-1, -1]) self.faces.append(tempFace) if self.verbose: print("Loaded " + self.fileName + ".obj with " + \ str(len(self.verts)) + " vertices, " + \ str(len(self.norms)) + " normals, and " + \ str(len(self.faces)) + " faces") ## Draws the object def drawObject(self): if self.hasTex: GL.glEnable(GL.GL_TEXTURE_2D) ## Use GL.GL_MODULATE instead of GL.GL_DECAL to retain lighting GL.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_MODULATE) ## ***************************************************************** ## Change GL.GL_FRONT to GL.GL_FRONT_AND_BACK if faces are missing ## (or fix the normals in the model so they point in the correct ## direction) ## ***************************************************************** GL.glPolygonMode(GL.GL_FRONT, GL.GL_FILL) for face in self.faces: ## Check if a material if face[0] == -1: self.setModelColor(face[1]) else: GL.glBegin(GL.GL_POLYGON) ## drawing normal, then texture, then vertice coords. for f in face: if f[2] != -1: GL.glNormal3f(self.norms[f[2]][0], self.norms[f[2]][1], self.norms[f[2]][2]) if f[1] != -1: GL.glTexCoord2f(self.texCoords[f[1]][0], self.texCoords[f[1]][1]) GL.glVertex3f(self.verts[f[0]][0], self.verts[f[0]][1], self.verts[f[0]][2]) GL.glEnd() ## Turn off texturing (global state variable again) GL.glDisable(GL.GL_TEXTURE_2D) ## Finds the matching material properties and sets them. def setModelColor(self, material): mat = [] for tempMat in self.materials: if tempMat[0] == material: mat = tempMat ## found it, break out. break ## Set the color for the case when lighting is turned off. Using ## the diffuse color, since the diffuse component best describes ## the object color. GL.glColor3f(mat[3][0], mat[3][1],mat[3][2]) ## Set the model to smooth or flat depending on the attribute setting if self.isSmooth: GL.glShadeModel(GL.GL_SMOOTH) else: GL.glShadeModel(GL.GL_FLAT) ## The RGBA values for the specular light intesity. The alpha value ## (1.0) is ignored unless blending is enabled. mat_specular = [mat[4][0], mat[4][1], mat[4][2], 1.0] ## The RGBA values for the diffuse light intesity. The alpha value ## (1.0) is ignored unless blending is enabled. mat_diffuse = [mat[3][0], mat[3][1],mat[3][2], 1.0] ## The value for the specular exponent. The higher the value, the ## "tighter" the specular highlight. Valid values are [0.0, 128.0] mat_ambient = [mat[2][0], mat[2][1], mat[2][2],1.0] ## The value for the specular exponent. The higher the value, the ## "tighter" the specular highlight. Valid values are [0.0, 128.0] mat_shininess = 0.128 * mat[1] ## Set the material specular values for the polygon front faces. GL.glMaterialfv(GL.GL_FRONT, GL.GL_SPECULAR, mat_specular) ## Set the material shininess values for the polygon front faces. GL.glMaterialfv(GL.GL_FRONT, GL.GL_SHININESS, mat_shininess) ## Set the material diffuse values for the polygon front faces. GL.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, mat_diffuse) ## Set the material ambient values for the polygon front faces. GL.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, mat_ambient) ## See if there is a texture and bind it if it's there if mat[5] != None: GL.glBindTexture(GL.GL_TEXTURE_2D, mat[5]) ## Load a texture from the provided image file name def loadTexture(self, texFile): if self.verbose: print("Loading " + texFile) ## Open the image file texImage = imageOpen(texFile) try: ix, iy, image = texImage.size[0], \ texImage.size[1], \ texImage.tobytes("raw", "RGBA", 0, -1) except SystemError: ix, iy, image = texImage.size[0], \ texImage.size[1], \ texImage.tobytes("raw", "RGBX", 0, -1) ## GL.glGenTextures() and GL.glBindTexture() name and create a texture ## object for a texture image tempID = GL.glGenTextures(1) GL.glBindTexture(GL.GL_TEXTURE_2D, tempID) ## The four calls to GL.glTexParameter*() specify how the texture is to ## be wrapped and how the colors are to be filtered if there isn't an ## exact match between pixels in the texture and pixels on the screen ## Values for GL.GL_TEXTURE_WRAP_S and GL.GL_TEXTURE_WRAP_T are ## GL.GL_REPEAT and GL.GL_CLAMP GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT) ## The MAG_FILTER has values of GL.GL_NEAREST and GL.GL_LINEAR. There ## are many choices for values for the MIN_FILTER. GL.GL_NEAREST has ## more pixelation, but is the fastest GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) ## Store the pixel data GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT,1) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, image) return tempID ## This class is used to create an object from geometry and materials ## saved to a file in WaveFront object format. The object exported ## from Blender must have the normals included. class ImportedObject: ## Constructor that includes storage for geometry and materials ## for an object. def __init__(self, fileName, setAmbient = 0.9, verbose = False): self.faces = [] self.verts = [] self.norms = [] self.texCoords = [] self.materials = [] self.fileName = fileName self.setAmbient = False self.hasTex = False ## Set this value to False before loading if the model is flat self.isSmooth = True self.verbose = verbose ## Load the material properties from the file def loadMat(self, texturePath = ""): ## Open the material file with open((self.fileName + ".mtl"), "r") as matFile: ## Load the material properties into tempMat tempMat = [] for line in matFile: ## Break the line into its components vals = line.split() ## Make sure there's something in the line (not blank) if len(vals) > 0 : ## Record that a new material is being applied if vals[0] == "newmtl": n = vals[1] tempMat.append(n) ## Load the specular exponent elif vals[0] == "Ns": n = vals[1] tempMat.append(float(n)) ## Load the diffuse values elif vals[0] == "Kd": n = map(float, vals[1:4]) tempMat.append(n) ## if self.setAmbient is False, ignore ambient values ## and load diffuse values twice to set the ambient ## equal to diffuse if self.setAmbient: tempMat.append(n) ## load the ambient values (if not overridden) elif vals[0] == "Ka" and not self.setAmbient: n = map(float, vals[1:4]) tempMat.append(n) ## load the specular values elif vals[0] == "Ks": n = map(float, vals[1:4]) tempMat.append(n) tempMat.append(None) ## specular is the last line loaded for the material self.materials.append(tempMat) tempMat = [] ## load texture file info elif vals[0] == "map_Kd": ## record the texture file name fileName = vals[1] self.materials[-1][5]=(self.loadTexture(texturePath +fileName)) self.hasTex = True if self.verbose: print("Loaded " + self.fileName + \ ".mtl with " + str(len(self.materials)) + " materials") ## Load the object geometry. def loadOBJ(self, texturePath = ""): ## parse the materials file first so we know when to apply materials ## and textures self.loadMat(texturePath) numFaces = 0 with open((self.fileName + ".obj"), "r") as objFile: for line in objFile: ## Break the line into its components vals = line.split() if len(vals) > 0: ## Load vertices if vals[0] == "v": v = map(float, vals[1:4]) self.verts.append(v) ## Load normals elif vals[0] == "vn": n = map(float, vals[1:4]) self.norms.append(n) ## Load texture coordinates elif vals[0] == "vt": t = map(float, vals[1:3]) self.texCoords.append(t) ## Load materials. Set index to -1! elif vals[0] == "usemtl": m = vals[1] self.faces.append([-1, m, numFaces]) ## Load the faces elif vals[0] == "f": tempFace = [] for f in vals[1:]: ## face entries have vertex/tex coord/normal w = f.split("/") ## Vertex required, but should work if texture or ## normal is missing if w[1] != '' and w[2] != '': tempFace.append([int(w[0])-1, int(w[1])-1, int(w[2])-1]) elif w[1] != '': tempFace.append([int(w[0])-1, int(w[1])-1], -1) elif w[2] != '': tempFace.append([int(w[0])-1, -1, int(w[2])-1]) else : tempFace.append([int(w[0])-1,-1, -1]) self.faces.append(tempFace) if self.verbose: print("Loaded " + self.fileName + ".obj with " + \ str(len(self.verts)) + " vertices, " + \ str(len(self.norms)) + " normals, and " + \ str(len(self.faces)) + " faces") ## Draws the object def drawObject(self): if self.hasTex: GL.glEnable(GL.GL_TEXTURE_2D) ## Use GL.GL_MODULATE instead of GL.GL_DECAL to retain lighting GL.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_MODULATE) ## ***************************************************************** ## Change GL.GL_FRONT to GL.GL_FRONT_AND_BACK if faces are missing ## (or fix the normals in the model so they point in the correct ## direction) ## ***************************************************************** GL.glPolygonMode(GL.GL_FRONT, GL.GL_FILL) normsKeyValues = {} texCoordsKeyValues = {} vertsKeyValues = {} for face in self.faces: ## Check if a material if face[0] == -1: self.setModelColor(face[1]) else: GL.glBegin(GL.GL_POLYGON) ## drawing normal, then texture, then vertice coords. for f in face: # print("f:" + str(f)) # print("self.norms[f[2]]:" + str(self.norms[f[2]])) # print("f[2]:" + str(f[2])) fList = list(map(int, f)) if f[2] != -1: normsf2List = None if len(normsKeyValues) > 0: if f[2] in normsKeyValues: normsf2List = normsKeyValues[f[2]] if normsf2List == None: normsKeyValues[f[2]] = list(map(float, self.norms[f[2]])) normsf2List = normsKeyValues[f[2]] GL.glNormal3f(normsf2List[0], normsf2List[1], normsf2List[2]) if f[1] != -1: texCoordsf1List = None if len(texCoordsKeyValues) > 0: if f[1] in texCoordsKeyValues: texCoordsf1List = texCoordsKeyValues[f[1]] if texCoordsf1List == None: texCoordsKeyValues[f[1]] = list(map(float, self.texCoords[f[1]])) texCoordsf1List = texCoordsKeyValues[f[1]] GL.glTexCoord2f(texCoordsf1List[0], texCoordsf1List[1]) vertsf0List = None if len(vertsKeyValues) > 0: if f[0] in vertsKeyValues: vertsf0List = vertsKeyValues[f[0]] if vertsf0List == None: vertsf0List = list(map(float, self.verts[f[0]])) vertsKeyValues[f[0]] = vertsf0List GL.glVertex3f(vertsf0List[0], vertsf0List[1], vertsf0List[2]) GL.glEnd() ## Turn off texturing (global state variable again) GL.glDisable(GL.GL_TEXTURE_2D) ## Finds the matching material properties and sets them. def setModelColor(self, material): mat = [] for tempMat in self.materials: if tempMat[0] == material: mat = tempMat ## found it, break out. break # print(mat[3]) mat3List = list(map(float, mat[3])) # print(mat3List) ## Set the color for the case when lighting is turned off. Using ## the diffuse color, since the diffuse component best describes ## the object color. GL.glColor3f(mat3List[0], mat3List[1], mat3List[2]) ## Set the model to smooth or flat depending on the attribute setting if self.isSmooth: GL.glShadeModel(GL.GL_SMOOTH) else: GL.glShadeModel(GL.GL_FLAT) mat2List = list(map(float, mat[2])) mat4List = list(map(float, mat[4])) ## The RGBA values for the specular light intesity. The alpha value ## (1.0) is ignored unless blending is enabled. mat_specular = [mat4List[0], mat4List[1], mat4List[2], 1.0] ## The RGBA values for the diffuse light intesity. The alpha value ## (1.0) is ignored unless blending is enabled. mat_diffuse = [mat3List[0], mat3List[1],mat3List[2], 1.0] ## The value for the specular exponent. The higher the value, the ## "tighter" the specular highlight. Valid values are [0.0, 128.0] mat_ambient = [mat2List[0], mat2List[1], mat2List[2],1.0] ## The value for the specular exponent. The higher the value, the ## "tighter" the specular highlight. Valid values are [0.0, 128.0] mat_shininess = 0.128 * mat[1] ## Set the material specular values for the polygon front faces. GL.glMaterialfv(GL.GL_FRONT, GL.GL_SPECULAR, mat_specular) ## Set the material shininess values for the polygon front faces. GL.glMaterialfv(GL.GL_FRONT, GL.GL_SHININESS, mat_shininess) ## Set the material diffuse values for the polygon front faces. GL.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, mat_diffuse) ## Set the material ambient values for the polygon front faces. GL.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, mat_ambient) ## See if there is a texture and bind it if it's there if mat[5] != None: GL.glBindTexture(GL.GL_TEXTURE_2D, mat[5]) ## Load a texture from the provided image file name def loadTexture(self, texFile): if self.verbose: print("Loading " + texFile) ## Open the image file texImage = imageOpen(texFile) try: ix, iy, image = texImage.size[0], \ texImage.size[1], \ texImage.tobytes("raw", "RGBX", 0, -1) except SystemError: ix, iy, image = texImage.size[0], \ texImage.size[1], \ texImage.tobytes("raw", "RGBA", 0, -1) ## GL.glGenTextures() and GL.glBindTexture() name and create a texture ## object for a texture image tempID = GL.glGenTextures(1) GL.glBindTexture(GL.GL_TEXTURE_2D, tempID) ## The four calls to GL.glTexParameter*() specify how the texture is to ## be wrapped and how the colors are to be filtered if there isn't an ## exact match between pixels in the texture and pixels on the screen ## Values for GL.GL_TEXTURE_WRAP_S and GL.GL_TEXTURE_WRAP_T are ## GL.GL_REPEAT and GL.GL_CLAMP GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT) ## The MAG_FILTER has values of GL.GL_NEAREST and GL.GL_LINEAR. There ## are many choices for values for the MIN_FILTER. GL.GL_NEAREST has ## more pixelation, but is the fastest GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) ## Store the pixel data GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT,1) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, image) return tempID # utils.py #----------------------------------------------texture development----------- def loadTexture(imageName): texturedImage = Image.open(imageName) try: imgX = texturedImage.size[0] imgY = texturedImage.size[1] img = texturedImage.tobytes("raw","RGBX",0,-1)#tostring("raw", "RGBX", 0, -1) except Exception as e: print("Error:", e) print("Switching to RGBA mode.") imgX = texturedImage.size[0] imgY = texturedImage.size[1] img = texturedImage.tobytes("raw","RGB",0,-1)#tostring("raw", "RGBA", 0, -1) textureID = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, textureID) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexImage2D(GL_TEXTURE_2D, 0, 3, imgX, imgY, 0, GL_RGBA, GL_UNSIGNED_BYTE, img) return textureID # Skybox.py class Skybox: textureIDs = [] MAP_WIDTH = 16 CELL_WIDTH = 16 MAP = MAP_WIDTH * CELL_WIDTH / 2 def __init__(self): pass def init(self): # back, front, bottom, top, left, right textureNames = ["sunset_negZ.bmp", "sunset_posZ.bmp", "sunset_negY.bmp", "sunset_posY.bmp", "sunset_negX.bmp", "sunset_posX.bmp"] for i in range(6): textureID = loadTexture("../img/" + textureNames[i]) self.textureIDs.append(textureID) def createSkybox(self, x, y, z, boxWidth, boxHeight, boxDepth): # Abtain lighting status lighing = glGetBooleanv(GL_LIGHTING) # Calculate width, height, depth of skybox width = self.MAP * boxWidth / 8 height = self.MAP * boxHeight / 8 depth = self.MAP * boxDepth / 8 # Calculate skybox center x = x + self.MAP / 8 - width / 2 y = y + self.MAP / 24 - height / 2 z = z + self.MAP / 8 - depth / 2 # Disable lighting glDisable(GL_LIGHTING) # glCullFace(GL_FRONT) glDepthMask(GL_FALSE) glPushMatrix() glLoadIdentity() glTranslatef(0, 0, 0) glEnable(GL_TEXTURE_2D) # Draw back glBindTexture(GL_TEXTURE_2D, self.textureIDs[0]) glBegin(GL_QUADS) # Assign texture coordinates and vertex positions glTexCoord2f(0.0, 0.0) glVertex3f(x + width, y, z) glTexCoord2f(0.0, 1.0) glVertex3f(x + width, y + height, z) glTexCoord2f(1.0, 1.0) glVertex3f(x, y + height, z) glTexCoord2f(1.0, 0.0) glVertex3f(x, y, z) glEnd() # Draw front glBindTexture(GL_TEXTURE_2D, self.textureIDs[1]) glBegin(GL_QUADS) # Assign texture coordinates and vertex positions glTexCoord2f(0.0, 0.0) glVertex3f(x, y, z + depth) glTexCoord2f(0.0, 1.0) glVertex3f(x, y + height, z + depth) glTexCoord2f(1.0, 1.0) glVertex3f(x + width, y + height, z + depth) glTexCoord2f(1.0, 0.0) glVertex3f(x + width, y, z + depth) glEnd() # Draw bottom glBindTexture(GL_TEXTURE_2D, self.textureIDs[2]) glBegin(GL_QUADS) # Assign texture coordinates and vertex positions glTexCoord2f(0.0, 0.0) glVertex3f(x, y, z) glTexCoord2f(0.0, 1.0) glVertex3f(x, y, z + depth) glTexCoord2f(1.0, 1.0) glVertex3f(x + width, y, z + depth) glTexCoord2f(1.0, 0.0) glVertex3f(x + width, y, z) glEnd() # Draw top glBindTexture(GL_TEXTURE_2D, self.textureIDs[3]) glBegin(GL_QUADS) # Assign texture coordinates and vertex positions glTexCoord2f(1.0, 1.0) glVertex3f(x + width, y + height, z) glTexCoord2f(1.0, 0.0) glVertex3f(x + width, y + height, z + depth) glTexCoord2f(0.0, 0.0) glVertex3f(x, y + height, z + depth) glTexCoord2f(0.0, 1.0) glVertex3f(x, y + height, z) glEnd() # Draw left glBindTexture(GL_TEXTURE_2D, self.textureIDs[4]) glBegin(GL_QUADS) # Assign texture coordinates and vertex positions glTexCoord2f(0.0, 1.0) glVertex3f(x, y + height, z) glTexCoord2f(1.0, 1.0) glVertex3f(x, y + height, z + depth) glTexCoord2f(1.0, 0.0) glVertex3f(x, y, z + depth) glTexCoord2f(0.0, 0.0) glVertex3f(x, y, z) glEnd() # Draw right glBindTexture(GL_TEXTURE_2D, self.textureIDs[5]) glBegin(GL_QUADS) # Assign texture coordinates and vertex positions glTexCoord2f(1.0, 0.0) glVertex3f(x + width, y, z) glTexCoord2f(0.0, 0.0) glVertex3f(x + width, y, z + depth) glTexCoord2f(0.0, 1.0) glVertex3f(x + width, y + height, z + depth) glTexCoord2f(1.0, 1.0) glVertex3f(x + width, y + height, z) glEnd() glPopMatrix() if lighing == GL_TRUE: glEnable(GL_LIGHTING) glDisable(GL_TEXTURE_2D) glDepthMask(GL_TRUE) # glCullFace(GL_BACK) # jeep.py from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * import math, time import ImportObject class jeep: obj = 0 displayList = 0 wheel1DL = 0 wheel2DL = 0 dimDL = 0 litDL = 0 dimL = 0 litL = 0 lightOn = False wheel1 = 0 wheel2 = 0 wheelTurn = 0.0 revWheelTurn = 360.0 #allWheels=[wheel1,wheel2] wheelDir = 'stop' posX = 0.0 posY = 1.75 posZ = 0.0 ## wheel1LocX =0 ## wheel1LocZ = 0 ## wheel2LocX = 0 ## wheel2LocZ = 0 sizeX = 1.0 sizeY = 1.0 sizeZ = 1.0 rotation = 0.0 def __init__(self, color): if (color == 'p'): self.obj = ImportedObject("../objects/jeepbare") elif (color == 'g'): self.obj = ImportedObject("../objects/jeepbare2") elif (color == 'r'): self.obj = ImportedObject("../objects/jeepbare3") self.wheel1 = ImportedObject("../objects/frontwheel") self.wheel2 = ImportedObject("../objects/backwheel") self.dimL = ImportedObject("../objects/dimlight") self.litL = ImportedObject("../objects/litlight") def makeDisplayLists(self): self.obj.loadOBJ() self.wheel1.loadOBJ() self.wheel2.loadOBJ() self.dimL.loadOBJ() self.litL.loadOBJ() self.displayList = glGenLists(1) glNewList(self.displayList, GL_COMPILE) self.obj.drawObject() glEndList() self.wheel1DL = glGenLists(1) glNewList(self.wheel1DL, GL_COMPILE) self.wheel1.drawObject() glEndList() self.wheel2DL = glGenLists(1) glNewList(self.wheel2DL, GL_COMPILE) self.wheel2.drawObject() glEndList() self.dimDL = glGenLists(1) glNewList(self.dimDL, GL_COMPILE) self.dimL.drawObject() glEndList() self.litDL = glGenLists(1) glNewList(self.litDL, GL_COMPILE) self.litL.drawObject() glEndList() def draw(self): glPushMatrix() glTranslatef(self.posX,self.posY,self.posZ) glRotatef(self.rotation,0.0,1.0,0.0) glScalef(self.sizeX,self.sizeY,self.sizeZ) glCallList(self.displayList) glPopMatrix() def drawW1(self): glPushMatrix() glTranslatef(self.posX, self.posY-1.3146, self.posZ) glRotatef(self.rotation,0.0,1.0,0.0) glTranslatef(0.0, self.posY-1.3146, 2.9845) glScalef(self.sizeX, self.sizeY, self.sizeZ) if self.wheelDir == 'fwd': glRotatef(self.revWheelTurn,1.0,0.0,0.0) elif self.wheelDir == 'back': glRotatef(self.wheelTurn,1.0,0.0,0.0) glTranslatef(0.0,1.3146,-2.9845) glCallList(self.wheel1DL) glPopMatrix() def drawW2(self): glPushMatrix() glTranslatef(self.posX, self.posY-1.3146, self.posZ) glRotatef(self.rotation,0.0,1.0,0.0) glTranslatef(0.0, self.posY-1.3146, -2.9845) glScalef(self.sizeX, self.sizeY, self.sizeZ) if self.wheelDir == 'fwd': glRotatef(self.revWheelTurn,1.0,0.0,0.0) elif self.wheelDir == 'back': glRotatef(self.wheelTurn,1.0,0.0,0.0) glTranslatef(0.0,1.3146,3.3) glCallList(self.wheel2DL) glPopMatrix() def rotateWheel(self, newTheta): global wheelTurn self.wheelTurn = self.wheelTurn + newTheta self.wheelTurn = self.wheelTurn % 360 self.revWheelTurn = 360 - self.wheelTurn def drawLight(self): glPushMatrix() glTranslatef(self.posX, self.posY, self.posZ) glRotatef(self.rotation,0.0,1.0,0.0) glScalef(self.sizeX, self.sizeY, self.sizeZ) if self.lightOn == True: glCallList(self.litDL) elif self.lightOn == False: glCallList(self.dimDL) glPopMatrix() def move(self, rot, val): if rot == False: self.posZ += val * math.cos(math.radians(self.rotation)) #must make more sophisticated to go in direction self.posX += val * math.sin(math.radians(self.rotation)) ## self.wheel1LocZ += val * math.cos(math.radians(self.rotation)) ## self.wheel1LocX += val * math.sin(math.radians(self.rotation)) ## self.wheel2LocZ += val * math.cos(math.radians(self.rotation)) ## self.wheel2LocX += val * math.sin(math.radians(self.rotation)) elif rot == True: self.rotation+= val # cone.py class cone: obj = 0 displayList = 0 posX = 0.0 posY = 0.0 posZ = 0.0 sizeX = 1.0 sizeY = 1.0 sizeZ = 1.0 rotation = 0.0 def __init__(self, x, z): self.obj = ImportObject.ImportedObject("../objects/cone") self.posX = x self.posZ = z def makeDisplayLists(self): self.obj.loadOBJ() self.displayList = glGenLists(1) glNewList(self.displayList, GL_COMPILE) self.obj.drawObject() glEndList() def draw(self): glPushMatrix() glTranslatef(self.posX,self.posY,self.posZ) #glRotatef(self.rotation,0.0,1.0,0.0) glScalef(self.sizeX,self.sizeY,self.sizeZ) glCallList(self.displayList) glPopMatrix() fov = 90.0 nearZ = 0.1 farZ = 100.0 helpWindow = False helpWin = 0 mainWin = 0 centered = False beginTime = 0 countTime = 0 score = 0 finalScore = 0 canStart = False overReason = "" moveSpeed = 20.0 #for wheel spinning tickTime = 0.0 #Frame time(in second) frameTime = 0.0 #creating objects objectArray = [] jeep1Obj = jeep('p') jeep2Obj = jeep('g') jeep3Obj = jeep('r') scene = None star = None starDL = None # Physics a = 2.0 s = 0.0 accumulatedTime = 0.0 allJeeps = [jeep1Obj, jeep2Obj, jeep3Obj] jeepNum = 0 jeepObj = allJeeps[jeepNum] #personObj = person.person(10.0,10.0) #concerned with camera eyeX = 0.0 eyeY = 3.0 eyeZ = -10.0 midDown = False topView = False behindView = True #concerned with panning nowX = 0.0 nowY = 0.0 angle = 0.0 radius = 10.0 phi = 0.0 #concerned with scene development land = 20 gameEnlarge = 10 #concerned with obstacles (cones) & rewards (stars) coneAmount = 15 starAmount = 5 #val = -10 pts diamondAmount = 1 #val = deducts entire by 1/2 # diamondObj = diamond.diamond(random.randint(-land, land), random.randint(10.0, land*gameEnlarge)) usedDiamond = False allcones = [] allstars = [] obstacleCoord = [] rewardCoord = [] ckSense = 5.0 #concerned with lighting#########################!!!!!!!!!!!!!!!!########## applyLighting = True attenuation = 1.0 lightIndex = 0; glLights = [GL_LIGHT0, GL_LIGHT1, GL_LIGHT2, GL_LIGHT3] light0_Ambient = [1.0, 0.0, 0.0, 1.0] light0_Diffuse = [0.75, 0.0, 0.0, 0.0] light0_Position = [-2.0, 2.0, -5.0, 1.0] light0_Intensity = [0.75, 0.0, 0.0, 0.0] ambientColors = [[random.random(), random.random(), random.random(), 1.0], [random.random(), random.random(), random.random(), 1.0], [random.random(), random.random(), random.random(), 1.0]] ambientColors = [[ambientColors[0][j] / 10 for j in range(3)], [ambientColors[1][j] / 10 for j in range(3)], [ambientColors[2][j] / 10 for j in range(3)]] diffuseColors = [[random.random(), random.random(), random.random(), 1.0], [random.random(), random.random(), random.random(), 1.0], [random.random(), random.random(), random.random(), 1.0]] lightPositions = [[-2.0, 2.0, -5.0, 1.0], [2.0, 2.0, 5.0, 1.0], [0.0, 2.0, 1.0, 1.0]] ambientColorIndex = 0 diffuseColorIndex = 0 lightPositionIndex = 0 light1_Ambient = [0.0, 1.0, 0.0, 1.0] light1_Position = [2.0, 2.0, 5.0, 1.0] light1_Diffuse = [0.5, 0.5, 0.0, 1.0] light2_Position = [0.0, 2.0, 1.0, 1.0] light2_Direction = [0.0, -1.0, 0.0, 0.0] light2_Ambient = [1.0, 0.0, 1.0, 1.0] light2_Diffuse = [1.0, 0.0, 1.0, 1.0] light3_Ambient = [0.0, 1.0, 1.0, 1.0] light3_Diffuse = [0.0, 1.0, 1.0, 1.0] matAmbient = [0.5, 0.5, 0.5, 0.5] matDiffuse = [0.5, 0.5, 0.5, 1.0] matSpecular = [0.5, 0.5, 0.5, 1.0] matShininess = 100.0 rotateAngle = 0.0 starRotateAngle = 0.0 starScale = 1.0 GKeyPressed = False filter = 0 fogMode = [GL_EXP, GL_EXP2, GL_LINEAR] fogFileter = 0 fogColor = [0.5, 0.5, 0.5, 1.0] class Actor: def __init__(self): pass #--------------------------------------developing scene--------------- class Scene: axisColor = (0.5, 0.5, 0.5, 0.5) axisXColor = (1.0, 0.0, 0.0, 1.0) axisYColor = (0.0, 1.0, 0.0, 1.0) axisZColor = (0.0, 0.0, 1.0, 1.0) axisLength = 50 # Extends to positive and negative on all axes landColor = (.47, .53, .6, 0.5) #Light Slate Grey landLength = land # Extends to positive and negative on x and y axis landW = 1.0 landH = 0.0 cont = gameEnlarge skybox = Skybox() ufo = None ufoPositionX = -10.0 ufoPosiitonY = 5.0 ufoPositionZ = 0.0 ufoDL = None star = None starPositionX = 0.0 starPositionY = 8.0 starPositionZ = 0.0 starDL = None rotateAngle = 0.0 def __init__(self): self.skybox.init() self.ufo = ImportObject.ImportedObject("../objects/ufo") self.ufo.loadOBJ("../img/") self.ufoDL = glGenLists(1) glNewList(self.ufoDL, GL_COMPILE) self.ufo.drawObject() glEndList() def update(self, frameTime): self.rotateAngle += 15.0 * frameTime def draw(self): # Draw skybox first self.drawSkybox() self.drawAxis() self.drawLand() self.drawUFO() # self.drawStar() def drawAxis(self): # Axis X glColor4f(self.axisXColor[0], self.axisXColor[1], self.axisXColor[2], self.axisXColor[3]) glBegin(GL_LINES) glVertex(0, 0, 0) glVertex(self.axisLength, 0, 0) glEnd() # Axis Y glColor4f(self.axisYColor[0], self.axisYColor[1], self.axisYColor[2], self.axisYColor[3]) glBegin(GL_LINES) glVertex(0, 0, 0) glVertex(0, self.axisLength, 0) glEnd() # Axis Z glColor4f(self.axisZColor[0], self.axisZColor[1], self.axisZColor[2], self.axisZColor[3]) glBegin(GL_LINES) glVertex(0, 0, 0) glVertex(0, 0, -self.axisLength) glEnd() def drawLand(self): glEnable(GL_TEXTURE_2D) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL) glBindTexture(GL_TEXTURE_2D, roadTextureID) glBegin(GL_POLYGON) glTexCoord2f(self.landH, self.landH) glVertex3f(self.landLength, 0, self.cont * self.landLength) glTexCoord2f(self.landH, self.landW) glVertex3f(self.landLength, 0, -self.landLength) glTexCoord2f(self.landW, self.landW) glVertex3f(-self.landLength, 0, -self.landLength) glTexCoord2f(self.landW, self.landH) glVertex3f(-self.landLength, 0, self.cont * self.landLength) glEnd() glDisable(GL_TEXTURE_2D) def drawSkybox(self): self.skybox.createSkybox(0.0, 0.0, 0.0, 10.0, 10.0, 8.0) def drawUFO(self, x = 0.0, y = 0.0, z = 0.0): glPushMatrix() self.ufoPositionX = self.ufoPositionZ * math.sin(math.radians(rotateAngle)) + self.ufoPositionX * math.cos(math.radians(rotateAngle)) self.ufoPositionZ = self.ufoPositionZ * math.cos(math.radians(rotateAngle)) - self.ufoPositionX * math.sin(math.radians(rotateAngle)) glTranslatef(self.ufoPositionX, 10.0, self.ufoPositionZ) glRotatef(self.rotateAngle, 0.0, 1.0, 0.0) glCallList(self.ufoDL) glPopMatrix() def drawStar(self, x = 0.0, y = 0.0, z = 0.0): glPushMatrix() glTranslatef(self.starPositionX, self.starPositionY, self.starPositionZ) glRotatef(self.rotateAngle, 0.0, 1.0, 0.0) glCallList(self.starDL) glPopMatrix() #--------------------------------------populating scene---------------- def staticObjects(): global objectArray, scene scene = Scene() objectArray.append(scene) print("scene appended") def setupLight(index, position, direction, ambient, diffuse): glPushMatrix() glLoadIdentity() gluLookAt(0.0, 3.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) glDisable(GL_LIGHTING) glColor3f(ambient[0] * 10.0, ambient[1] * 10.0, ambient[2] * 10.0) if position != None: glTranslatef(position[0], position[1], position[2]) glutSolidSphere(0.25, 36, 24) if position != None: glTranslatef(-position[0], -position[1], -position[2]) glEnable(GL_LIGHTING) if position != None: glLightfv(glLights[index], GL_POSITION, position) glLightfv(glLights[index], GL_AMBIENT, ambient); glLightfv(glLights[index], GL_DIFFUSE, diffuse); if direction != None: glLightf(glLights[index], GL_SPOT_CUTOFF, 90.0) glLightfv(glLights[index], GL_SPOT_DIRECTION, direction) glLightf(glLights[index], GL_SPOT_EXPONENT, 128.0) glEnable(glLights[index]) # glMaterialfv(GL_FRONT, GL_AMBIENT, matAmbient) # for x in range(1,4): # for z in range(1,4): # matDiffuse = [float(x) * 0.3, float(x) * 0.3, float(x) * 0.3, 1.0] # matSpecular = [float(z) * 0.3, float(z) * 0.3, float(z) * 0.3, 1.0] # matShininess = float(z * z) * 10.0 # ## Set the material diffuse values for the polygon front faces. # glMaterialfv(GL_FRONT, GL_DIFFUSE, matDiffuse) # ## Set the material specular values for the polygon front faces. # glMaterialfv(GL_FRONT, GL_SPECULAR, matSpecular) # ## Set the material shininess value for the polygon front faces. # glMaterialfv(GL_FRONT, GL_SHININESS, matShininess) # ## Draw a glut solid sphere with inputs radius, slices, and stacks # glutSolidSphere(0.25, 72, 64) # glTranslatef(1.0, 0.0, 0.0) # glTranslatef(-3.0, 0.0, 1.0) glPopMatrix() def display(): global jeepObj, canStart, score, beginTime, countTime glClearColor(0.4, 0.6, 0.9, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) if (applyLighting == True): if lightIndex == 0: setupLight(lightIndex, lightPositions[lightPositionIndex], None, ambientColors[ambientColorIndex], diffuseColors[diffuseColorIndex]) elif lightIndex == 1: setupLight(lightIndex, lightPositions[lightPositionIndex], None, ambientColors[ambientColorIndex], diffuseColors[diffuseColorIndex]) elif lightIndex == 2: setupLight(lightIndex, lightPositions[lightPositionIndex], light2_Direction, ambientColors[ambientColorIndex], diffuseColors[diffuseColorIndex]) elif lightIndex == 3: setupLight(lightIndex, None, None, ambientColors[ambientColorIndex], diffuseColors[diffuseColorIndex]) beginTime = 6 - score countTime = score - 6 if (score <= 5): canStart = False glColor3f(1.0,0.0,1.0) text3d("Begins in: " + str(beginTime), jeepObj.posX, jeepObj.posY + 3.0, jeepObj.posZ) elif (score == 6): canStart = True glColor(1.0,0.0,1.0) text3d("GO!", jeepObj.posX, jeepObj.posY + 3.0, jeepObj.posZ) else: canStart = True glColor3f(0.0,1.0,1.0) text3d("Scoring: "+ str(countTime), jeepObj.posX, jeepObj.posY + 3.0, jeepObj.posZ) for obj in objectArray: obj.draw() for cone in allcones: cone.draw() for star in allstars: star.draw() # if (usedDiamond == False): # diamondObj.draw() drawStar(0.0, 8.0, 0.0) jeepObj.draw() jeepObj.drawW1() jeepObj.drawW2() jeepObj.drawLight() #personObj.draw() glutSwapBuffers() def idle():#--------------with more complex display items like turning wheel--- global tickTime, prevTime, score, frameTime, accumulatedTime, rotateAngle, starRotateAngle global lightPositionIndex, lightPositions jeepObj.rotateWheel(-0.1 * tickTime) glutPostRedisplay() x = lightPositions[lightPositionIndex][0] z = lightPositions[lightPositionIndex][2] x = z * math.sin(math.radians(rotateAngle)) + x * math.cos(math.radians(rotateAngle)) z = z * math.cos(math.radians(rotateAngle)) - x * math.sin(math.radians(rotateAngle)) rotateAngle = frameTime * 15.0 lightPositions[lightPositionIndex][0] = x lightPositions[lightPositionIndex][2] = z x = light1_Position[0] z = light1_Position[2] x = z * math.sin(math.radians(rotateAngle)) + x * math.cos(math.radians(rotateAngle)) z = z * math.cos(math.radians(rotateAngle)) - x * math.sin(math.radians(rotateAngle)) light1_Position[0] = x light1_Position[2] = z # light2_Position[2] += 0.01 curTime = glutGet(GLUT_ELAPSED_TIME) tickTime = curTime - prevTime frameTime = tickTime / 1000.0; accumulatedTime += frameTime prevTime = curTime score = curTime/1000 scene.update(frameTime) #---------------------------------setting camera---------------------------- def setView(): global eyeX, eyeY, eyeZ glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(90, aspect, nearZ, farZ) glMatrixMode(GL_MODELVIEW) glLoadIdentity() if (topView == True): gluLookAt(0, 10, land * gameEnlarge / 2, 0, jeepObj.posY, land * gameEnlarge / 2, 0, 1, 0) elif (behindView ==True): gluLookAt(jeepObj.posX, jeepObj.posY + 3.0, jeepObj.posZ - 10.0, jeepObj.posX, jeepObj.posY, jeepObj.posZ, 0, 1, 0) else: gluLookAt(eyeX, eyeY, eyeZ, 0, 0, 0, 0, 1, 0) glutPostRedisplay() def setObjView(): # things to do # realize a view following the jeep # refer to setview glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(90, aspect, nearZ, farZ) glMatrixMode(GL_MODELVIEW) glLoadIdentity() if (topView == True): gluLookAt(0, 10, land * gameEnlarge / 2, 0, jeepObj.posY, land * gameEnlarge / 2, 0, 1, 0) elif (behindView ==True): gluLookAt(jeepObj.posX, jeepObj.posY + 3.0, jeepObj.posZ - 10.0, jeepObj.posX, jeepObj.posY, jeepObj.posZ, 0, 1, 0) glutPostRedisplay() #-------------------------------------------user inputs------------------ def mouseHandle(button, state, x, y): global midDown if (button == GLUT_MIDDLE_BUTTON and state == GLUT_DOWN): midDown = True print("getting pushed") else: midDown = False def motionHandle(x,y): global nowX, nowY, angle, eyeX, eyeY, eyeZ, phi if (midDown == True): pastX = nowX pastY = nowY nowX = x nowY = y if (nowX - pastX > 0): angle -= 0.25 elif (nowX - pastX < 0): angle += 0.25 #elif (nowY - pastY > 0): look into looking over and under object... #phi += 1.0 #elif (nowX - pastY <0): #phi -= 1.0 eyeX = radius * math.sin(angle) eyeZ = radius * math.cos(angle) #eyeY = radius * math.sin(phi) if centered == False: setView() elif centered == True: setObjView() #print eyeX, eyeY, eyeZ, nowX, nowY, radius, angle #print "getting handled" def mouseWheel(button, dir, x, y): global eyeX, eyeY, eyeZ, radius if (dir > 0): #zoom in radius -= 1 #setView() print("zoom in!") elif (dir < 0): #zoom out radius += 1 #setView() print("zoom out!") eyeX = radius * math.sin(angle) eyeZ = radius * math.cos(angle) if centered == False: setView() elif centered == True: setObjView() def specialKeys(keypress, mX, mY): # things to do # this is the function to move the car if keypress == GLUT_KEY_UP: jeepObj.posZ += moveSpeed * frameTime elif keypress == GLUT_KEY_DOWN: jeepObj.posZ -= moveSpeed * frameTime elif keypress == GLUT_KEY_LEFT: jeepObj.posX += moveSpeed * frameTime elif keypress == GLUT_KEY_RIGHT: jeepObj.posX -= moveSpeed * frameTime s = 1 / 2 * a * math.pow(accumulatedTime, 2) jeepObj.posZ += s setObjView() def CreateMenu(): menu = glutCreateMenu(processMenuEvents) glutAddMenuEntry("One", 1) glutAddMenuEntry("Two", 2) glutAttachMenu(GLUT_RIGHT_BUTTON) # Add the following line to fix your code return 0 def processMenuEvents(option): print(option) def changeWindowSize(width, height): global lastWindowWidth global lastWindowHeight global windowWidth global windowHeight lastWindowWidth = windowWidth lastWindowHeight = windowHeight windowWidth = width windowHeight = height glutReshapeWindow(windowWidth, windowHeight) class Menu: def selectMenu(self, choice): # def _exit(): # import sys # sys.exit(0) # { # 1: _exit # }[choice]() global applyLighting global lightIndex global windowWidth global windowHeight global isFullScreen if choice == 1: if applyLighting == True: applyLighting = bool(1 - applyLighting) glDisable(GL_LIGHTING) glDisable(GL_LIGHT0) glDisable(GL_LIGHT1) glDisable(GL_LIGHT2) glDisable(GL_LIGHT3) elif applyLighting == False: applyLighting = bool(1 - applyLighting) glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glEnable(GL_LIGHT1) glEnable(GL_LIGHT2) glEnable(GL_LIGHT3) elif choice == 2: lightIndex = 0 elif choice == 3: lightIndex = 1 elif choice == 4: lightIndex = 2 elif choice == 5: lightIndex = 3 elif choice == 6: changeWindowSize(800, 600) elif choice == 7: changeWindowSize(1280, 720) elif choice == 8: if isFullScreen == False: glutFullScreen() isFullScreen = bool(1 - isFullScreen) elif isFullScreen == True: windowWidth = lastWindowWidth windowHeight = lastWindowHeight glutReshapeWindow(windowWidth, windowHeight) isFullScreen = bool(1 - isFullScreen) return 0 def test(self): pass def ambientColorMenu(self, choice): global ambientColorIndex ambientColorIndex = choice return 0 def diffuseColorMenu(self, choice): global diffuseColorIndex diffuseColorIndex = choice return 0 def lightPositionMenu(self, choice): global lightPositionIndex lightPositionIndex = choice return 0 def createMenu(self): # --- Right-click Menu -------- from ctypes import c_int import platform #platform specific imports: if (platform.system() == 'Windows'): #Windows from ctypes import WINFUNCTYPE CMPFUNCRAW = WINFUNCTYPE(c_int, c_int) # first is return type, then arg types. else: #Linux from ctypes import CFUNCTYPE CMPFUNCRAW = CFUNCTYPE(c_int, c_int) # first is return type, then arg types. callback = CMPFUNCRAW(self.selectMenu) testCallback = CMPFUNCRAW(self.test) ambientColorMenuCallback = CMPFUNCRAW(self.ambientColorMenu) diffuseColorMenuCallback = CMPFUNCRAW(self.diffuseColorMenu) lightPositionMenuCallback = CMPFUNCRAW(self.lightPositionMenu) ambientColorSubMenu = glutCreateMenu(ambientColorMenuCallback) glutAddMenuEntry("Ambient Color 1", 0) glutAddMenuEntry("Ambient Color 2", 1) glutAddMenuEntry("Ambient Color 3", 2) diffuseColorSubMenu = glutCreateMenu(diffuseColorMenuCallback) glutAddMenuEntry("Diffuse Color 1", 0) glutAddMenuEntry("Diffuse Color 2", 1) glutAddMenuEntry("Diffuse Color 3", 2) lightColorSubMenu = glutCreateMenu(lightPositionMenuCallback) glutAddMenuEntry("Light Position 1", 0) glutAddMenuEntry("Light Position 2", 1) glutAddMenuEntry("Light Position 3", 2) ambientColorMenu = glutCreateMenu(testCallback) glutAddSubMenu("Ambient Color", ambientColorSubMenu) glutAddSubMenu("Diffuse Color", diffuseColorSubMenu) glutAddSubMenu("Light Positions", lightColorSubMenu) lightingMenu = glutCreateMenu( callback ) glutAddMenuEntry("Toggle Lighting", 1); # glutAddMenuEntry("Light0", 2) glutAddMenuEntry("Point Light", 3) glutAddMenuEntry("Spot Light", 4) glutAddMenuEntry("Directional Light", 5) glutAddSubMenu("Light Properties", ambientColorMenu) # glutAddMenuEntry("800x600", 6) # glutAddMenuEntry("1280x720", 7) # glutAddMenuEntry("Toggle FullScreen", 8) glutAttachMenu(GLUT_RIGHT_BUTTON); # - def myKeyboard(key, mX, mY): global eyeX, eyeY, eyeZ, angle, radius, helpWindow, centered global helpWin, overReason, topView, behindView, GKeyPressed, starScale global windowWidth, windowHeight, fogFileter, fogMode, starRotateAngle if key == "h": print("h pushed ") + str(helpWindow) winNum = glutGetWindow() if helpWindow == False: helpWindow = True glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH) glutInitWindowSize(500,300) glutInitWindowPosition(600,0) helpWin = glutCreateWindow('Help Guide') glutDisplayFunc(showHelp) glutKeyboardFunc(myKeyboard) glutMainLoop() elif helpWindow == True and winNum!=1: helpWindow = False print(glutGetWindow()) glutHideWindow() glutMainLoop() if key == "r": print(eyeX, eyeY, eyeZ, angle, radius) eyeX = 0.0 eyeY = 2.0 eyeZ = 10.0 angle = 0.0 radius = 10.0 if centered == False: setView() elif centered == True: setObjView() elif key == "h": print("h pushed ") + str(helpWindow) winNum = glutGetWindow() if helpWindow == False: helpWindow = True glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH) glutInitWindowSize(500,300) glutInitWindowPosition(600,0) helpWin = glutCreateWindow('Help Guide') glutDisplayFunc(showHelp) glutKeyboardFunc(stdKey) glutMainLoop() elif helpWindow == True and winNum!=1: helpWindow = False print(glutGetWindow()) glutHideWindow() #glutDestroyWindow(helpWin) glutMainLoop() elif key == "l": print("light triggered!") if jeepObj.lightOn == True: jeepObj.lightOn = False elif jeepObj.lightOn == False: jeepObj.lightOn = True glutPostRedisplay() elif key == "c": if centered == True: centered = False print("non-centered view") elif centered == False: centered = True print("centered view") elif key == "t":#top view, like a map ####################!!!!!! if (topView == True): topView = False elif (topView == False): topView = True if centered == False: setView() elif centered == True: setObjView() elif key == "b": #behind the wheel if (behindView == True): behindView = False elif (behindView == False): behindView = True setView() elif key == "q" and canStart == True: overReason = "You decided to quit!" gameOver() elif key == "x": createSettingDialog() if isFullScreen == True: glutFullScreen(); glutReshapeWindow(windowWidth, windowHeight) glutPostRedisplay() elif key == "f": fogFileter = (fogFileter + 1) % 3 glFogi(GL_FOG_MODE, fogMode[fogFileter]) if behindView == True: if key == "w": jeepObj.posZ += moveSpeed * frameTime setObjView() elif key == "s": jeepObj.posZ -= moveSpeed * frameTime setObjView() elif key == "a": jeepObj.posX += moveSpeed * frameTime setObjView() elif key == "d": jeepObj.posX -= moveSpeed * frameTime setObjView() if key == "1": starRotateAngle += frameTime * 100.0; elif key == "2": starRotateAngle -= frameTime * 100.0 elif key == "3": starScale += 0.1 elif key == "4": starScale -= 0.1 s = 1 / 2 * a * math.pow(accumulatedTime, 2) jeepObj.posZ += s #-------------------------------------------------tools---------------------- def drawTextBitmap(string, x, y): #for writing text to display glRasterPos2f(x, y) for char in string: glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(char)) def text3d(string, x, y, z): glRasterPos3f(x,y,z) for char in string: glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(char)) def drawStar(x = 0.0, y = 0.0, z = 0.0): global starDL, starScale glPushMatrix() glTranslatef(x, y, z) glRotatef(starRotateAngle, 0.0, 1.0, 0.0) glScalef(starScale, starScale, starScale) glCallList(starDL) glPopMatrix() def dist(pt1, pt2): a = pt1[0] b = pt1[1] x = pt2[0] y = pt2[1] return math.sqrt((a-x)**2 + (b-y)**2) def noReshape(newX, newY): #used to ensure program works correctly when resized global windowWidth, windowHeight, aspect windowWidth = newX windowHeight = newY aspect = 1.0 * windowWidth / windowHeight; setView() # 设置视口大小为增个窗口大小 glViewport(0, 0, windowWidth, windowHeight) #--------------------------------------------making game more complex-------- def addCone(x,z): allcones.append(cone(x,z)) obstacleCoord.append((x,z)) def collisionCheck(): global overReason, score, usedDiamond, countTime for obstacle in obstacleCoord: if dist((jeepObj.posX, jeepObj.posZ), obstacle) <= ckSense: overReason = "You hit an obstacle!" gameOver() if (jeepObj.posX >= land or jeepObj.posX <= -land): overReason = "You ran off the road!" gameOver() for reward in rewardCoord: if dist((jeepObj.posX, jeepObj.posZ), reward) <= ckSense: print("Star bonus!") allstars.pop(rewardCoord.index(reward)) rewardCoord.remove(reward) countTime -= 10 if (dist((jeepObj.posX, jeepObj.posZ), (diamondObj.posX, diamondObj.posZ)) <= ckSense and usedDiamond ==False): print("Diamond bonus!") countTime /= 2 usedDiamond = True if (jeepObj.posZ >= land*gameEnlarge): gameSuccess() #----------------------------------multiplayer dev (using tracker)----------- def recordGame(): with open('results.csv', 'wt') as csvfile: spamwriter = csv.writer(csvfile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL) ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') print(st) spamwriter.writerow([st] + [finalScore]) #-------------------------------------developing additional windows/options---- def gameOver(): global finalScore print("Game completed!") finalScore = score-6 #recordGame() #add to excel glutHideWindow() glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH) glutInitWindowSize(200,200) glutInitWindowPosition(600,100) overWin = glutCreateWindow("Game Over!") glutDisplayFunc(overScreen) glutMainLoop() def gameSuccess(): global finalScore print("Game success!") finalScore = score-6 #recordGame() #add to excel glutHideWindow() glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH) glutInitWindowSize(200,200) glutInitWindowPosition(600,100) overWin = glutCreateWindow("Complete!") glutDisplayFunc(winScreen) glutMainLoop() def winScreen(): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glColor3f(0.0,1.0,0.0) drawTextBitmap("Completed Trial!" , -0.6, 0.85) glColor3f(0.0,1.0,0.0) drawTextBitmap("Your score is: ", -1.0, 0.0) glColor3f(1.0,1.0,1.0) drawTextBitmap(str(finalScore), -1.0, -0.15) glutSwapBuffers() def overScreen(): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glColor3f(1.0,0.0,1.0) drawTextBitmap("Incomplete Trial" , -0.6, 0.85) glColor3f(0.0,1.0,0.0) drawTextBitmap("Because you..." , -1.0, 0.5) glColor3f(1.0,1.0,1.0) drawTextBitmap(overReason, -1.0, 0.35) glColor3f(0.0,1.0,0.0) drawTextBitmap("Your score stopped at: ", -1.0, 0.0) glColor3f(1.0,1.0,1.0) drawTextBitmap(str(finalScore), -1.0, -0.15) glutSwapBuffers() def showHelp(): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glColor3f(1.0,0.0,0.0) drawTextBitmap("Help Guide" , -0.2, 0.85) glColor3f(0.0,0.0,1.0) drawTextBitmap(" 1.Use W/S/A/D to move the car, the camera will follow." , -1.0, 0.7) drawTextBitmap(" 2.Press 'B' will switch to orbit camera mode." , -1.0, 0.5) drawTextBitmap(" 3.Press the middle mouse button and move can fly around the car.", -1.0, 0.3) drawTextBitmap(" (1).Mouse wheel used to change fov(zoom in / out)." , -1.0, 0.1) drawTextBitmap(" (2).Number keys 1, 2 used to rotate the star." , -1.0, -0.1) drawTextBitmap(" 4.Number keys 3, 4 used to scale the star." , -1.0, -0.3) drawTextBitmap(" 5.Right click in the viewport to fire up light setting memnu." , -1.0, -0.5) drawTextBitmap(" 6.Press \"X\" fire up resolution setting window." , -1.0, -0.7) glutSwapBuffers() def loadSceneTextures(): global roadTextureID roadTextureID = loadTexture("../img/road2.png") # roadTextureID = utils.loadTexture("../img/sunset_posX.bmp") #-----------------------------------------------lighting work-------------- def initializeLight(): glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glEnable(GL_DEPTH_TEST) glClearDepth(1.0); glDepthFunc(GL_LEQUAL) glEnable(GL_NORMALIZE) #~~~~~~~~~~~~~~~~~~~~~~~~~the finale!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def initFog(): glFogi(GL_FOG_MODE, fogMode[fogFileter]) glFogfv(GL_FOG_COLOR, fogColor) glFogf(GL_FOG_DENSITY, 0.35) glHint(GL_FOG_HINT, GL_DONT_CARE) glFogf(GL_FOG_START, 1.0) glFogf(GL_FOG_END, 5.0) glEnable(GL_FOG) def createSettingDialog(): settingDialog = SettingDialog() #生成对话框实例对象 settingDialog. DoModal() #创建对话框 def main(): glutInit() global prevTime, mainWin, displayList, star, starDL global lastWindowWidth, lastWindowHeight prevTime = glutGet(GLUT_ELAPSED_TIME) glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH) createSettingDialog() # things to do # change the window resolution in the game glutInitWindowSize(windowWidth, windowHeight) lastWindowWidth = windowWidth lastWindowHeight = windowHeight; screenWidth = glutGet(GLUT_SCREEN_WIDTH) screenHeight = glutGet(GLUT_SCREEN_HEIGHT) glutInitWindowPosition((screenWidth - windowWidth) / 2, (screenHeight - windowHeight) / 2) mainWin = glutCreateWindow('CS4182') if isFullScreen == True: glutFullScreen() glutDisplayFunc(display) glutIdleFunc(idle)#wheel turn glEnable(GL_DEPTH_TEST) glutMouseFunc(mouseHandle) glutMotionFunc(motionHandle) glutMouseWheelFunc(mouseWheel) glutSpecialFunc(specialKeys) glutKeyboardFunc(myKeyboard) glutReshapeFunc(noReshape) # things to do # add a menu loadSceneTextures() jeep1Obj.makeDisplayLists() jeep2Obj.makeDisplayLists() jeep3Obj.makeDisplayLists() #personObj.makeDisplayLists() # things to do # add a automatic object for i in range(coneAmount):#create cones randomly for obstacles, making sure to give a little lag time in beginning by adding 10.0 buffer addCone(random.randint(-land, land), random.randint(10.0, land*gameEnlarge)) # things to do # add stars for cone in allcones: cone.makeDisplayLists() for star in allstars: star.makeDisplayLists() star = ImportObject.ImportedObject("../objects/starR") star.loadOBJ("../img/") starDL = glGenLists(1) glNewList(starDL, GL_COMPILE) star.drawObject() glEndList() # initFog() # CreateMenu() menu = Menu() menu.createMenu() # diamondObj.makeDisplayLists() staticObjects() if (applyLighting == True): initializeLight() glutMainLoop() main() <file_sep> #*-coding: utf-8-*- #file: Dialog.py # import win32ui #导入win32ui模块 import win32con #导入win32con模块 from pywin. mfc import dialog #从 pywin.mfc导入 dialog class MyDialog(dialog. Dialog): # 通过继承dialog Dialog生成对话框类 def OnInitDialog(self): #重载对话框初始化方法 dialog.Dialog.OnInitDialog(self) #调用父类的对话框初始化方法 self.edit = self.GetDlgItem(13) def OnOK(self): #重载OnOK方法 win32ui.MessageBox('Press', 'Python', win32con.MB_OK) print(self.edit.GetWindowText()) self.EndDialog(1) def OnCancel(self):#重载OnCancel方法 win32ui. MessageBox('Press Cancel', 'Python'. win32con.MB_OK) self.EndDialog() style = (win32con.DS_MODALFRAME | #定义对话框样式 win32con.WS_POPUP | win32con.WS_VISIBLE | win32con.WS_CAPTION | win32con.WS_SYSMENU | win32con.DS_SETFONT) childstyle =(win32con. WS_CHILD | #定义控件样式 win32con.WS_VISIBLE) buttonstyle = win32con.WS_TABSTOP | childstyle di = ['Python', (0, 0, 200, 90), style, None,(8, "MS Sans Serif")] ButoK =(['Button', #设置OK按钮属性 "OK", win32con.IDOK, (50, 50, 50, 14), buttonstyle | win32con.BS_PUSHBUTTON]) ButCancel =(['Button', #设置Cancel按钮属性 "Cancel", win32con.IDCANCEL, (110, 50, 50, 14), buttonstyle | win32con.BS_PUSHBUTTON]) Stadic =(['Static', #设置标签属性 'Resolution:', 12, (10, 30, 60, 14), childstyle]) Width =(['Edit', #设置文本框属性 '1280', 13, (50, 30, 50, 14), childstyle | win32con.ES_LEFT | win32con.WS_BORDER | win32con.WS_TABSTOP]) Height =(['Edit', #设置文本框属性 '720', 14, (110, 30, 50, 14), childstyle | win32con.ES_LEFT | win32con.WS_BORDER | win32con.WS_TABSTOP]) init = [] #初始化信息列表 init.append(di) init.append(ButoK) init.append(ButCancel) init.append(Stadic) init.append(Width) init.append(Height) mydialog = MyDialog(init) #生成对话框实例对象 mydialog. DoModal() #创建对话框<file_sep>Django==1.11.29 image==1.5.32 Pillow==6.2.2 pytz==2020.1 six==1.15.0 appdirs==1.4.4 certifi==2016.2.28 django==1.11.29 enum==0.4.7 glm==0.4.3 image 1.5.32 numpy==1.16.6 packaging==20.9 pip==9.0.1 pyopengl==3.1.5 pyopengl-accelerate==3.1.5 pyparsing==2.4.7 pypiwin32==223 python==2.7.13 pytz==2020.1 pywin32==228 setuptools==36.4.0 vc==9 vs2008_runtime==9.00.30729.5054 wheel==0.29.0 wincertstore==0.2<file_sep>from enum import Enum import glm import numpy as np from keyboard import keys from OpenGL.GLUT import * class CAMERA_MOVEMENT(Enum): FORWARD = 1 BACKWARD = 2 LEFT = 3 RIGHT = 4 class Camera3D(): def __init__(self, position=glm.vec3(0.0, 0.0, 0.0), up=glm.vec3(0.0, 1.0, 0.0), yaw=-90, pitch=0, front=glm.vec3(0.0, 0.0, -1.0), movement_speed=50, mouse_sensitivity=0.1, zoom=45.0): self.position = position self.world_up = up self.yaw = yaw self.pitch = pitch self.front = front self.movement_speed = movement_speed self.mouse_sensitivity = mouse_sensitivity self.zoom = zoom self.__update_camera_vectors() def get_view_matrix(self): return glm.lookAt(self.position, self.position + self.front, self.world_up) def process_keyboard(self, delta_time): if keys["escape"]: glutLeaveMainLoop() if keys["w"]: self.__process_keyboard(CAMERA_MOVEMENT.FORWARD, delta_time) if keys["s"]: self.__process_keyboard(CAMERA_MOVEMENT.BACKWARD, delta_time) if keys["a"]: self.__process_keyboard(CAMERA_MOVEMENT.LEFT, delta_time) if keys["d"]: self.__process_keyboard(CAMERA_MOVEMENT.RIGHT, delta_time) def __process_keyboard(self, direction, deltaTime): velocity = self.movement_speed * deltaTime if direction == CAMERA_MOVEMENT.FORWARD: self.position += self.front * velocity if direction == CAMERA_MOVEMENT.BACKWARD: self.position -= self.front * velocity if direction == CAMERA_MOVEMENT.LEFT: self.position -= self.right * velocity if direction == CAMERA_MOVEMENT.RIGHT: self.position += self.right * velocity def process_mouse_movement(self, x_offset, y_offset, constrain_pitch=True): x_offset *= self.mouse_sensitivity y_offset *= self.mouse_sensitivity self.yaw += x_offset self.pitch += y_offset # if constrain_pitch: # if self.pitch > 89.0: # self.pitch = 89.0 # if self.pitch < -89.0: # self.pitch = -89.0 self.__update_camera_vectors() def process_mouse_scroll(self, y_offset): if self.zoom >= 1.0 and self.zoom <= 45.0: self.zoom -= y_offset if self.zoom <= 1.0: self.zoom = 1.0 if self.zoom >= 45.0: self.zoom = 45.0 def __update_camera_vectors(self): front = glm.vec3(0) front.x = np.cos(glm.radians(self.yaw)) * np.cos(glm.radians(self.pitch)) front.y = np.sin(glm.radians(self.pitch)) front.z = np.sin(glm.radians(self.yaw)) * np.cos(glm.radians(self.pitch)) self.front = glm.normalize(front) self.right = glm.normalize(glm.cross(self.front, self.world_up)) <file_sep>from OpenGL.GL import * import PIL.Image as Image import utils # Skybox class class Skybox: textureIDs = [] MAP_WIDTH = 16 CELL_WIDTH = 16 MAP = MAP_WIDTH * CELL_WIDTH / 2 def __init__(self): pass def init(self): # back, front, bottom, top, left, right textureNames = ["sunset_negZ.bmp", "sunset_posZ.bmp", "sunset_negY.bmp", "sunset_posY.bmp", "sunset_negX.bmp", "sunset_posX.bmp"] for i in range(6): textureID = utils.loadTexture("../img/" + textureNames[i]) self.textureIDs.append(textureID) def createSkybox(self, x, y, z, boxWidth, boxHeight, boxDepth): # Abtain lighting status lighing = glGetBooleanv(GL_LIGHTING) # Calculate width, height, depth of skybox width = self.MAP * boxWidth / 8 height = self.MAP * boxHeight / 8 depth = self.MAP * boxDepth / 8 # Calculate skybox center x = x + self.MAP / 8 - width / 2 y = y + self.MAP / 24 - height / 2 z = z + self.MAP / 8 - depth / 2 # Disable lighting glDisable(GL_LIGHTING) # glCullFace(GL_FRONT) glDepthMask(GL_FALSE) glPushMatrix() glLoadIdentity() glTranslatef(0, 0, 0) glEnable(GL_TEXTURE_2D) # Draw back glBindTexture(GL_TEXTURE_2D, self.textureIDs[0]) glBegin(GL_QUADS) # Assign texture coordinates and vertex positions glTexCoord2f(0.0, 0.0) glVertex3f(x + width, y, z) glTexCoord2f(0.0, 1.0) glVertex3f(x + width, y + height, z) glTexCoord2f(1.0, 1.0) glVertex3f(x, y + height, z) glTexCoord2f(1.0, 0.0) glVertex3f(x, y, z) glEnd() # Draw front glBindTexture(GL_TEXTURE_2D, self.textureIDs[1]) glBegin(GL_QUADS) # Assign texture coordinates and vertex positions glTexCoord2f(0.0, 0.0) glVertex3f(x, y, z + depth) glTexCoord2f(0.0, 1.0) glVertex3f(x, y + height, z + depth) glTexCoord2f(1.0, 1.0) glVertex3f(x + width, y + height, z + depth) glTexCoord2f(1.0, 0.0) glVertex3f(x + width, y, z + depth) glEnd() # Draw bottom glBindTexture(GL_TEXTURE_2D, self.textureIDs[2]) glBegin(GL_QUADS) # Assign texture coordinates and vertex positions glTexCoord2f(0.0, 0.0) glVertex3f(x, y, z) glTexCoord2f(0.0, 1.0) glVertex3f(x, y, z + depth) glTexCoord2f(1.0, 1.0) glVertex3f(x + width, y, z + depth) glTexCoord2f(1.0, 0.0) glVertex3f(x + width, y, z) glEnd() # Draw top glBindTexture(GL_TEXTURE_2D, self.textureIDs[3]) glBegin(GL_QUADS) # Assign texture coordinates and vertex positions glTexCoord2f(1.0, 1.0) glVertex3f(x + width, y + height, z) glTexCoord2f(1.0, 0.0) glVertex3f(x + width, y + height, z + depth) glTexCoord2f(0.0, 0.0) glVertex3f(x, y + height, z + depth) glTexCoord2f(0.0, 1.0) glVertex3f(x, y + height, z) glEnd() # Draw left glBindTexture(GL_TEXTURE_2D, self.textureIDs[4]) glBegin(GL_QUADS) # Assign texture coordinates and vertex positions glTexCoord2f(0.0, 1.0) glVertex3f(x, y + height, z) glTexCoord2f(1.0, 1.0) glVertex3f(x, y + height, z + depth) glTexCoord2f(1.0, 0.0) glVertex3f(x, y, z + depth) glTexCoord2f(0.0, 0.0) glVertex3f(x, y, z) glEnd() # Draw right glBindTexture(GL_TEXTURE_2D, self.textureIDs[5]) glBegin(GL_QUADS) # Assign texture coordinates and vertex positions glTexCoord2f(1.0, 0.0) glVertex3f(x + width, y, z) glTexCoord2f(0.0, 0.0) glVertex3f(x + width, y, z + depth) glTexCoord2f(0.0, 1.0) glVertex3f(x + width, y + height, z + depth) glTexCoord2f(1.0, 1.0) glVertex3f(x + width, y + height, z) glEnd() glPopMatrix() if lighing == GL_TRUE: glEnable(GL_LIGHTING) glDisable(GL_TEXTURE_2D) glDepthMask(GL_TRUE) # glCullFace(GL_BACK) <file_sep>from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * import math, time import ImportObject class jeep: obj = 0 displayList = 0 wheel1DL = 0 wheel2DL = 0 dimDL = 0 litDL = 0 dimL = 0 litL = 0 lightOn = False wheel1 = 0 wheel2 = 0 wheelTurn = 0.0 revWheelTurn = 360.0 #allWheels=[wheel1,wheel2] wheelDir = 'stop' posX = 0.0 posY = 1.75 posZ = 0.0 ## wheel1LocX =0 ## wheel1LocZ = 0 ## wheel2LocX = 0 ## wheel2LocZ = 0 sizeX = 1.0 sizeY = 1.0 sizeZ = 1.0 rotation = 0.0 def __init__(self, color): if (color == 'p'): self.obj = ImportObject.ImportedObject("../objects/jeepbare") elif (color == 'g'): self.obj = ImportObject.ImportedObject("../objects/jeepbare2") elif (color == 'r'): self.obj = ImportObject.ImportedObject("../objects/jeepbare3") self.wheel1 = ImportObject.ImportedObject("../objects/frontwheel") self.wheel2 = ImportObject.ImportedObject("../objects/backwheel") self.dimL = ImportObject.ImportedObject("../objects/dimlight") self.litL = ImportObject.ImportedObject("../objects/litlight") def makeDisplayLists(self): self.obj.loadOBJ() self.wheel1.loadOBJ() self.wheel2.loadOBJ() self.dimL.loadOBJ() self.litL.loadOBJ() self.displayList = glGenLists(1) glNewList(self.displayList, GL_COMPILE) self.obj.drawObject() glEndList() self.wheel1DL = glGenLists(1) glNewList(self.wheel1DL, GL_COMPILE) self.wheel1.drawObject() glEndList() self.wheel2DL = glGenLists(1) glNewList(self.wheel2DL, GL_COMPILE) self.wheel2.drawObject() glEndList() self.dimDL = glGenLists(1) glNewList(self.dimDL, GL_COMPILE) self.dimL.drawObject() glEndList() self.litDL = glGenLists(1) glNewList(self.litDL, GL_COMPILE) self.litL.drawObject() glEndList() def draw(self): glPushMatrix() glTranslatef(self.posX,self.posY,self.posZ) glRotatef(self.rotation,0.0,1.0,0.0) glScalef(self.sizeX,self.sizeY,self.sizeZ) glCallList(self.displayList) glPopMatrix() def drawW1(self): glPushMatrix() glTranslatef(self.posX, self.posY-1.3146, self.posZ) glRotatef(self.rotation,0.0,1.0,0.0) glTranslatef(0.0, self.posY-1.3146, 2.9845) glScalef(self.sizeX, self.sizeY, self.sizeZ) if self.wheelDir == 'fwd': glRotatef(self.revWheelTurn,1.0,0.0,0.0) elif self.wheelDir == 'back': glRotatef(self.wheelTurn,1.0,0.0,0.0) glTranslatef(0.0,1.3146,-2.9845) glCallList(self.wheel1DL) glPopMatrix() def drawW2(self): glPushMatrix() glTranslatef(self.posX, self.posY-1.3146, self.posZ) glRotatef(self.rotation,0.0,1.0,0.0) glTranslatef(0.0, self.posY-1.3146, -2.9845) glScalef(self.sizeX, self.sizeY, self.sizeZ) if self.wheelDir == 'fwd': glRotatef(self.revWheelTurn,1.0,0.0,0.0) elif self.wheelDir == 'back': glRotatef(self.wheelTurn,1.0,0.0,0.0) glTranslatef(0.0,1.3146,3.3) glCallList(self.wheel2DL) glPopMatrix() def rotateWheel(self, newTheta): global wheelTurn self.wheelTurn = self.wheelTurn + newTheta self.wheelTurn = self.wheelTurn % 360 self.revWheelTurn = 360 - self.wheelTurn def adrawLight(self): glPushMatrix() glTranslatef(self.posX, self.posY, self.posZ) glRotatef(self.rotation,0.0,1.0,0.0) glScalef(self.sizeX, self.sizeY, self.sizeZ) if self.lightOn == True: glCallList(self.litDL) elif self.lightOn == False: glCallList(self.dimDL) glPopMatrix() def move(self, rot, val): if rot == False: self.posZ += val * math.cos(math.radians(self.rotation)) #must make more sophisticated to go in direction self.posX += val * math.sin(math.radians(self.rotation)) ## self.wheel1LocZ += val * math.cos(math.radians(self.rotation)) ## self.wheel1LocX += val * math.sin(math.radians(self.rotation)) ## self.wheel2LocZ += val * math.cos(math.radians(self.rotation)) ## self.wheel2LocX += val * math.sin(math.radians(self.rotation)) elif rot == True: self.rotation+= val <file_sep>from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * import math, time import ImportObject class cone: obj = 0 displayList = 0 posX = 0.0 posY = 0.0 posZ = 0.0 sizeX = 1.0 sizeY = 1.0 sizeZ = 1.0 rotation = 0.0 def __init__(self, x, z): self.obj = ImportObject.ImportedObject("../objects/cone") self.posX = x self.posZ = z def makeDisplayLists(self): self.obj.loadOBJ() self.displayList = glGenLists(1) glNewList(self.displayList, GL_COMPILE) self.obj.drawObject() glEndList() def draw(self): glPushMatrix() glTranslatef(self.posX,self.posY,self.posZ) #glRotatef(self.rotation,0.0,1.0,0.0) glScalef(self.sizeX,self.sizeY,self.sizeZ) glCallList(self.displayList) glPopMatrix() <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*-‘ from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * import math, time, random, csv, datetime import ImportObject import PIL.Image as Image import jeep, cone, utils from skybox import * import math windowWidth = 800 windowHeight = 600 lastWindowWidth = 0 lastWindowHeight = 0 isFullScreen = False aspect = float(windowWidth) / windowHeight; fov = 90.0 nearZ = 0.1 farZ = 100.0 helpWindow = False helpWin = 0 mainWin = 0 centered = False beginTime = 0 countTime = 0 score = 0 finalScore = 0 canStart = False overReason = "" moveSpeed = 20.0 #for wheel spinning tickTime = 0.0 #Frame time(in second) frameTime = 0.0 #creating objects objectArray = [] jeep1Obj = jeep.jeep('p') jeep2Obj = jeep.jeep('g') jeep3Obj = jeep.jeep('r') scene = None star = None starDL = None # Physics a = 2.0 s = 0.0 accumulatedTime = 0.0 allJeeps = [jeep1Obj, jeep2Obj, jeep3Obj] jeepNum = 0 jeepObj = allJeeps[jeepNum] #personObj = person.person(10.0,10.0) #concerned with camera eyeX = 0.0 eyeY = 3.0 eyeZ = -10.0 midDown = False topView = False behindView = True #concerned with panning nowX = 0.0 nowY = 0.0 angle = 0.0 radius = 10.0 phi = 0.0 #concerned with scene development land = 20 gameEnlarge = 10 #concerned with obstacles (cones) & rewards (stars) coneAmount = 15 starAmount = 5 #val = -10 pts diamondAmount = 1 #val = deducts entire by 1/2 # diamondObj = diamond.diamond(random.randint(-land, land), random.randint(10.0, land*gameEnlarge)) usedDiamond = False allcones = [] allstars = [] obstacleCoord = [] rewardCoord = [] ckSense = 5.0 #concerned with lighting#########################!!!!!!!!!!!!!!!!########## applyLighting = True attenuation = 1.0 lightIndex = 0; glLights = [GL_LIGHT0, GL_LIGHT1, GL_LIGHT2] light0_Position = [-2.0, 2.0, -5.0, 1.0] light0_Intensity = [0.75, 0.0, 0.0, 0.0] light1_Position = [2.0, 2.0, 5.0, 1.0] light1_Intensity = [0.5, 0.5, 0.0, 1.0] light2_Position = [0.0, 2.0, 1.0, 1.0] light2_Direction = [0.0, -1.0, 0.0, 0.0] light2_Ambient = [1.0, 0.0, 1.0, 1.0] light2_Diffuse = [1.0, 0.0, 1.0, 1.0] matAmbient = [0.5, 0.5, 0.5, 0.5] matDiffuse = [0.5, 0.5, 0.5, 1.0] matSpecular = [0.5, 0.5, 0.5, 1.0] matShininess = 100.0 rotateAngle = 0.0 starRotateAngle = 0.0 starScale = 1.0 GKeyPressed = False filter = 0 fogMode = [GL_EXP, GL_EXP2, GL_LINEAR] fogFileter = 0 fogColor = [0.5, 0.5, 0.5, 1.0] class Actor: def __init__(self): pass #--------------------------------------developing scene--------------- class Scene: axisColor = (0.5, 0.5, 0.5, 0.5) axisXColor = (1.0, 0.0, 0.0, 1.0) axisYColor = (0.0, 1.0, 0.0, 1.0) axisZColor = (0.0, 0.0, 1.0, 1.0) axisLength = 50 # Extends to positive and negative on all axes landColor = (.47, .53, .6, 0.5) #Light Slate Grey landLength = land # Extends to positive and negative on x and y axis landW = 1.0 landH = 0.0 cont = gameEnlarge skybox = Skybox() ufo = None ufoPositionX = -10.0 ufoPosiitonY = 5.0 ufoPositionZ = 0.0 ufoDL = None star = None starPositionX = 0.0 starPositionY = 8.0 starPositionZ = 0.0 starDL = None rotateAngle = 0.0 def __init__(self): self.skybox.init() self.ufo = ImportObject.ImportedObject("../objects/ufo") self.ufo.loadOBJ("../img/") self.ufoDL = glGenLists(1) glNewList(self.ufoDL, GL_COMPILE) self.ufo.drawObject() glEndList() def update(self, frameTime): self.rotateAngle += 15.0 * frameTime def draw(self): # Draw skybox first self.drawSkybox() self.drawAxis() self.drawLand() self.drawUFO() # self.drawStar() def drawAxis(self): # Axis X glColor4f(self.axisXColor[0], self.axisXColor[1], self.axisXColor[2], self.axisXColor[3]) glBegin(GL_LINES) glVertex(0, 0, 0) glVertex(self.axisLength, 0, 0) glEnd() # Axis Y glColor4f(self.axisYColor[0], self.axisYColor[1], self.axisYColor[2], self.axisYColor[3]) glBegin(GL_LINES) glVertex(0, 0, 0) glVertex(0, self.axisLength, 0) glEnd() # Axis Z glColor4f(self.axisZColor[0], self.axisZColor[1], self.axisZColor[2], self.axisZColor[3]) glBegin(GL_LINES) glVertex(0, 0, 0) glVertex(0, 0, -self.axisLength) glEnd() def drawLand(self): glEnable(GL_TEXTURE_2D) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL) glBindTexture(GL_TEXTURE_2D, roadTextureID) glBegin(GL_POLYGON) glTexCoord2f(self.landH, self.landH) glVertex3f(self.landLength, 0, self.cont * self.landLength) glTexCoord2f(self.landH, self.landW) glVertex3f(self.landLength, 0, -self.landLength) glTexCoord2f(self.landW, self.landW) glVertex3f(-self.landLength, 0, -self.landLength) glTexCoord2f(self.landW, self.landH) glVertex3f(-self.landLength, 0, self.cont * self.landLength) glEnd() glDisable(GL_TEXTURE_2D) def drawSkybox(self): self.skybox.createSkybox(0.0, 0.0, 0.0, 10.0, 10.0, 8.0) def drawUFO(self, x = 0.0, y = 0.0, z = 0.0): glPushMatrix() self.ufoPositionX = self.ufoPositionZ * math.sin(math.radians(rotateAngle)) + self.ufoPositionX * math.cos(math.radians(rotateAngle)) self.ufoPositionZ = self.ufoPositionZ * math.cos(math.radians(rotateAngle)) - self.ufoPositionX * math.sin(math.radians(rotateAngle)) glTranslatef(self.ufoPositionX, 10.0, self.ufoPositionZ) glRotatef(self.rotateAngle, 0.0, 1.0, 0.0) glCallList(self.ufoDL) glPopMatrix() def drawStar(self, x = 0.0, y = 0.0, z = 0.0): glPushMatrix() glTranslatef(self.starPositionX, self.starPositionY, self.starPositionZ) glRotatef(self.rotateAngle, 0.0, 1.0, 0.0) glCallList(self.starDL) glPopMatrix() #--------------------------------------populating scene---------------- def staticObjects(): global objectArray, scene scene = Scene() objectArray.append(scene) print("scene appended") def setupLight(index, position, direction, intensity): glPushMatrix() glLoadIdentity() gluLookAt(0.0, 3.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) glDisable(GL_LIGHTING) glColor3f(intensity[0], intensity[1], intensity[2]) glTranslatef(position[0], position[1], position[2]) glutSolidSphere(0.25, 36, 24) glTranslatef(-position[0], -position[1], -position[2]) glEnable(GL_LIGHTING) glDisable(GL_LIGHTING) glLightfv(glLights[index], GL_POSITION, position) glLightfv(glLights[index], GL_DIFFUSE, intensity); if index == 2: glLightfv(glLights[index], GL_AMBIENT, intensity); glLightfv(glLights[index], GL_DIFFUSE, intensity); glLightf(glLights[index], GL_SPOT_CUTOFF, 90.0) glLightfv(glLights[index], GL_SPOT_DIRECTION, direction) glLightf(glLights[index], GL_SPOT_EXPONENT, 128.0) glEnable(GL_LIGHTING) glEnable(glLights[index]) # glMaterialfv(GL_FRONT, GL_AMBIENT, matAmbient) # for x in range(1,4): # for z in range(1,4): # matDiffuse = [float(x) * 0.3, float(x) * 0.3, float(x) * 0.3, 1.0] # matSpecular = [float(z) * 0.3, float(z) * 0.3, float(z) * 0.3, 1.0] # matShininess = float(z * z) * 10.0 # ## Set the material diffuse values for the polygon front faces. # glMaterialfv(GL_FRONT, GL_DIFFUSE, matDiffuse) # ## Set the material specular values for the polygon front faces. # glMaterialfv(GL_FRONT, GL_SPECULAR, matSpecular) # ## Set the material shininess value for the polygon front faces. # glMaterialfv(GL_FRONT, GL_SHININESS, matShininess) # ## Draw a glut solid sphere with inputs radius, slices, and stacks # glutSolidSphere(0.25, 72, 64) # glTranslatef(1.0, 0.0, 0.0) # glTranslatef(-3.0, 0.0, 1.0) glPopMatrix() def display(): global jeepObj, canStart, score, beginTime, countTime glClearColor(0.4, 0.6, 0.9, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) if (applyLighting == True): if lightIndex == 0: setupLight(lightIndex, light0_Position, light2_Direction, light0_Intensity) elif lightIndex == 1: setupLight(lightIndex, light1_Position, light2_Direction, light1_Intensity) elif lightIndex == 2: setupLight(lightIndex, light2_Position, light2_Direction, light2_Diffuse) beginTime = 6 - score countTime = score - 6 if (score <= 5): canStart = False glColor3f(1.0,0.0,1.0) text3d("Begins in: " + str(beginTime), jeepObj.posX, jeepObj.posY + 3.0, jeepObj.posZ) elif (score == 6): canStart = True glColor(1.0,0.0,1.0) text3d("GO!", jeepObj.posX, jeepObj.posY + 3.0, jeepObj.posZ) else: canStart = True glColor3f(0.0,1.0,1.0) text3d("Scoring: "+ str(countTime), jeepObj.posX, jeepObj.posY + 3.0, jeepObj.posZ) for obj in objectArray: obj.draw() for cone in allcones: cone.draw() for star in allstars: star.draw() # if (usedDiamond == False): # diamondObj.draw() drawStar(0.0, 8.0, 0.0) jeepObj.draw() jeepObj.drawW1() jeepObj.drawW2() #jeepObj.drawLight() #personObj.draw() glutSwapBuffers() def idle():#--------------with more complex display items like turning wheel--- global tickTime, prevTime, score, frameTime, accumulatedTime, rotateAngle, starRotateAngle jeepObj.rotateWheel(-0.1 * tickTime) glutPostRedisplay() x = light0_Position[0] z = light0_Position[2] x = z * math.sin(math.radians(rotateAngle)) + x * math.cos(math.radians(rotateAngle)) z = z * math.cos(math.radians(rotateAngle)) - x * math.sin(math.radians(rotateAngle)) rotateAngle = frameTime * 15.0 light0_Position[0] = x light0_Position[2] = z x = light1_Position[0] z = light1_Position[2] x = z * math.sin(math.radians(rotateAngle)) + x * math.cos(math.radians(rotateAngle)) z = z * math.cos(math.radians(rotateAngle)) - x * math.sin(math.radians(rotateAngle)) light1_Position[0] = x light1_Position[2] = z # light2_Position[2] += 0.01 curTime = glutGet(GLUT_ELAPSED_TIME) tickTime = curTime - prevTime frameTime = tickTime / 1000.0; accumulatedTime += frameTime prevTime = curTime score = curTime/1000 scene.update(frameTime) #---------------------------------setting camera---------------------------- def setView(): global eyeX, eyeY, eyeZ glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(90, aspect, nearZ, farZ) glMatrixMode(GL_MODELVIEW) glLoadIdentity() if (topView == True): gluLookAt(0, 10, land * gameEnlarge / 2, 0, jeepObj.posY, land * gameEnlarge / 2, 0, 1, 0) elif (behindView ==True): gluLookAt(jeepObj.posX, jeepObj.posY + 3.0, jeepObj.posZ - 10.0, jeepObj.posX, jeepObj.posY, jeepObj.posZ, 0, 1, 0) else: gluLookAt(eyeX, eyeY, eyeZ, 0, 0, 0, 0, 1, 0) glutPostRedisplay() def setObjView(): # things to do # realize a view following the jeep # refer to setview glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(90, aspect, nearZ, farZ) glMatrixMode(GL_MODELVIEW) glLoadIdentity() if (topView == True): gluLookAt(0, 10, land * gameEnlarge / 2, 0, jeepObj.posY, land * gameEnlarge / 2, 0, 1, 0) elif (behindView ==True): gluLookAt(jeepObj.posX, jeepObj.posY + 3.0, jeepObj.posZ - 10.0, jeepObj.posX, jeepObj.posY, jeepObj.posZ, 0, 1, 0) glutPostRedisplay() #-------------------------------------------user inputs------------------ def mouseHandle(button, state, x, y): global midDown if (button == GLUT_MIDDLE_BUTTON and state == GLUT_DOWN): midDown = True print("getting pushed") else: midDown = False def motionHandle(x,y): global nowX, nowY, angle, eyeX, eyeY, eyeZ, phi if (midDown == True): pastX = nowX pastY = nowY nowX = x nowY = y if (nowX - pastX > 0): angle -= 0.25 elif (nowX - pastX < 0): angle += 0.25 #elif (nowY - pastY > 0): look into looking over and under object... #phi += 1.0 #elif (nowX - pastY <0): #phi -= 1.0 eyeX = radius * math.sin(angle) eyeZ = radius * math.cos(angle) #eyeY = radius * math.sin(phi) if centered == False: setView() elif centered == True: setObjView() #print eyeX, eyeY, eyeZ, nowX, nowY, radius, angle #print "getting handled" def mouseWheel(button, dir, x, y): global eyeX, eyeY, eyeZ, radius if (dir > 0): #zoom in radius -= 1 #setView() print("zoom in!") elif (dir < 0): #zoom out radius += 1 #setView() print("zoom out!") eyeX = radius * math.sin(angle) eyeZ = radius * math.cos(angle) if centered == False: setView() elif centered == True: setObjView() def specialKeys(keypress, mX, mY): # things to do # this is the function to move the car if keypress == GLUT_KEY_UP: jeepObj.posZ += moveSpeed * frameTime elif keypress == GLUT_KEY_DOWN: jeepObj.posZ -= moveSpeed * frameTime elif keypress == GLUT_KEY_LEFT: jeepObj.posX += moveSpeed * frameTime elif keypress == GLUT_KEY_RIGHT: jeepObj.posX -= moveSpeed * frameTime s = 1 / 2 * a * math.pow(accumulatedTime, 2) jeepObj.posZ += s setObjView() def CreateMenu(): menu = glutCreateMenu(processMenuEvents) glutAddMenuEntry("One", 1) glutAddMenuEntry("Two", 2) glutAttachMenu(GLUT_RIGHT_BUTTON) # Add the following line to fix your code return 0 def processMenuEvents(option): print(option) def changeWindowSize(width, height): global lastWindowWidth global lastWindowHeight global windowWidth global windowHeight lastWindowWidth = windowWidth lastWindowHeight = windowHeight windowWidth = width windowHeight = height glutReshapeWindow(windowWidth, windowHeight) class Menu: def selectMenu(self, choice): # def _exit(): # import sys # sys.exit(0) # { # 1: _exit # }[choice]() global applyLighting global lightIndex global windowWidth global windowHeight global isFullScreen if choice == 1: if applyLighting == True: applyLighting = bool(1 - applyLighting) glDisable(GL_LIGHTING) glDisable(GL_LIGHT0) glDisable(GL_LIGHT1) elif applyLighting == False: applyLighting = bool(1 - applyLighting) glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glEnable(GL_LIGHT1) elif choice == 2: lightIndex = 0 elif choice == 3: lightIndex = 1 elif choice == 4: lightIndex = 2 elif choice == 5: changeWindowSize(800, 600) elif choice == 6: changeWindowSize(1280, 720) elif choice == 7: if isFullScreen == False: glutFullScreen() isFullScreen = bool(1 - isFullScreen) elif isFullScreen == True: windowWidth = lastWindowWidth windowHeight = lastWindowHeight glutReshapeWindow(windowWidth, windowHeight) isFullScreen = bool(1 - isFullScreen) return 0 def createMenu(self): # --- Right-click Menu -------- from ctypes import c_int import platform #platform specific imports: if (platform.system() == 'Windows'): #Windows from ctypes import WINFUNCTYPE CMPFUNCRAW = WINFUNCTYPE(c_int, c_int) # first is return type, then arg types. else: #Linux from ctypes import CFUNCTYPE CMPFUNCRAW = CFUNCTYPE(c_int, c_int) # first is return type, then arg types. myfunc = CMPFUNCRAW(self.selectMenu) selection_menu = glutCreateMenu( myfunc ) glutAddMenuEntry("Toggle Lighting", 1); glutAddMenuEntry("Light0", 2) glutAddMenuEntry("Light1", 3) glutAddMenuEntry("Light2", 4) glutAddMenuEntry("800x600", 5) glutAddMenuEntry("1280x720", 6) glutAddMenuEntry("Toggle FullScreen", 7) glutAttachMenu(GLUT_RIGHT_BUTTON); # - def myKeyboard(key, mX, mY): global eyeX, eyeY, eyeZ, angle, radius, helpWindow, centered global helpWin, overReason, topView, behindView, GKeyPressed, starScale global windowWidth, windowHeight, fogFileter, fogMode, starRotateAngle if key == "h": print("h pushed ") + str(helpWindow) winNum = glutGetWindow() if helpWindow == False: helpWindow = True glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH) glutInitWindowSize(500,300) glutInitWindowPosition(600,0) helpWin = glutCreateWindow('Help Guide') glutDisplayFunc(showHelp) glutKeyboardFunc(myKeyboard) glutMainLoop() elif helpWindow == True and winNum!=1: helpWindow = False print(glutGetWindow()) glutHideWindow() glutMainLoop() if key == "r": print(eyeX, eyeY, eyeZ, angle, radius) eyeX = 0.0 eyeY = 2.0 eyeZ = 10.0 angle = 0.0 radius = 10.0 if centered == False: setView() elif centered == True: setObjView() elif key == "h": print("h pushed ") + str(helpWindow) winNum = glutGetWindow() if helpWindow == False: helpWindow = True glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH) glutInitWindowSize(500,300) glutInitWindowPosition(600,0) helpWin = glutCreateWindow('Help Guide') glutDisplayFunc(showHelp) glutKeyboardFunc(stdKey) glutMainLoop() elif helpWindow == True and winNum!=1: helpWindow = False print(glutGetWindow()) glutHideWindow() #glutDestroyWindow(helpWin) glutMainLoop() elif key == "l": print("light triggered!") if jeepObj.lightOn == True: jeepObj.lightOn = False elif jeepObj.lightOn == False: jeepObj.lightOn = True glutPostRedisplay() elif key == "c": if centered == True: centered = False print("non-centered view") elif centered == False: centered = True print("centered view") elif key == "t":#top view, like a map ####################!!!!!! if (topView == True): topView = False elif (topView == False): topView = True if centered == False: setView() elif centered == True: setObjView() elif key == "b": #behind the wheel if (behindView == True): behindView = False elif (behindView == False): behindView = True setView() elif key == "q" and canStart == True: overReason = "You decided to quit!" gameOver() elif key == "x": windowWidth = 1280 windowHeight = 720 glutReshapeWindow(1280, 720) glutPostRedisplay() elif key == "f": fogFileter = (fogFileter + 1) % 3 glFogi(GL_FOG_MODE, fogMode[fogFileter]) if behindView == True: if key == "w": jeepObj.posZ += moveSpeed * frameTime setObjView() elif key == "s": jeepObj.posZ -= moveSpeed * frameTime setObjView() elif key == "a": jeepObj.posX += moveSpeed * frameTime setObjView() elif key == "d": jeepObj.posX -= moveSpeed * frameTime setObjView() if key == "1": starRotateAngle += frameTime * 100.0; elif key == "2": starRotateAngle -= frameTime * 100.0 elif key == "3": starScale += 0.1 elif key == "4": starScale -= 0.1 s = 1 / 2 * a * math.pow(accumulatedTime, 2) jeepObj.posZ += s #-------------------------------------------------tools---------------------- def drawTextBitmap(string, x, y): #for writing text to display glRasterPos2f(x, y) for char in string: glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(char)) def text3d(string, x, y, z): glRasterPos3f(x,y,z) for char in string: glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(char)) def drawStar(x = 0.0, y = 0.0, z = 0.0): global starDL, starScale glPushMatrix() glTranslatef(x, y, z) glRotatef(starRotateAngle, 0.0, 1.0, 0.0) glScalef(starScale, starScale, starScale) glCallList(starDL) glPopMatrix() def dist(pt1, pt2): a = pt1[0] b = pt1[1] x = pt2[0] y = pt2[1] return math.sqrt((a-x)**2 + (b-y)**2) def noReshape(newX, newY): #used to ensure program works correctly when resized global windowWidth, windowHeight, aspect windowWidth = newX windowHeight = newY aspect = 1.0 * windowWidth / windowHeight; setView() # 设置视口大小为增个窗口大小 glViewport(0, 0, windowWidth, windowHeight) #--------------------------------------------making game more complex-------- def addCone(x,z): allcones.append(cone.cone(x,z)) obstacleCoord.append((x,z)) def collisionCheck(): global overReason, score, usedDiamond, countTime for obstacle in obstacleCoord: if dist((jeepObj.posX, jeepObj.posZ), obstacle) <= ckSense: overReason = "You hit an obstacle!" gameOver() if (jeepObj.posX >= land or jeepObj.posX <= -land): overReason = "You ran off the road!" gameOver() for reward in rewardCoord: if dist((jeepObj.posX, jeepObj.posZ), reward) <= ckSense: print("Star bonus!") allstars.pop(rewardCoord.index(reward)) rewardCoord.remove(reward) countTime -= 10 if (dist((jeepObj.posX, jeepObj.posZ), (diamondObj.posX, diamondObj.posZ)) <= ckSense and usedDiamond ==False): print("Diamond bonus!") countTime /= 2 usedDiamond = True if (jeepObj.posZ >= land*gameEnlarge): gameSuccess() #----------------------------------multiplayer dev (using tracker)----------- def recordGame(): with open('results.csv', 'wt') as csvfile: spamwriter = csv.writer(csvfile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL) ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') print(st) spamwriter.writerow([st] + [finalScore]) #-------------------------------------developing additional windows/options---- def gameOver(): global finalScore print("Game completed!") finalScore = score-6 #recordGame() #add to excel glutHideWindow() glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH) glutInitWindowSize(200,200) glutInitWindowPosition(600,100) overWin = glutCreateWindow("Game Over!") glutDisplayFunc(overScreen) glutMainLoop() def gameSuccess(): global finalScore print("Game success!") finalScore = score-6 #recordGame() #add to excel glutHideWindow() glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH) glutInitWindowSize(200,200) glutInitWindowPosition(600,100) overWin = glutCreateWindow("Complete!") glutDisplayFunc(winScreen) glutMainLoop() def winScreen(): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glColor3f(0.0,1.0,0.0) drawTextBitmap("Completed Trial!" , -0.6, 0.85) glColor3f(0.0,1.0,0.0) drawTextBitmap("Your score is: ", -1.0, 0.0) glColor3f(1.0,1.0,1.0) drawTextBitmap(str(finalScore), -1.0, -0.15) glutSwapBuffers() def overScreen(): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glColor3f(1.0,0.0,1.0) drawTextBitmap("Incomplete Trial" , -0.6, 0.85) glColor3f(0.0,1.0,0.0) drawTextBitmap("Because you..." , -1.0, 0.5) glColor3f(1.0,1.0,1.0) drawTextBitmap(overReason, -1.0, 0.35) glColor3f(0.0,1.0,0.0) drawTextBitmap("Your score stopped at: ", -1.0, 0.0) glColor3f(1.0,1.0,1.0) drawTextBitmap(str(finalScore), -1.0, -0.15) glutSwapBuffers() def showHelp(): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glColor3f(1.0,0.0,0.0) drawTextBitmap("Help Guide" , -0.2, 0.85) glColor3f(0.0,0.0,1.0) drawTextBitmap("describe your control strategy." , -1.0, 0.7) glutSwapBuffers() def loadSceneTextures(): global roadTextureID roadTextureID = utils.loadTexture("../img/road2.png") # roadTextureID = utils.loadTexture("../img/sunset_posX.bmp") #-----------------------------------------------lighting work-------------- def initializeLight(): glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glEnable(GL_DEPTH_TEST) glClearDepth(1.0); glDepthFunc(GL_LEQUAL) glEnable(GL_NORMALIZE) #~~~~~~~~~~~~~~~~~~~~~~~~~the finale!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def initFog(): glFogi(GL_FOG_MODE, fogMode[fogFileter]) glFogfv(GL_FOG_COLOR, fogColor) glFogf(GL_FOG_DENSITY, 0.35) glHint(GL_FOG_HINT, GL_DONT_CARE) glFogf(GL_FOG_START, 1.0) glFogf(GL_FOG_END, 5.0) glEnable(GL_FOG) def main(): glutInit() global prevTime, mainWin, displayList, star, starDL prevTime = glutGet(GLUT_ELAPSED_TIME) glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH) # things to do # change the window resolution in the game glutInitWindowSize(windowWidth, windowHeight) glutInitWindowPosition(0, 0) mainWin = glutCreateWindow('CS4182') glutDisplayFunc(display) glutIdleFunc(idle)#wheel turn glEnable(GL_DEPTH_TEST) glutMouseFunc(mouseHandle) glutMotionFunc(motionHandle) glutMouseWheelFunc(mouseWheel) glutSpecialFunc(specialKeys) glutKeyboardFunc(myKeyboard) glutReshapeFunc(noReshape) # things to do # add a menu loadSceneTextures() jeep1Obj.makeDisplayLists() jeep2Obj.makeDisplayLists() jeep3Obj.makeDisplayLists() #personObj.makeDisplayLists() # things to do # add a automatic object for i in range(coneAmount):#create cones randomly for obstacles, making sure to give a little lag time in beginning by adding 10.0 buffer addCone(random.randint(-land, land), random.randint(10.0, land*gameEnlarge)) # things to do # add stars for cone in allcones: cone.makeDisplayLists() for star in allstars: star.makeDisplayLists() star = ImportObject.ImportedObject("../objects/starR") star.loadOBJ("../img/") starDL = glGenLists(1) glNewList(starDL, GL_COMPILE) star.drawObject() glEndList() # initFog() # CreateMenu() menu = Menu() menu.createMenu() # diamondObj.makeDisplayLists() staticObjects() if (applyLighting == True): initializeLight() glutMainLoop() main()
cc1356affd73334eafc65f0c4dc6882d95e2bd94
[ "Markdown", "Python", "Text" ]
15
Markdown
Felicia35/CS4182-course-project
4bb957d38751f5e5a33709aa44cc669ab0f946f5
611269b5cb2cd11226eb3e3c4a6afe50ffc5a960
refs/heads/master
<repo_name>44uk/gulp-skelton<file_sep>/gulpfile.babel.js 'use strict'; gulp.task('default', ['sync']); gulp.task('sync', ['build', 'serv'] , watch); // TODO: replace run-sequence to gulp.parallel when gulp4 released. // @see http://qiita.com/joe-re/items/e04010ed03826fb94a16 gulp.task('build', (cb) => { return rs( 'sprite', [ 'jade', 'styl', 'coffee', 'babel' ], 'copy', cb )}); gulp.task('release', (cb) => { return rs( 'production', 'clean', 'build', cb )}); gulp.task('minify', ['uglify', 'csso']); gulp.task('jade', jade); gulp.task('styl', styl); gulp.task('coffee', coffee); gulp.task('babel', babel); gulp.task('copy', copy); gulp.task('sprite', sprite); gulp.task('uglify', uglify); gulp.task('csso', csso); gulp.task('conv', conv); gulp.task('capture', capture); gulp.task('validate', validate); gulp.task('clean', clean); gulp.task('nil', nil); gulp.task('watch', watch); gulp.task('serv', bsInit); gulp.task('serv:reload', bsReload); gulp.task('production', production); import del from 'del'; import path from 'path'; import rs from 'run-sequence'; import browserSync from 'browser-sync'; import autoprefixer from 'autoprefixer'; import mqpacker from 'css-mqpacker'; import gulp from 'gulp'; import gIf from 'gulp-if'; import gPlumber from 'gulp-plumber'; import gNotify from 'gulp-notify'; import gStyl from 'gulp-stylus'; import gJade from 'gulp-jade'; import gPostcss from 'gulp-postcss'; import gCsso from 'gulp-csso'; import gCoffee from 'gulp-coffee'; import gBabel from 'gulp-babel'; import gUglify from 'gulp-uglify'; import gSprite from 'gulp.spritesmith'; import gRename from 'gulp-rename'; import gConv from 'gulp-convert-encoding'; import gReplace from 'gulp-replace'; import gWebshot from 'gulp-webshot'; import gHtmlhint from 'gulp-htmlhint'; import gSourcemap from 'gulp-sourcemaps'; import conf from './gulpconf.json'; var isProd = false; var root = process.cwd(); var bs = null; function jade () { let srcPath = [ path.join('!' + conf.general.srcPath, "__partials/**/*.jade"), path.join(conf.general.srcPath, "**/!(_)*.jade") ]; let options = Object.assign(conf.jade.options, { "basedir": conf.general.srcPath }); gulp.src(srcPath) .pipe(notify()) .pipe(gJade(options)) .pipe(gulp.dest(conf.general.dstPath)) ; } function styl () { let srcPath = [ path.join(conf.general.srcPath, "**/!(_)*.{styl,css}") ]; let options = Object.assign(conf.styl.options, { }); let processors = [ autoprefixer({browsers: ['last 2 version']}), mqpacker ] gulp.src(srcPath) .pipe(notify()) .pipe(gSourcemap.init()) .pipe(gStyl(options)) .pipe(gPostcss(processors)) .pipe(gIf(isProd, gSourcemap.write('.'), gSourcemap.write())) .pipe(gulp.dest(conf.general.dstPath)) ; } function coffee () { let srcPath = [ path.join(conf.general.srcPath, "**/!(_)*.coffee") ]; let options = Object.assign(conf.coffee.options, { }); gulp.src(srcPath) .pipe(notify()) .pipe(gSourcemap.init()) .pipe(gCoffee(options)) .pipe(gIf(isProd, gSourcemap.write('.'), gSourcemap.write())) .pipe(gulp.dest(conf.general.dstPath)) ; } function babel () { let srcPath = [ path.join(conf.general.srcPath, "**/!(_)*.babel.js") ]; let options = Object.assign(conf.babel.options, { }); gulp.src(srcPath) .pipe(notify()) .pipe(gBabel(options)) .pipe(gRename((path) => { path.basename = path.basename.replace(/\.babel$/, ''); })) .pipe(gulp.dest(conf.general.dstPath)) ; } function copy () { let srcPath = [ path.join('!' + conf.general.srcPath, "**/*.babel.js"), path.join(conf.general.srcPath, "**/*." + conf.copy.options.ext) ]; gulp.src(srcPath) .pipe(notify()) .pipe(gulp.dest(conf.general.dstPath)) ; } function sprite () { let srcPath = [ path.join(conf.general.resPath, "**/*.{jpeg,jpg,gif,png}") ]; let imgSheetPath = path.join(conf.general.srcPath, 'assets/css/'); let cssSheetPath = path.join(conf.general.srcPath, 'assets/css/'); let options = Object.assign(conf.sprite.options, {}); let sprite = gulp.src(srcPath) .pipe(notify()) .pipe(gSprite(options)); sprite.img.pipe(gulp.dest(imgSheetPath)); sprite.css.pipe(gulp.dest(cssSheetPath)); } function csso () { let srcPath = [ path.join(conf.general.dstPath, "**/*.css") ]; gulp.src(srcPath) .pipe(notify()) .pipe(gCsso()) .pipe(gulp.dest(conf.general.dstPath)) ; } function uglify () { let srcPath = [ path.join(conf.general.dstPath, "**/*.js") ]; gulp.src(srcPath) .pipe(notify()) .pipe(gUglify(conf.uglify.options)) .pipe(gulp.dest(conf.general.dstPath)) ; } function watch () { let srcPath = conf.general.srcPath; let resPath = conf.general.resPath; let options = conf.watch.options; let reload = bs ? 'serv:reload' : 'nil'; gulp.watch(path.join(srcPath, '**', '*' + options.jade), ['jade', reload]); gulp.watch(path.join(srcPath, '**', '*' + options.styl), ['styl', reload]); gulp.watch(path.join(srcPath, '**', '*' + options.coffee), ['coffee', reload]); gulp.watch(path.join(srcPath, '**', '*' + options.babel), ['babel', reload]); gulp.watch(path.join(srcPath, '**', '*' + options.files), ['copy', reload]); gulp.watch(path.join(resPath, '**', '*' + options.sprite), ['sprite', 'copy', reload]); } function bsInit () { let options = Object.assign(conf.browserSync.options, { "server": { "baseDir": conf.general.dstPath } }); bs = browserSync.init(options); } function notify () { return gPlumber({errorHandler: gNotify.onError("Error: <%= error.message %>")}); } function conv () { let srcPath = [ path.join(conf.general.dstPath, "**/*.{html,htm}") ]; let options = Object.assign(conf.conv.options, { }); let pattern = new RegExp(conf.conv.pattern); gulp.src(srcPath) .pipe(notify()) .pipe(gReplace(pattern, conf.conv.replace)) .pipe(gConv(options)) .pipe(gulp.dest(conf.general.dstPath, {overwrite: true})) ; } function capture () { let srcPath = [ path.join(conf.general.dstPath, "**/*.{html,htm}") ]; let options = Object.assign(conf.capture.options, { dest: conf.general.capPath }); gulp.src(srcPath) .pipe(notify()) .pipe(gWebshot(options)) ; } function validate () { let srcPath = [ path.join(conf.general.dstPath, "**/*.{html,htm}") ]; gulp.src(srcPath) .pipe(gHtmlhint()) .pipe(gHtmlhint.reporter()) ; } function clean () { let dstPath = [ path.join(conf.general.dstPath, "**/*.*"), path.join(conf.general.capPath, "**/*.*") ]; del(dstPath); } function production () { isProd = true } function bsReload () { bs.reload() } function nil () {} <file_sep>/README.md # gulp-skelton よく使用するであろうタスクを紹介します。 それ以外の詳しいことは `gulpfile.babel.js` を参照してください。 ## npm start 最初に`src/`以下をビルドし、`src/`以下の監視を開始した状態でローカルサーバを立ち上げます。 ## npm run build 最初に`src/`以下をビルドします。 ## npm run release 実施前に、`public/`にあるファイルを削除して、`src`以下をビルドします。 ## npm run cap `public/`以下の`html`ファイルのプレビューをキャプチャして`capture`へ保存します。 ## npm run min `public/`以下の`js`と`css`を圧縮最適化します。
50e7fd311e52ebdce8576c5726f5f087fee8bf0c
[ "JavaScript", "Markdown" ]
2
JavaScript
44uk/gulp-skelton
3bfbaf8377290b887e9b1aac7117ceac024034cc
bb3d8f136ac53d46072e5b437822da063c4a9175
refs/heads/master
<repo_name>capacitaciones-metal/react-task<file_sep>/README.md # REACT ## 1. Que es React? React es una librería de JavaScript declarativa, eficiente y flexible para construir interfaces de usuario. Permite componer IUs complejas de pequeñas y aisladas piezas de código llamadas “componentes”. React ha sido diseñado desde su inicio para ser adoptado gradualmente, así puedes usar tan poco o mucho de React como necesites. Link: https://es.reactjs.org/ ## 2. React devtools Extension de Chrome para desarrolladores. Link: https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi ## 3. Create React App Create React App es un ambiente cómodo para aprender React, y es la mejor manera de comenzar a construir una nueva aplicación de página única usando React. Create React App configura tu ambiente de desarrollo de forma que puedas usar las últimas características de Javascript, brindando una buena experiencia de desarrollo, y optimizando tu aplicación para producción. Link: https://es.reactjs.org/docs/create-a-new-react-app.html#create-react-app #### Crear proyecto `npx create-react-app nombre-del-proyecto` ## Readme generado por "create-react-app" This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.<br> Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.<br> You will also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.<br> See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.<br> It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.<br> Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. <file_sep>/src/EventSystem.js class EventSystem{ constructor(){ this.events = []; } emit(event,data){ this.events[event].forEach((callback) => { callback(data) }); } subscribe(event,callback){ if (typeof this.events[event] === 'undefined') { this.events[event] = []; } this.events[event].push(callback) } unsubscribe(event, callback) { if (typeof this.events[event] !== 'undefined') { this.events[event] = this.events[event].filter(function(value) { return value !== callback; }) } } } const eventSystem = new EventSystem(); export default eventSystem;<file_sep>/src/components/TaskNew.js import React from 'react'; import PropTypes from 'prop-types' export default class TaskNew extends React.Component { constructor(props){ super(props); this.state = {task: ""}; this.handleTaskChange = this.handleTaskChange.bind(this); } handleTaskChange(event){ this.setState({task: event.target.value}); } handleAddTask(){ if(this.state.task){ this.props.addTask(this.state.task) this.setState({task:""}) } } render(){ return ( <div> <label>Agregar Tarea: </label> <input type="text" name="task" value={this.state.task} onChange={this.handleTaskChange} /> <button onClick={this.handleAddTask.bind(this)}>Agregar</button> </div> ); } } TaskNew.propTypes = { addTask: PropTypes.func };<file_sep>/actividad.md ## Objetivo Desarrollar una herramienta para gestion de tareas. Se utilizara el siguiente esquema de componentes: ![Texto alternativo](EsquemaDeComponentes.png "Título alternativo") ### 1. Crear componente "Contenedor de tareas" - Crear un componente llamado "TaskContainer" en el path "src/componentes" - Agregar un titulo en tag h3 "Gestion de tareas" - Importar y agregar el componente "TaskContainer" en "App" ### 2. Crear componente "Nueva tarea" - Crear un componente llamado "TaskNew." en el path "src/componentes" - Agregar un input field con el label "nueva tarea" - Agregar un boton con el label "agregar" - Agregar un state denomiando "task", inicializar con String vacio - Vincular el state "task" con el input field mediante value - Importar y agregar el componente "TaskNew" al componente "TaskContainer" - Inyectar una funcion llamada "handleAddTask" desde TaskContainer hacia TaskNew mediante una prop llamada "addTask" - Implementar la funcion "handleAddTask" en taskContainer, recibiendo 1 parametro (task) e imprimir por consola el valor recibido - Agregar una validacion al apretar el boton "agregar" que corrobore que task no esta vacio - Al apretar el boton "agregar" luego de invocar la funcion de addTask vaciar el contenido del input ### 3. Recepción de evento - Agregar un state denominado "tasks" e inicializar como array vacio - Agregar items al array "tasks" en el metodo "handleAddTask" desde el valor recibido en "task". Usar concat (React way) - Verificar los states con Devtools ### 4. Crear componente "Lista de tareas" - Crear un componente llamado "TaskList" en el path "src/componentes" - Agregar una prop denominada "list" del tipo array - Agregar un titulo en tag h4 "Lista de tareas" - Agregar una lista mediante <ul> & <li> con un loop. Usar map (React way) - Importar y agregar el componente "TaskList" al componente "TaskContainer" - Desde "TaskContainer" inyectar la variable del estado interno "tasks" en la prop "list" del componente "TaskList" ### 5. Crear componente "item de lista de Tarea" - Crear un componente llamado "TaskListItem" en el path "src/componentes" - Agregar una prop "subject" del tipo String - Agregar una prop "id" del tipo Number - Imprimir el valor de "subject" dentro del tag "<li>" - Importar y agregar el componente "TaskListItem" remplazando el li del loop (map) inyectando la prop "id" y "subject" ### 6. Eliminar tarea - Agregar un boton "eliminar" en el componente "TaskListItem" - Al presionar el boton "eliminar" solicitar confirmación (window.confirm). Agregar console.log("confirmado") - Crear un simple EventSystem con funcion emit y suscribe - Importar eventSystem "TaskContainer" y suscribir al evento "delete-task" con una funcion "handleDeleteTask" - Importar eventSystem "TaskListItem" y al confirmar emitir un evento "delete-task" sobre el eventSystem - En la funcion "handleDeleteTask" dentro de "TaskContainer" eliminar la tarea del state "tasks" usando filter (React way) ### 7. Agregarle estilos con material ui - Agregar una card centrada y wrapear el contenido en la misma - Mejorar input text - Mejorar boton - Mejorar lista<file_sep>/component-comunication.md # COMPONENT COMUNICATION Parent / Child direct communication ``` const Child = ({fromChildToParentCallback}) => ( <div onClick={() => fromChildToParentCallback(42)}> Click me </div> ); class Parent extends React.Component { receiveChildValue = (value) => { console.log("Parent received value from child: " + value); // value is 42 }; render() { return ( <Child fromChildToParentCallback={this.receiveChildValue}/> ) } } ``` Here the child component will call a callback provided by the parent with a value, and the parent will be able to get the value provided by the children in the parent. If you build a feature/page of your app, it's better to have a single parent managing the callbacks/state (also called container or smart component), and all childs to be stateless, only reporting things to the parent. This way you can easily "share" the state of the parent to any child that need it. ### Context React Context permits to hold state at the root of your component hierarchy, and be able to inject this state easily into very deeply nested components, without the hassle to have to pass down props to every intermediate components. Until now, context was an experimental feature, but a new API is available in React 16.3. const AppContext = React.createContext(null) ``` class App extends React.Component { render() { return ( <AppContext.Provider value={{language: "en",userId: 42}}> <div> ... <SomeDeeplyNestedComponent/> ... </div> </AppContext.Provider> ) } }; const SomeDeeplyNestedComponent = () => ( <AppContext.Consumer> {({language}) => <div>App language is currently {language}</div>} </AppContext.Consumer> ); ``` The consumer is using the render prop / children function pattern Check this blog post for more details. Before React 16.3, I'd recommend using react-broadcast which offer quite similar API, and use former context API. ### Portals Use a portal when you'd like to keep 2 components close together to make them communicate with simple functions, like in normal parent / child, but you don't want these 2 components to have a parent/child relationship in the DOM, because of visual / CSS constraints it implies (like z-index, opacity...). In this case you can use a "portal". There are different react libraries using portals, usually used for modals, popups, tooltips... Consider the following: ``` <div className="a"> a content <Portal target="body"> <div className="b"> b content </div> </Portal> </div> ``` Could produce the following DOM when rendered inside reactAppContainer: ``` <body> <div id="reactAppContainer"> <div className="a"> a content </div> </div> <div className="b"> b content </div> </body> ``` More details here ### Slots You define a slot somewhere, and then you fill the slot from another place of your render tree. ``` import { Slot, Fill } from 'react-slot-fill'; const Toolbar = (props) => <div> <Slot name="ToolbarContent" /> </div> export default Toolbar; export const FillToolbar = ({children}) => <Fill name="ToolbarContent"> {children} </Fill> ``` This is a bit similar to portals except the filled content will be rendered in a slot you define, while portals generally render a new dom node (often a children of document.body) Check react-slot-fill library ### Event bus As stated in the React documentation: For communication between two components that don't have a parent-child relationship, you can set up your own global event system. Subscribe to events in componentDidMount(), unsubscribe in componentWillUnmount(), and call setState() when you receive an event. There are many things you can use to setup an event bus. You can just create an array of listeners, and on event publish, all listeners would receive the event. Or you can use something like EventEmitter or PostalJs ### Flux Flux is basically an event bus, except the event receivers are stores. This is similar to the basic event bus system except the state is managed outside of React Original Flux implementation looks like an attempt to do Event-sourcing in a hacky way. Redux is for me the Flux implementation that is the closest from event-sourcing, an benefits many of event-sourcing advantages like the ability to time-travel. It is not strictly linked to React and can also be used with other functional view libraries. Egghead's Redux video tutorial is really nice and explains how it works internally (it really is simple). ### Cursors Cursors are coming from ClojureScript/Om and widely used in React projects. They permit to manage the state outside of React, and let multiple components have read/write access to the same part of the state, without needing to know anything about the component tree. Many implementations exists, including ImmutableJS, React-cursors and Omniscient Edit 2016: it seems that people agree cursors work fine for smaller apps but it does not scale well on complex apps. Om Next does not have cursors anymore (while it's Om that introduced the concept initially) ### Elm architecture The Elm architecture is an architecture proposed to be used by the Elm language. Even if Elm is not ReactJS, the Elm architecture can be done in React as well. <NAME>, the author of Redux, did an implementation of the Elm architecture using React. Both Redux and Elm are really great and tend to empower event-sourcing concepts on the frontend, both allowing time-travel debugging, undo/redo, replay... The main difference between Redux and Elm is that Elm tend to be a lot more strict about state management. In Elm you can't have local component state or mount/unmount hooks and all DOM changes must be triggered by global state changes. Elm architecture propose a scalable approach that permits to handle ALL the state inside a single immutable object, while Redux propose an approach that invites you to handle MOST of the state in a single immutable object. While the conceptual model of Elm is very elegant and the architecture permits to scale well on large apps, it can in practice be difficult or involve more boilerplate to achieve simple tasks like giving focus to an input after mounting it, or integrating with an existing library with an imperative interface (ie JQuery plugin). Related issue. Also, Elm architecture involves more code boilerplate. It's not that verbose or complicated to write but I think the Elm architecture is more suited to statically typed languages. ### FRP Libraries like RxJS, BaconJS or Kefir can be used to produce FRP streams to handle communication between components. You can try for example Rx-React I think using these libs is quite similar to using what the ELM language offers with signals. CycleJS framework does not use ReactJS but uses vdom. It share a lot of similarities with the Elm architecture (but is more easy to use in real life because it allows vdom hooks) and it uses RxJs extensively instead of functions, and can be a good source of inspiration if you want to use FRP with React. CycleJs Egghead videos are nice to understand how it works. ### CSP CSP (Communicating Sequential Processes) are currently popular (mostly because of Go/goroutines and core.async/ClojureScript) but you can use them also in javascript with JS-CSP. <NAME> has done a video explaining how it can be used with React. ### Sagas A saga is a backend concept that comes from the DDD / EventSourcing / CQRS world, also called "process manager". It is being popularized by the redux-saga project, mostly as a replacement to redux-thunk for handling side-effects (ie API calls etc). Most people currently think it only services for side-effects but it is actually more about decoupling components. It is more of a compliment to a Flux architecture (or Redux) than a totally new communication system, because the saga emit Flux actions at the end. The idea is that if you have widget1 and widget2, and you want them to be decoupled, you can't fire action targeting widget2 from widget1. So you make widget1 only fire actions that target itself, and the saga is a "background process" that listens for widget1 actions, and may dispatch actions that target widget2. The saga is the coupling point between the 2 widgets but the widgets remain decoupled. If you are interested take a look at my answer here ## Conclusion If you want to see an example of the same little app using these different styles, check the branches of this repository. I don't know what is the best option in the long term but I really like how Flux looks like event-sourcing. If you don't know event-sourcing concepts, take a look at this very pedagogic blog: Turning the database inside out with apache Samza, it is a must-read to understand why Flux is nice (but this could apply to FRP as well) I think the community agrees that the most promising Flux implementation is Redux, which will progressively allow very productive developer experience thanks to hot reloading. Impressive livecoding ala Bret Victor's Inventing on Principle video is possible!
f7f8cbe74b755a431e3c1bd06f1b5024d38ed512
[ "Markdown", "JavaScript" ]
5
Markdown
capacitaciones-metal/react-task
553ef63d304b462214d42dc6b384aefee4e7dba4
5a48119becae3a27987be11cc008410ee51c50d5
refs/heads/master
<repo_name>shannonfarvolden/Doitall<file_sep>/controllers/sessions.js const jwt = require('jsonwebtoken'); const bcrypt = require('bcryptjs'); const config = require('../config'); const knex = require('../db'); const SessionsController = { //Post: Sign in user. Create JWT async create (req, res, next) { const {email, password} = req.body; try { const user = await knex.first().from('users').where({email}); if (user && bcrypt.compareSync(password, user.passwordDigest)) { const token = jwt.sign({ id: user._id }, config.secret, { expiresIn: 86400 }); res.status(200).send({ auth: true, token: token }); } else { res.status(404).send('No user found.'); } } catch (error) { res.status(500).send('Error on the server.'); } }, // TODO: Destroy JWT in localstorage in ClientSide //DELETE: Sign out user. destroy (req, res, next) { res.status(200).send({ auth: false, token: null }); } } module.exports = SessionsController // bump <file_sep>/controllers/groups.js const knex = require('../db'); const GroupsController = { // GET: List all the groups index (req, res, next) { knex .select() .from('groups') .orderBy('created_at', 'DESC') .then(groups => { res.json(groups); }) .catch(error => res.send(error)); }, //POST: Creating new group async create (req, res, next) { const {title, description, category, public, group_size, owner} = req.body; await knex .insert({title, description, category, public, group_size, owner}) .into('groups') .catch(error => res.send(error)); res.send({ message: 'New group created!' }); }, // GET: List all members belong to the group getMembers(req, res, next) { const id = req.params.groupId; try{ knex .select('user_id') .from('group_members') .where({group_id: id}) .then(members => { res.json(members); }) .catch(error => res.send(error)); } catch (error) { res.send(error); } }, }; module.exports = GroupsController; <file_sep>/graphql/schema.js const { makeExecutableSchema } = require('graphql-tools'); const User = require('./user/schema'); const resolvers = require('./resolvers'); console.log("resolvers", resolvers); const schema = makeExecutableSchema({ typeDefs: [User], resolvers, }); module.exports = schema; <file_sep>/index.js const express = require('express'); const bodyParser = require('body-parser'); const expressGraphQL = require('express-graphql'); const fs = require('fs'); const path = require('path'); const { makeExecutableSchema } = require('graphql-tools'); const { Client } = require('pg'); const app = express(); const root = require('./routes'); const schema = require('./graphql/schema'); const start = async () => { // make database connections const pgClient = new Client('postgresql://localhost:5432/doitall_dev'); await pgClient.connect(); var app = express(); app.use('/graphql', expressGraphQL({ schema: schema, graphiql: true, context: { pgClient }, })); const PORT = process.env.PORT || 5000; app.listen(PORT, () => { console.log(`🖥 Server listenning on PORT: ${PORT}`); }); }; start(); <file_sep>/graphql/user/schema.js const User = ` schema { query: UserQuery } type UserQuery { User(id: ID!): User Users: [User] } type User { id: ID email: String username: String password: String confirmPassword: String } `; module.exports = User; <file_sep>/controllers/groupMembers.js const knex = require('../db'); const GroupMembersController = { //POST: Join group and user async create (req, res, next) { const id = req.params.groupId; // Member Ids stored in Array const {memberIdArr} = req.body; for(memberId in memberIdArr) { let user_id = memberIdArr[memberId]; await knex .insert({group_id: id, user_id}) .into('group_members') .catch(error => res.send(error)); res.send({ message: 'New members added to the group' }); } } }; module.exports = GroupMembersController; <file_sep>/graphql/user/resolvers.js const userResolvers = { UserQuery: { Users: (_, __, context) => context.pgClient .query('SELECT * from users') .then(res => res.rows), User: (_, { id }, context) => context.pgClient .query('SELECT * from users WHERE id = $1', [id]) .then(res => res.rows[0]), } }; module.exports = userResolvers; <file_sep>/config.js module.exports = { 'secret': 'SuperSecretDoItAll' };
b94a3bdac914b5df1cb773172d2d606700eaffc5
[ "JavaScript" ]
8
JavaScript
shannonfarvolden/Doitall
596f41287330445dc652043af0a551abbfbc9a81
ed3bc2b1464c01225d24d57cff96ee3f4640da7b
refs/heads/master
<repo_name>trykystm/tennis-score<file_sep>/tenis_score.rb module Composite def <<(elm) @sub ||= [] @sub << elm end def each yield(self) @sub.each{|elm| elm.each{|elm| yield(elm)}} if @sub end end class OneToTow def initialize(contena) @tow_for_one = contena end def <<(contena) @tow_for_one << contena end def [](key) @tow_for_one[key] end def other(key) @tow_for_one.reject{|key1, value| key1 == key}.shift[1] end end class Digit attr_reader :digit def initialize reset! end def increment! @digit += 1 end def reset! @digit = 0 end def deuce_again! @digit = 3 end end class Element include Composite def initialize @left = Digit.new @right = Digit.new @player = OneToTow.new({:left => :@left, :right => :@right}) @default_display = lambda{left.to_s + "-" + right.to_s} end def get_point(side) @side = side @winner = @player[side] @loser = @player.other(side) increment evaluate end def test_display [left, right] end def display @display[@mode].call end private def left @left.digit end def right @right.digit end def winner instance_variable_get(@winner).digit end def loser instance_variable_get(@loser).digit end def reset @left.reset! @right.reset! end def increment instance_variable_get(@winner).increment! end def over @sub[0].get_point @side if @sub reset end def evaluate @evaluate[@mode].call end end class Point < Element attr_writer :mode def initialize super() evaluate_set display_set self << Game.new(self) @mode = :normal end private def deuce_again @left.deuce_again! @right.deuce_again! end def evaluate_set normal = lambda do if winner == 4 @mode = :normal over elsif left == 3 && right ==3 @mode = :deuce end end deuce = lambda do if winner == 5 @mode = :normal over elsif left == 4 && right ==4 deuce_again end end tie_breake = lambda do if winner == 7 @mode = :normal over elsif left == 6 && right == 6 @mode = :tie_breake_deuce end end tie_breake_deuce = lambda do if winner - loser == 2 @mode = :normal over end end @evaluate = { :normal => normal, :deuce => deuce, :tie_breake => tie_breake, :tie_breake_deuce => tie_breake_deuce} end def display_set normal = lambda do num = ["0", "15", "30", "40"] num[left] + "-" + num[right] end deuce = lambda do if left == 3 && right == 3 "Deuce" elsif left ==4 "A- " else " -A" end end @display = { :normal => normal, :deuce => deuce, :tie_breake => @default_display, :tie_breake_deuce => @default_display} end end class Game < Element def initialize(point) super() evaluate_set display_set @mode = :normal self << Sets.new @point = point end private def evaluate_set normal = lambda do if winner == 6 over elsif left == 5 && right == 5 @mode = :five_all end end five_all = lambda do if winner == 7 @mode = :normal over elsif left == 6 && right ==6 @point.mode = :tie_breake end end @evaluate = { :normal => normal, :five_all => five_all} end def display_set @display = { :normal => @default_display, :five_all => @default_display} end end class Sets < Element #Setとするとdebuggerが何故か動かなくなるので、これだけ複数形 def initialize super dummy = lambda {} @mode = :dummy @evaluate = {:dummy => dummy} @display = {:dummy => @default_display} end end class TenisScore def initialize @score = Point.new end def get_point(side) @score.get_point side end def display rtn = [] @score.each{|elm| rtn << elm.display} rtn end def test_array rtn = [] @score.each{|elm| rtn << elm.test_display} rtn.flatten end end <file_sep>/tenis_score_spec.rb require './tenis_score' RSpec.describe TenisScore do desctibe '#list' do subject do tenis_score = TenisScore.new tenis_score.configuration(conf) tenis_score.win_LEFT tenis_score.list end context 'when sideA win' do it{is_expected eq [[0, 0, 1], [0, 0, 0]]} end end end
6f427f7a273e6d59197358e9179ee782c7c28abb
[ "Ruby" ]
2
Ruby
trykystm/tennis-score
617106624512c2474d4a2b3e59800e4c680e3416
00119844d079a85373d77f54b6be580d2055f6ce
refs/heads/master
<repo_name>farmanAbbasi/dashboardWithNGXEditor<file_sep>/src/app/app.routes.ts import { Routes } from '@angular/router'; import { DashboardRoutes } from './components/dashboard/dashboard.route'; import { ForumRoutes } from './components/forum/forum.route'; export const routes: Array<any> = [ ...DashboardRoutes, ...ForumRoutes, { // fallback route path: '**', redirectTo: 'dashboard', pathMatch: 'full' } ]; <file_sep>/src/app/components/forum/forum.route.ts import { Route } from '@angular/router'; import { ForumComponent } from './forum.component'; export const ForumRoutes: Array<any> = [ { path: 'forum', component: ForumComponent } ]; <file_sep>/src/app/components/forum/forum.component.ts import { Component, OnInit} from '@angular/core'; import { dog } from './datadog'; import { PostService } from '../../services/post.service'; @Component({ selector: 'app-forum', templateUrl: './forum.component.html', styleUrls: ['./forum.component.scss'] }) export class ForumComponent implements OnInit { private noOfItemsToShowInitially = 5; dogs = dog; private itemsToLoad = 3; public itemsToShow = dog.slice(0, this.noOfItemsToShowInitially); public isFullListDisplayed = false; j = 0; thought:''; thoughtToShare = []; likeButton = 'likes'; postButton = 'click to add comment'; dataContent = []; found: boolean; toShare = false; shared = true; id = 1; i: number; likesCount = 0; jj = 0; commentLength = 0; value = 'Clear me'; commentCount = 0; text: string; selected = 'post'; flagForPost = true; flagForPoll = false; arrayOption1 = ''; arrayOption2 = ''; arrayOption3 = ''; arrayOption4 = ''; arrayOptionAll = []; indexArrayOptionAll = 0; optionsToShare = []; ioption = 0; pollQuestion = ''; pollShareFlag = false; checkedBool = false; checkedBoolArray = []; oRadio = []; o1 = false; o2 = false; o3 = false; k = 1; check = 0; constructor(private postService:PostService) { } ngOnInit() { } onThoughtKeyUp(event: any) { this.thought = event.target.value; console.log('firedThrow'); } iii = 0; sharePoll() { if (this.pollQuestion.length !== 0) { this.optionsToShare[this.iii] = this.pollQuestion; this.arrayOptionAll[(this.iii * 4) + 0] = this.arrayOption1; this.arrayOptionAll[(this.iii * 4) + 1] = this.arrayOption2; this.arrayOptionAll[(this.iii * 4) + 2] = this.arrayOption3; this.arrayOptionAll[(this.iii * 4) + 3] = this.arrayOption4; console.log(this.arrayOptionAll[0]); console.log(this.arrayOptionAll[1]); console.log(this.arrayOptionAll[2]); console.log(this.arrayOptionAll[3]); this.iii++; //fifth place pe multiple or singl option true ya false save hogi this.pollShareFlag = true; } } deleteThought() { this.thought = ''; this.arrayOption1 = ''; this.arrayOption2 = ''; this.arrayOption3 = ''; this.arrayOption4 = ''; } shareThought() { if (this.shared === true && this.thought.length !== 0) { this.toShare = true; if (this.toShare === true) { this.thoughtToShare[this.j] = this.thought; this.j = this.j + 1; /////////////////////////////////////////////////////////////////////////////////////////////////////// //sending to service this.postService.sendPostData(this.thought);//postService is to be injected in the constructor // thought is received inside the value postData this.deleteThought(); } } } onScroll() { console.log('fired'); if (this.noOfItemsToShowInitially <= dog.length) { this.noOfItemsToShowInitially += this.itemsToLoad; this.itemsToShow = dog.slice(0, this.noOfItemsToShowInitially); console.log('scrolled'); } else { this.isFullListDisplayed = true; } } } <file_sep>/src/app/services/global.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; @Injectable() export class GlobalService { _baseUrl: any = 'https://jsonplaceholder.typicode.com/'; constructor(public http: HttpClient) { } public httpGet(requestString): Observable<any> { return this.http.get(this._baseUrl + requestString); } public httpPost(requestString: string, body: Object = {}, options: Object = {}): Observable<any> { return this.http.post(this._baseUrl + requestString, body); } } <file_sep>/src/app/services/post.service.ts import { Injectable } from '@angular/core'; import { Http } from '@angular/http' @Injectable() export class PostService { constructor(private http:Http) { } sendPostData(postData){ this.http.post('http://localhost:3000/register',postData) .subscribe(res=>{ console.log(res) }) } } <file_sep>/src/app/components/forum/datadog.ts export const dog = [ { 'name': 'Person1', 'desc': 'good Person ' }, { 'name': 'Person2', 'desc': 'good Person ' }, { 'name': 'Person3', 'desc': 'good Person ' }, { 'name': 'Person4', 'desc': 'good Person ' }, { 'name': 'Person5', 'desc': 'good Person ' }, { 'name': 'Person6', 'desc': 'goodPerson ' }, { 'name': 'Person7', 'desc': 'good Person ' }, { 'name': 'Person8', 'desc': 'good Person ' }, { 'name': 'Person9', 'desc': 'good Person ' }, { 'name': 'Person10', 'desc': 'good Person ' }, { 'name': 'Person11', 'desc': 'good Person ' }, { 'name': 'Person12', 'desc': 'good Person ' }, { 'name': 'Person13', 'desc': 'good Person ' }, { 'name': 'Person14', 'desc': 'good Person' }, { 'name': 'Person15', 'desc': 'good Person' }, { 'name': 'Person16', 'desc': 'good Person ' }, { 'name': 'Person17', 'desc': 'good Person' }, { 'name': 'Person18', 'desc': 'good Person' }, { 'name': 'Person19', 'desc': 'good Person' }, { 'name': 'Person20', 'desc': 'good Person' }, { 'name': 'Person21', 'desc': 'good Person ' }, { 'name': 'Person22', 'desc': 'good Person ' }, { 'name': 'Person23', 'desc': 'good Person ' }, { 'name': 'Person24', 'desc': 'good Person ' }, { 'name': 'Person25', 'desc': 'good Person ' }, { 'name': 'Person26', 'desc': 'goodPerson ' }, { 'name': 'Person27', 'desc': 'good Person ' }, { 'name': 'Person28', 'desc': 'good Person ' }, { 'name': 'Person29', 'desc': 'good Person ' }, { 'name': 'Person30', 'desc': 'good Person ' }, { 'name': 'Person31', 'desc': 'good Person ' }, { 'name': 'Person32', 'desc': 'good Person ' }, { 'name': 'Person33', 'desc': 'good Person ' }, { 'name': 'Person34', 'desc': 'good Person' }, { 'name': 'Person35', 'desc': 'good Person' }, { 'name': 'Person36', 'desc': 'good Person ' }, { 'name': 'Person37', 'desc': 'good Person' }, { 'name': 'Person38', 'desc': 'good Person' }, { 'name': 'Person39', 'desc': 'good Person' }, { 'name': 'Person40', 'desc': 'good Person' } ]; <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { ServiceWorkerModule } from '@angular/service-worker'; import { environment } from '../environments/environment'; import { AppComponent } from './app.component'; import { HttpClientModule } from '@angular/common/http'; // Main route import { RouterModule } from '@angular/router'; import { routes } from './app.routes'; //installed import { InfiniteScrollModule } from 'ngx-infinite-scroll'; import { MatCardModule } from '@angular/material/card'; import { FormsModule } from '@angular/forms' import { HttpModule } from '@angular/http'; import { PostService } from './services/post.service'; import { NgxEditorModule } from 'ngx-editor'; import { DashboardComponent } from './components/dashboard/dashboard.component'; import { HeaderComponent } from './components/app/header/header.component'; import { FooterComponent } from './components/app/footer/footer.component'; import { SidebarComponent } from './components/app/sidebar/sidebar.component'; import { GlobalService } from './services/global.service'; // Modules import { GridStackModule } from 'ng2-gridstack'; import { ForumComponent } from './components/forum/forum.component'; import { EditorComponent } from './components/editor/editor.component'; @NgModule({ declarations: [ AppComponent, DashboardComponent, HeaderComponent, FooterComponent, SidebarComponent, ForumComponent, EditorComponent, ], imports: [ BrowserModule, RouterModule.forRoot(routes, { useHash: true }), HttpClientModule, GridStackModule, InfiniteScrollModule, MatCardModule, FormsModule, HttpModule, NgxEditorModule, environment.production ? ServiceWorkerModule.register('ngsw-worker.js') : [] ], providers: [GlobalService,PostService], bootstrap: [AppComponent] }) export class AppModule { }
af8d8668447c3269ccf40377e01f3bc67337a8bb
[ "TypeScript" ]
7
TypeScript
farmanAbbasi/dashboardWithNGXEditor
4ab5ec9caece43db586f01d22bdd6166b8959805
09ec9e3039e798102d22f22fc60fff1a3f0f4c74
refs/heads/main
<file_sep>function roadRadar(input) { input = String(input); const inputInfo = input.split(','); speed = Number(inputInfo[0]); area = inputInfo[1]; function getSpeedingMessage(speed, limit) { let speeding = speed - limit; let speedingMessage = ''; if (speeding <= 20 && speeding > 0) { speedingMessage = 'speeding'; } else if (speeding > 20 && speeding <= 40) { speedingMessage = 'excessive speeding'; } else if (speeding > 40) { speedingMessage = 'reckless driving'; } return speedingMessage; } let limit = 0; let result = ''; switch (area) { case 'residential': limit = 20; result = getSpeedingMessage(speed, limit); break; case 'city': limit = 50; result = getSpeedingMessage(speed, limit); break; case 'interstate': limit = 90; result = getSpeedingMessage(speed, limit); break; case 'motorway': limit = 130; result = getSpeedingMessage(speed, limit); break; } console.log(result); } // roadRadar([40, 'city']);<file_sep>function solve(input) { let juices = {}; let juicesProduced = {}; input.forEach(fruitQuantity => { let [fruit, quantity] = fruitQuantity.split(' => '); if (!juices[fruit]) { juices[fruit] = 0; } juices[fruit] += Number(quantity); if (juices[fruit] >= 1000) { let juiceCount = 0; while (juices[fruit] >= 1000) { juices[fruit] -= 1000 juiceCount++; } if (!juicesProduced[fruit]) { juicesProduced[fruit] = 0 } juicesProduced[fruit] += juiceCount; } }); for (const fruit in juicesProduced) { console.log(`${fruit} => ${juicesProduced[fruit]}`); } } solve([ 'Orange => 2000', 'Peach => 1432', 'Banana => 450', 'Peach => 600', 'Strawberry => 549'] );<file_sep>function solve(collection) { collection .sort() .sort(function (a, b) { return a.length - b.length; }) console.log(collection.join('\n')); } solve(['alpha', 'beta', 'gamma'] );<file_sep>function solve(ticketInfo, sortingCriteria) { class Ticket { constructor(destination, price, status) { this.destination = destination; this.price = Number(price); this.status = status; } } let tickets = []; ticketInfo.forEach(info => { let [destination, price, status] = info.split('|'); let ticket = new Ticket(destination, price, status); tickets.push(ticket); }); switch (sortingCriteria) { case "destination": tickets.sort(function (a, b) { if (a.destination < b.destination) { return -1; } if (a.destination > b.destination) { return 1; } return 0; } ); break; case "price": tickets.sort(); break; case "status": tickets.sort(function (a, b) { if (a.status < b.status) { return -1; } if (a.status > b.status) { return 1; } return 0; }); break; } return tickets; } solve([ 'Philadelphia|94.20|available', 'New York City|95.99|available', 'New York City|95.99|sold', 'Boston|126.20|departed'], 'destination' );<file_sep>function createArticle() { let titleFromInput = document.getElementById('createTitle'); let contentFromInput = document.getElementById('createContent'); if (titleFromInput.value != '' && contentFromInput.value != '') { let title = document.createElement('h3'); title.innerText = titleFromInput.value; let content = document.createElement('p'); content.innerText = contentFromInput.value; let article = document.createElement('article') article.appendChild(title); article.appendChild(content); let articleSection = document.getElementById('articles'); articleSection.appendChild(article); } titleFromInput.value = ''; contentFromInput.value = ''; }<file_sep>function solve(matrix) { let initialSum = matrix[0].reduce(function (a, b) { return a + b; }, 0); let areEqual = true; for (let row = 0; row < matrix.length; row++) { const currentRow = matrix[row]; const currentRowSum = currentRow.reduce(function (a, b) { return a + b; }, 0); if (initialSum !== currentRowSum) { areEqual = false; break; } const currentCol = new Array(); for (let col = 0; col < matrix.length; col++) { currentCol.push(matrix[col][row]); } const currentColSum = currentCol.reduce(function (a, b) { return a + b; }, 0); if (initialSum !== currentColSum) { areEqual = false; break; } } console.log(areEqual); } // solve([[4, 5, 6], // [6, 5, 4], // [5, 5, 5]] // ); // solve([[11, 32, 45], // [21, 0, 1], // [21, 1, 1]] // ); // solve([[1, 0, 0], // [0, 0, 1], // [0, 1, 0]] // );<file_sep> function solve(arg1, arg2, arg3) { let sumLength; let sumAverageLength; let firstArgLength = arg1.length; let secondArgLength = arg2.length; let thirdArgLength = arg3.length; sumLength = firstArgLength + secondArgLength + thirdArgLength; sumAverageLength = Math.floor(sumLength / 3); console.log(sumLength) console.log(sumAverageLength) } <file_sep>function solve(input) { let heroes = []; input.forEach(line => { let [name, level, items] = line.split(' / '); level = Number(level); items = items ? items.split(', ') : []; let hero = { name, level, items, }; heroes.push(hero); }); console.log(JSON.stringify(heroes)); } solve([ 'Isacc / 25 / Apple, GravityGun', 'Derek / 12 / BarrelVest, DestructionSword', 'Hes / 1 / Desolator, Sentinel, Antara'] ); // function solve(input) { // class Hero { // constructor(name, level, items) { // this.name = name; // this.level = level; // this.items = items ? items.split(', ') : []; // } // } // let heroesInfo = input // .map(x => x.split(',')); // let heroes = []; // for (let hero = 0; hero < heroesInfo.length; hero++) { // const currentHeroInfo = String(heroesInfo[hero]).split(' / '); // const currentHeroName = currentHeroInfo[0]; // const currentHeroLevel = Number(currentHeroInfo[1]); // const currentHeroItems = currentHeroInfo[2]; // let currentHero = new Hero(currentHeroName, currentHeroLevel, currentHeroItems); // heroes.push(currentHero); // } // console.log(JSON.stringify(heroes)); // } <file_sep>function cookByNumber(input) { const numberAndCommands = String(input).split(","); let cookedNumber = Number(numberAndCommands[0]); for (let i = 1; i < numberAndCommands.length; i++) { const currentCommand = numberAndCommands[i]; switch (currentCommand) { case 'chop': cookedNumber /= 2; break; case 'dice': cookedNumber = Math.sqrt(cookedNumber); break; case 'spice': cookedNumber++; break; case 'bake': cookedNumber *= 3; break; case 'fillet': cookedNumber -= 0.2 * cookedNumber; break; } console.log(cookedNumber); } } // cookByNumber(['9', 'dice', 'spice', 'chop', 'bake', 'fillet']); <file_sep>function solve() { const selectMenuTo = document.getElementById('selectMenuTo'); document .querySelector("#container > button") .addEventListener('click', convert); function convert() { let inputNumber = Number(document.getElementById('input').value); let result; if (selectMenuTo.value === 'binary') { result = decimalToBinary(inputNumber); } else if (selectMenuTo.value === 'hexadeicmal') { result = decimalToHexadeicmal(inputNumber); } appendresult(result); } function appendresult(result) { document.getElementById('result').value = result; } function decimalToBinary(inputNumber) { return (inputNumber >>> 0).toString(2); } function decimalToHexadeicmal(inputNumber) { return inputNumber.toString(16).toUpperCase(); } function createSelectMenuOptions() { let binaryOption = document.createElement('option'); binaryOption.textContent = 'Binary'; binaryOption.value = 'binary'; let hexadeicmalOption = document.createElement('option'); hexadeicmalOption.textContent = 'Hexadeicmal'; hexadeicmalOption.value = 'hexadeicmal'; selectMenuTo.appendChild(binaryOption); selectMenuTo.appendChild(hexadeicmalOption); } createSelectMenuOptions(); }<file_sep>function solve(matrix) { let pairs = 0; matrix.forEach((row, i) => { row.forEach((el, j) => { if (el === row[j + 1]) { pairs++; } if (matrix[i + 1] && el === matrix[i + 1][j]) { pairs++; } }); }); console.log(pairs); } // solve([['test', 'yes', 'yo', 'ho'], // ['well', 'done', 'yo', '6'], // ['not', 'done', 'yet', '5']] // );<file_sep>function findLargestNumber(first, second, third){ let maxNumber = Math.max(first, second, third); console.log(`The largest number is ${maxNumber}.`); } findLargestNumber(-3, -5, -22.5);<file_sep>function solve(commands) { let initialNumber = 1; let numbers = Array(); for (let i = 0; i < commands.length; i++) { if (commands[i] === 'add') { numbers.push(initialNumber); }else if(commands[i] === 'remove'){ numbers.pop(); } initialNumber++; } let result = numbers.length > 0 ? numbers.join('\n') : 'Empty'; console.log(result); } solve(['add', 'add', 'add', 'add'] ); solve(['add', 'add', 'remove', 'add', 'add'] ); solve(['remove', 'remove', 'remove'] );<file_sep>function calculateTime(steps, stepLength, speed) { let length = (steps * stepLength); let totalRestTimeInMinutes = Math.floor(length / 500); let totalTime = length / speed / 1000 * 60; let totalTimeInSeconds = Math.ceil((totalRestTimeInMinutes + totalTime) * 60); let result = new Date(null, null, null, null, null, totalTimeInSeconds); console.log(result.toTimeString().split(' ')[0]); } // calculateTime(4000, 0.60, 5);<file_sep>function solve(collection) { let biggestNum = Number.MIN_SAFE_INTEGER; // let increasingSequence = Array(); for (let i = 0; i < collection.length; i++) { const currentElement = collection[i]; if (currentElement >= biggestNum) { biggestNum = currentElement; // increasingSequence.push(currentElement); console.log(biggestNum); } } } solve([1, 3, 8, 4, 10, 10, 12, 3, 2, 24] );<file_sep>function solve(numbers) { let negatives = numbers.filter(x => { return x < 0; }); let positives = numbers.filter(x => { return x >= 0; }); negatives.reverse().forEach(x => { console.log(x); }); positives.forEach(x => { console.log(x); }); } // solve([3, -2, 0, -1]);<file_sep>function solve(numbers) { let result = []; for (let i = 0; i < numbers.length; i += 2) { const element = numbers[i]; result.push(element); } console.log(result.join(' ')); } // solve(['5', '10', '16']);
63507a695fe0590bb62c147e20ce8202d17d7d7a
[ "JavaScript" ]
17
JavaScript
TsvetomirShterev/JsAdvanced
655003b1cfe136e3fe9db992ae00fe87b23daaf3
fba06afb2c568104182dfbaaa2312ceb9e0def35
refs/heads/master
<file_sep><?php namespace AppBundle\Tests\Controller; use ApiLib\Tests\Fixtures\Article; use ApiLib\Collection\ArticleCollection; class ArticleCollectionTest extends \PHPUnit_Framework_TestCase { public function testAll() { $articleEntity = new Article(); $this->assertInstanceOf('\ApiLib\Interfaces\ArticleRepositoryInterface', $articleEntity); $collection = new ArticleCollection($articleEntity); $this->assertInternalType('array', $collection->all()); $this->assertEquals(4, count($collection->all())); } }<file_sep><?php /** * Created by PhpStorm. * User: mbucse * Date: 08/04/2016 * Time: 05:01 */ namespace ApiBundle\DataFixtures\ORM; use ApiBundle\Utils\FakerTrait; use ApiBundle\Utils\InitializeContainerTrait; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use ApiBundle\Entity\Answer; use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use ApiBundle\Entity\Article; class LoadAnswersData implements FixtureInterface, OrderedFixtureInterface, ContainerAwareInterface { use FakerTrait; use InitializeContainerTrait; /** * Load data fixtures with the passed EntityManager * * @param ObjectManager $manager */ public function load(ObjectManager $manager) { for($i = 0; $i < 15; $i++) { $this->createAnswer($manager); } } public function getOrder() { // the order in which fixtures will be loaded // the lower the number, the sooner that this fixture is loaded return 30; } /** * @param ObjectManager $manager */ private function createAnswer(ObjectManager $manager) { $article = new Answer(); $article->setName($this->faker->name); $article->setBody($this->faker->paragraph(20)); $article->setArticle($this->getRandomArticle($manager)); $article->setRating(rand(1,5)); $manager->persist($article); $manager->flush(); } private function getRandomArticle(ObjectManager $manager) { $userManager = $manager->getRepository('ApiBundle:Article'); $articles = $userManager->findAll(); shuffle($articles); // return $articles[0] ?? null; return isset($articles[0]) ? $articles[0] : null; } }<file_sep><?php /** * Created by PhpStorm. * User: mbucse * Date: 07/04/2016 * Time: 07:00 */ namespace ApiLib\Interfaces; interface ArticleCollectionInterface { public function setPage($page); public function setLimit($limit); public function all(); }<file_sep><?php /** * Created by PhpStorm. * User: mbucse * Date: 08/04/2016 * Time: 05:24 */ namespace ApiBundle\DQL; trait ExtendDoctrine { /** * Get random entities * * @param int $count Entities count, default is 10 * * @return array */ public function getRandomEntities($count = 10) { return $this->createQueryBuilder('q') ->addSelect('RAND() as HIDDEN rand') ->addOrderBy('rand') ->setMaxResults($count) ->getQuery() ->getResult(); } }<file_sep><?php /** * Created by PhpStorm. * User: mbucse * Date: 07/04/2016 * Time: 06:46 */ namespace ApiLib\Tests\Fixtures; use ApiLib\Interfaces\ArticleRepositoryInterface; class Article implements ArticleRepositoryInterface { public function listArticles() { return [ [ 'id' => 12, 'title' => 'kljkl jkl lkj lk', 'excerpt' => 'jlk jslk jflksj dlkfajsdk jflasdkjf sdj', 'body' => 'jlk jslk jflksj dlkfajsdk jflasdkjf dlkfajsdk jflasdkjf dlkfajsdk jflasdkjf sdj', 'no_answers' => 10, 'rating' => 4.3, ], [ 'id' => 13, 'title' => 'tyurtyurtyurty r lk', 'excerpt' => 'jlk jslk jflksj dlkfajsdk jflasdkjf sdj', 'body' => 'jlk jslk jflksj dlkfajsdk jflasdkjf dlkfajsdk jflasdkjf dlkfajsdk jflasdkjf sdj', 'no_answers' => 0, 'rating' => 4.3, ], [ 'id' => 123, 'title' => 'aaaaa a a atyurtyurtyurty r lk', 'excerpt' => 'jlk jslk jflksj dlkfajsdk jflasdkjf sdj', 'body' => 'jlk jslk jflksj dlkfajsdk jflasdkjf dlkfajsdk jflasdkjf dlkfajsdk jflasdkjf sdj', 'no_answers' => 0, 'rating' => 3.2, ], [ 'id' => 124, 'title' => 'eeeee a atyurtyurtyurty r lk', 'excerpt' => 'jlk jslk jflksj dlkfajsdk jflasdkjf sdj', 'body' => 'jlk jslk jflksj dlkfajsdk jflasdkjf dlkfajsdk jflasdkjf dlkfajsdk jflasdkjf sdj', 'no_answers' => 0, 'rating' => 3.2, ], ]; } public function get($article_id) { return [ 'id' => 12, 'title' => 'kljkl jkl lkj lk', 'excerpt' => 'jlk jslk jflksj dlkfajsdk jflasdkjf sdj', 'body' => 'jlk jslk jflksj dlkfajsdk jflasdkjf dlkfajsdk jflasdkjf dlkfajsdk jflasdkjf sdj', 'no_answers' => 10, 'rating' => 4.8, ] ; } public function getAnswers($article_id) { return [ [ 'id' => 1, 'body' => 'jlk jslk jflksj dlkfajsdk jflasdkjf dlkfajsdk jflasdkjf dlkfajsdk jflasdkjf sdj', 'author' => 'Jijel', 'hr_date' => 'February 23, 2016', ], [ 'id' => 1, 'body' => 'jlk jslk jflksj dlkfajsdk jflasdkjf dlkfajsdk jflasdkjf dlkfajsdk jflasdkjf sdj', 'author' => 'Gicu', 'hr_date' => 'February 24, 2016', ], ]; } public function saveAnswer(array $data) { return true; } }<file_sep><?php /** * Created by PhpStorm. * User: mbucse * Date: 07/04/2016 * Time: 06:49 */ namespace ApiLib\Interfaces; interface ArticleRepositoryInterface { public function listArticles(); public function get($article_id); public function getAnswers($article_id); public function saveAnswer(array $data); public function saveArticle(array $data); }<file_sep><?php /** * Created by PhpStorm. * User: mbucse * Date: 07/04/2016 * Time: 07:02 */ namespace ApiLib\Interfaces; interface ArticleEntityInterface { }<file_sep>(function () { 'use strict'; angular.module('SymfonyApp', ['ngRoute', 'ngAnimate', 'SymfonyAppTpl', 'restangular', 'ui.bootstrap']) .service('authorisation', ['$window', function($window) { var storage = $window.localStorage; var cachedToken; var userToken = '<PASSWORD>'; var authorisation = { setToken: function(token) { cachedToken = token; storage.setItem(userToken, token); }, getToken: function() { if (!cachedToken) { cachedToken = storage.getItem(userToken); } return cachedToken; }, isAuthenticated: function() { // return true; return !!authorisation.getToken(); }, removeToken: function() { cachedToken = null; storage.removeItem(userToken); } }; return authorisation; }]) .run([ 'Restangular', 'authorisation', function(RestangularProvider, authorisation) { if (authorisation.is) { RestangularProvider.setDefaultHeaders({Authorization: 'Bearer ' + authorisation.getToken()}) } } ]) .config([ '$locationProvider', '$routeProvider', '$interpolateProvider', 'RestangularProvider', function($locationProvider, $routeProvider, $interpolateProvider, RestangularProvider) { // $locationProvider.hashPrefix('!'); $interpolateProvider.startSymbol('[[').endSymbol(']]'); // routes $routeProvider .when("/", { templateUrl: "article_list.html", controller: "PageController" }) .when("/article/:articleId", { templateUrl: "article.html", controller: "ArticleController", resolve: { article: ArticleController.loadArticle } }) .otherwise({ redirectTo: '/' }); RestangularProvider.setBaseUrl('http://localhost:8000/api/v1'); } ]); //Load controller var app = angular.module('SymfonyApp'); var MainController = app.controller('MainController', [ '$scope', '$rootScope', '$location', 'Restangular', '$uibModal', 'authorisation', '$route', function($scope, $rootScope, $location, Restangular, $uibModal, authorisation, $route) { $rootScope.authenticated = authorisation.isAuthenticated(); $scope.newArticle = function () { var modalInstance = $uibModal.open({ templateUrl: 'createArticle.html', animation: true, size: 'lg', backdrop: 'static', controller: ['$scope', '$uibModalInstance', function ($scope, $uibModalInstance) { $scope.submitArticle = function () { $uibModalInstance.close($scope.article); }; $scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }; }] }); modalInstance.result.then(function (article) { Restangular.all('articles').post(article); $location.path("/"); $route.reload(); }, console.error); }; $scope.logout = function () { Restangular.all('logout').post().then(function () { authorisation.removeToken(); $rootScope.authenticated = authorisation.isAuthenticated(); $route.reload(); }, console.error); } $scope.showLogin = function () { var modalInstance = $uibModal.open({ templateUrl: 'login.html', animation: true, controller: ['$scope', '$uibModalInstance', function ($scope, $uibModalInstance) { $scope.submitLogin = function () { $uibModalInstance.close($scope.user); }; $scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }; }] }); modalInstance.result.then(function (user) { Restangular.all('login').post(user).then(function () { authorisation.setToken('<PASSWORD>'); $rootScope.authenticated = authorisation.isAuthenticated(); $route.reload(); }, console.error); }, console.error); }; $scope.showModal = false; $scope.toggleModal = function(){ $scope.showModal = !$scope.showModal; }; } ]); var PageController = app.controller('PageController', [ '$scope', '$location', 'Restangular', function($scope, $location, Restangular) { $scope.viewArticle = function (article_id) { $location.path( '/article/' + article_id ); }; var loadArticles = function() { console.log('load articles'); Restangular .all('articles') .getList().then(function(articles) { $scope.articles = articles; }); } loadArticles(); } ]); var ArticleController = app.controller('ArticleController', [ '$scope', '$route', 'Restangular', 'article', '$uibModal', function($scope, $route, Restangular, article, $uibModal) { $scope.article = article; var loadAnswers = function() { Restangular .one('article/', $route.current.params.articleId) .one('answers') .get() .then(function (answers) { $scope.article.answers = answers; }); } var reload = function() { Restangular .one('article/', $route.current.params.articleId) .get() .then(function (article) { $scope.article = article; }); } loadAnswers(); $scope.postAnswer = function(article_id) { var modalInstance = $uibModal.open({ templateUrl: 'createAnswer.html', animation: true, controller: ['$scope', '$uibModalInstance', function ($scope, $uibModalInstance) { $scope.submitAnswer = function () { $uibModalInstance.close($scope.user); }; $scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }; }] }); modalInstance.result.then(function (user) { var postData = user; postData.article_id = $scope.article.id Restangular.all('article/' + $route.current.params.articleId + '/answers').post(postData); reload(); loadAnswers(); }, console.error); } } ]); ArticleController.loadArticle = ['Restangular', '$route', function(Restangular, $route){ return Restangular .one('article', $route.current.params.articleId) .get(); }]; }());<file_sep><?php namespace ApiBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Answer * * @ORM\Table(name="answer") * @ORM\Entity(repositoryClass="ApiBundle\Repository\AnswerRepository") */ class Answer extends AbstractEntity { /** * @var int * @ORM\Id * @ORM\Column(name="id", type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255) */ private $name; /** * @var string * * @ORM\Column(name="body", type="text") */ private $body; /** * @var int * * @ORM\Column(name="rating", type="integer") */ private $rating; /** * @ORM\ManyToOne(targetEntity="Article" , inversedBy="answers" ) * @ORM\JoinColumn(name="article_id", referencedColumnName="id") */ private $article; /** * Get id * * @return int */ public function getId() { return $this->id; } /** * Set name * * @param string $name * * @return Answer */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set body * * @param string $body * * @return Answer */ public function setBody($body) { $this->body = $body; return $this; } /** * Get body * * @return string */ public function getBody() { return $this->body; } /** * Set rating * * @param integer $rating * * @return Answer */ public function setRating($rating) { $this->rating = $rating; return $this; } /** * Get rating * * @return int */ public function getRating() { return $this->rating; } /** * Set article * * @param integer $article * * @return Answer */ public function setArticle($article) { $this->article = $article; return $this; } /** * Get article * * @return int */ public function getArticle() { return $this->article; } } <file_sep><?php /** * Created by PhpStorm. * User: mbucse * Date: 07/04/2016 * Time: 06:52 */ namespace ApiLib\Collection; use ApiLib\Interfaces\ArticleCollectionInterface; use ApiLib\Interfaces\ArticleRepositoryInterface; class ArticleCollection implements ArticleCollectionInterface { /** * @var int */ protected $page = 1; /** * @var int */ protected $limit = 20; /** * @var ArticleRepositoryInterface */ private $articleEntity; public function __construct(ArticleRepositoryInterface $articleEntity) { $this->articleEntity = $articleEntity; } /** * @param $page */ public function setPage($page) { $this->page = $page; return $this; } /** * @param $limit */ public function setLimit($limit) { $this->limit = $limit; return $this; } public function all() { return $this->articleEntity->listArticles(); } }<file_sep><?php /** * Created by PhpStorm. * User: mbucse * Date: 08/04/2016 * Time: 05:37 */ namespace ApiBundle\Utils; use Faker\Factory as Faker; trait FakerTrait { protected $faker; public function __construct() { $this->faker = Faker::create(); } }<file_sep><?php namespace ApiBundle\Entity; use ApiLib\Interfaces\ArticleInterface; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; use ApiBundle\Entity\Answer; /** * Article * * @ORM\Table(name="article") * @ORM\Entity(repositoryClass="ApiBundle\Repository\ArticleRepository") */ class Article extends AbstractEntity { /** * @ORM\OneToMany(targetEntity="Answer", mappedBy="article") * @var Answer */ private $answers; public function __construct() { $this->answers = new ArrayCollection(); } public function getAnswers() { return $this->answers; } /** * @var int * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="title", type="string", length=255) */ private $title; /** * @var string * * @ORM\Column(name="excerpt", type="string", length=255) */ private $excerpt; /** * @var string * * @ORM\Column(name="body", type="text") */ private $body; /** * @var User * * @ORM\ManyToOne(targetEntity="User") * @ORM\JoinColumn(name="user_id", referencedColumnName="id") */ private $user; /** * Get id * * @return int */ public function getId() { return $this->id; } /** * Set title * * @param string $title * * @return Article */ public function setTitle($title) { $this->title = $title; return $this; } /** * Get title * * @return string */ public function getTitle() { return $this->title; } /** * Set excerpt * * @param string $excerpt * * @return Article */ public function setExcerpt($excerpt) { $this->excerpt = $excerpt; return $this; } /** * Get excerpt * * @return string */ public function getExcerpt() { return $this->excerpt; } /** * Set body * * @param string $body * * @return Article */ public function setBody($body) { $this->body = $body; return $this; } /** * Get body * * @return string */ public function getBody() { return $this->body; } /** * Set user * * @param User $user * * @return Article */ public function setUser(User $user) { $this->user = $user; return $this; } /** * Get user * * @return User */ public function getUser() { return $this->user; } } <file_sep><?php /** * Created by PhpStorm. * User: mbucse * Date: 08/04/2016 * Time: 06:19 */ namespace ApiBundle\Utils; use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerInterface; trait InitializeContainerTrait { protected $container; /** * Sets the container. * * @param ContainerInterface|null $container A ContainerInterface instance or null */ public function setContainer(ContainerInterface $container = null) { $this->container = $container; } }<file_sep><?php namespace ApiBundle\DataFixtures\ORM; use ApiBundle\Utils\FakerTrait; use ApiBundle\Entity\User; use ApiBundle\Utils\InitializeContainerTrait; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerInterface; class LoadUserData implements FixtureInterface, OrderedFixtureInterface, ContainerAwareInterface { use FakerTrait; use InitializeContainerTrait; /** * Load data fixtures with the passed EntityManager * * @param ObjectManager $manager */ public function load(ObjectManager $manager) { $this->createUser($manager); $this->createUser($manager); } public function getOrder() { // the order in which fixtures will be loaded // the lower the number, the sooner that this fixture is loaded return 10; } /** * @param ObjectManager $manager */ private function createUser(ObjectManager $manager) { $userManager = $this->container->get('fos_user.user_manager'); $user = $userManager->createUser(); $user->setUsername($this->faker->userName); $user->setPlainPassword('<PASSWORD>'); $user->setEmail($this->faker->email); $user->setEnabled(true); // $user->setRoles(array('ROLE_ADMIN')); $manager->persist($user); $manager->flush(); } }<file_sep><?php namespace ApiBundle\Repository; /** * UserRepository */ class UserRepository extends \Doctrine\ORM\EntityRepository { use ExtendDoctrine; } <file_sep><?php use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Bundle\FrameworkBundle\Routing\Router; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface; use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface { private $router; public function onAuthenticationSuccess(Request $request, TokenInterface $token) { } public function onAuthenticationFailure(Request $request, AuthenticationException $exception) { } } <file_sep><?php /** * Created by PhpStorm. * User: mbucse * Date: 07/04/2016 * Time: 06:25 */ namespace ApiLib\Interfaces; interface UserInterface { public function login($username, $password); }<file_sep><?php namespace ApiBundle\Repository; use ApiBundle\Entity\Answer; use ApiBundle\Entity\Article; use ApiLib\Interfaces\ArticleRepositoryInterface; /** * ArticleRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class ArticleRepository extends \Doctrine\ORM\EntityRepository implements ArticleRepositoryInterface { public function listArticles() { return $this->findAllWithNoAnswers(); } public function get($article_id) { return $this->find($article_id); } public function getAnswers($article_id) { return $this->find($article_id)->getAnswers(); } public function saveAnswer(array $data) { $article = $this->find($data['article_id']); $answer = new Answer(); $answer->setName($data['name']); $answer->setBody($data['body']); $answer->setRating($data['rating']); $answer->setArticle($article); $this->getEntityManager()->persist($answer); $this->getEntityManager()->flush(); return true; } public function saveArticle(array $data) { $article = new Article(); $article->setTitle($data['title']); $article->setExcerpt($data['excerpt']); $article->setBody($data['body']); $user = $this->getEntityManager()->getRepository('ApiBundle:User')->find(20); $article->setUser($user); $this->getEntityManager()->persist($article); $this->getEntityManager()->flush(); return true; } private function findAllWithNoAnswers($limit = 10) { $qb = $this->createQueryBuilder("a") ->select('a, COUNT(1) no_answers') ->leftJoin('a.answers', 'article') ->groupBy('a.id') ->orderBy('a.id', 'DESC') ; if (is_numeric($limit)) { $qb->setMaxResults($limit); } return $qb->getQuery()->getResult(); } } <file_sep><?php namespace ApiBundle\Controller; use ApiLib\Collection\ArticleCollection; use FOS\RestBundle\Controller\Annotations\View; use FOS\RestBundle\Controller\FOSRestController; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Symfony\Component\HttpFoundation\Request; class ArticleController extends FOSRestController { /** * @Route("/articles") * @Method({"GET"}) * @View() */ public function indexAction($page = 1) { $articleRepository = $this->getDoctrine()->getManager()->getRepository('ApiBundle:Article'); $articlesCollection = (new ArticleCollection($articleRepository)) ->setPage($page) ->setLimit(10); $articles = $articlesCollection->all(); return $this->view($articlesCollection->all(), 200); } /** * @Route("/article/{article_id}", requirements={"article_id" = "\d+"}) * @Method({"GET"}) * @View() */ public function articleAction($article_id) { $articleEntity = $this->getDoctrine()->getManager()->getRepository('ApiBundle:Article'); return $this->view($articleEntity->get($article_id), 200); } /** * @Route("/article/{article_id}/answers", requirements={"article_id" = "\d+"}) * @Method({"GET"}) * @View() */ public function articleAnswersAction($article_id) { $articleEntity = $this->getDoctrine()->getManager()->getRepository('ApiBundle:Article'); return $this->view($articleEntity->getAnswers($article_id), 200); } /** * @Route("/article/{article_id}/answers", requirements={"article_id" = "\d+"}) * @Method({"POST"}) * @View() * @param Request $request * @return \FOS\RestBundle\View\View */ public function createArticleAnswersAction(Request $request) { $articleEntity = $this->getDoctrine()->getManager()->getRepository('ApiBundle:Article'); $data = [ 'article_id' => $request->request->get('article_id'), 'name' => $request->request->get('name'), 'body' => $request->request->get('answer'), 'rating' => $request->request->get('rating') ]; return $this->view($articleEntity->saveAnswer($data), 200); } /** * @Route("/articles") * @Method({"POST"}) * @View() * @param Request $request * @return \FOS\RestBundle\View\View */ public function createArticleAction(Request $request) { $articleEntity = $this->getDoctrine()->getManager()->getRepository('ApiBundle:Article'); $data = [ 'title' => $request->request->get('title'), 'excerpt' => $request->request->get('excerpt'), 'body' => $request->request->get('body') ]; return $this->view($articleEntity->saveArticle($data), 200); } } <file_sep><?php /** * Created by PhpStorm. * User: mbucse * Date: 07/04/2016 * Time: 11:51 */ namespace ApiBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints\DateTime; use Gedmo\Mapping\Annotation as Gedmo; class AbstractEntity { /** * @var datetime $created * * @Gedmo\Timestampable(on="create") * @ORM\Column(type="datetime") */ private $created; /** * @var datetime $updated * * @Gedmo\Timestampable(on="update") * @ORM\Column(type="datetime") */ private $updated; public function __construct() { $this->setCreated(new DateTime()); $this->setUpdated(new DateTime()); } private function setCreated(DateTime $date) { $this->created = $date; } private function setUpdated(DateTime $date) { $this->updated = $date; } }<file_sep><?php /** * Created by PhpStorm. * User: mbucse * Date: 07/04/2016 * Time: 06:32 */ namespace ApiLib\Exceptions; class UserException extends \Exception { }<file_sep><?php /** * Created by PhpStorm. * User: mbucse * Date: 08/04/2016 * Time: 05:01 */ namespace ApiBundle\DataFixtures\ORM; use ApiBundle\Utils\FakerTrait; use ApiBundle\Utils\InitializeContainerTrait; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use ApiBundle\Entity\Article; use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use ApiBundle\Entity\User; class LoadArticleData implements FixtureInterface, OrderedFixtureInterface, ContainerAwareInterface { use FakerTrait; use InitializeContainerTrait; /** * Load data fixtures with the passed EntityManager * * @param ObjectManager $manager */ public function load(ObjectManager $manager) { for($i = 0; $i < 5; $i++) { $this->createArticle($manager); } } public function getOrder() { // the order in which fixtures will be loaded // the lower the number, the sooner that this fixture is loaded return 20; } /** * @param ObjectManager $manager */ private function createArticle(ObjectManager $manager) { $article = new Article(); $article->setTitle($this->faker->sentence(10)); $article->setExcerpt($this->faker->paragraph(5)); $article->setBody($this->faker->paragraph(20)); $article->setUser($this->getRandomUser($manager)); $manager->persist($article); $manager->flush(); } private function getRandomUser(ObjectManager $manager) { $userManager = $this->container->get('fos_user.user_manager'); $users = $userManager->findUsers(); shuffle($users); // return $users[0] ?? null; return isset($users[0]) ? $users[0] : null; } }<file_sep><?php namespace ApiBundle\Controller; use FOS\RestBundle\Controller\Annotations\View; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Component\HttpFoundation\Request; class DefaultController extends Controller { /** * @Route("/") * @View() */ public function indexAction() { return array('success' => true); } /** * @Route("/login") * @View() */ public function loginAction(Request $request) { $username = $request->get('username'); $password = $request->get('password'); return array('success' => true); } /** * @Route("/logout") * @View() */ public function logoutAction(Request $request) { return array('success' => true); } } <file_sep><?php namespace ApiBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * ArticleRating * * @ORM\Table(name="article_rating") * @ORM\Entity(repositoryClass="ApiBundle\Repository\ArticleRatingRepository") */ class ArticleRating extends AbstractEntity { /** * * @ORM\Id * @ORM\ManyToOne(targetEntity="Article") * @ORM\JoinColumn(name="article_id", referencedColumnName="id") */ private $article; /** * * @ORM\Id * @ORM\ManyToOne(targetEntity="Answer") * @ORM\JoinColumn(name="answer_id", referencedColumnName="id") */ private $answer; /** * @var int * * @ORM\Column(name="rating", type="integer") */ private $rating; } <file_sep>// gulp var gulp = require('gulp'); // plugins var uglify = require('gulp-uglify'); var minifyCSS = require('gulp-minify-css'); var runSequence = require('run-sequence').use(gulp); var minifyHtml = require('gulp-minify-html'); var ngTemplate = require('gulp-ng-template'); var gp_concat = require('gulp-concat'); // tasks gulp.task('minify-css', function() { var opts = {comments:true,spare:true}; gulp.src(['./app/**/*.css', '!./app/bower_components/**']) .pipe(minifyCSS(opts)) .pipe(gulp.dest('./web/css/')) }); gulp.task('templates', function() { gulp.src('./ngApp/templates/**/*.html') .pipe(minifyHtml({empty: true, quotes: true})) .pipe(ngTemplate({ moduleName: 'SymfonyAppTpl', standalone: true, filePath: 'templates.js' })) .pipe(gulp.dest('./ngApp/')) }); gulp.task('minify-js', function() { gulp.src(['./ngApp/**/*.js']) .pipe(gp_concat('app.js')) .pipe(uglify()) .pipe(gulp.dest('./web/js/')) }); // default task gulp.task('default', ['lint', 'connect'] ); gulp.task('build', function() { runSequence( ['minify-css','templates', 'minify-js'] ); });
253076815ae67a521b5f7272df57ca443bbef3ec
[ "JavaScript", "PHP" ]
25
PHP
mikitu/Symfony2Rest
c3afd6730f22ad69bbb21df0be2dc97e5fc1887d
77750d82af6f790568563f35440488ccfb06c719
refs/heads/master
<repo_name>KSMubasshir/algo-trading<file_sep>/dse_data_loader_pkg/dse_data_loader/__init__.py #!/usr/bin/env python __author__ = "<NAME>" __copyright__ = "Copyright (c) 2021 The Python Packaging Authority" from .dse_data_loader import PriceData from .dse_data_loader import FundamentalData from .price_plots import CandlestickPlot <file_sep>/dse_data_loader_pkg/README.md ## Description This is a Python library based on *beautifulsoup4*, *pandas* & *mplfinance* to download price data and fundamental data of companies from Dhaka Stock Exchange. <br/>This can assist you to create further analyses based on fundamental and price history data. <br/>Also create Candlestick charts to analyse price history of stocks using a simple wrapper for mplfinance. ## Installation ``` pip install dse-data-loader ``` ## Usage #### Downloading historical price data of a single stock- ```python from dse_data_loader import PriceData loader = PriceData() loader.save_history_csv('ACI', file_name='ACI_history.csv') ``` The above code will create a file named- 'ACI_history.csv'. It'll contain historical price data for ACI Limited. 'ACI' is the stock symbol. #### Downloading current price data of all listed companies in DSE- ```python from dse_data_loader import PriceData loader = PriceData() loader.save_current_csv(file_name='current_data.csv') ``` The above code will create a file named- 'ACI_history.csv' in the current folder. It'll contain current price data for all symbols. #### Downloading fundamental data for a list of companies available in DSE- ```python from dse_data_loader import FundamentalData loader = FundamentalData() loader.save_company_data(['ACI', 'GP', 'WALTONHIL'], path='company_info') ``` The above code will create two files named 'company_data.csv' & 'financial_data.csv' in the 'company_info' folder relative to current directory. The file named company_data.csv contains the fundamental data of ACI Limited, GP and Walton BD for the current year and financial_data.csv contains year-wise fundamental data according to [DSE website](http://dsebd.org). #### Create Candlestick charts for analyzing price history- ```python from dse_data_loader import CandlestickPlot cd_plot = CandlestickPlot(csv_path='ACI_history.csv', symbol='ACI') cd_plot.show_plot( xtick_count=120, resample=True, step='3D' ) ``` The above code will create a Candlestick plot like the ones provided by Stock broker trading panels. There are 3 parameters- 1. ```xtick_count``` : Provide an integer value. It sets the count of how many recent data points needs to be plotted. 2. ```resample``` : Provide boolean ```True``` or ```False```. Set ```True``` if you want to plot daily data aggregated by multiple days. 3. ```step```: Only Active when ```resample=True```. Valid values are in the form- ```'3D'``` and ```'7D'``` for 3 days plots and weekly plots respectively. The following are some example images of Candlestick plots- ![Candlestick Plot](https://github.com/skfarhad/algo-trading/blob/master/dse_data_loader_pkg/example_plot.jpg?raw=true) <br><br>![Candlestick Plot 3days](https://github.com/skfarhad/algo-trading/blob/master/dse_data_loader_pkg/example_plot_3D.jpg?raw=true) This is the minimal documentation. It'll be improved continuously (hopefully!).
38e959736918760ebb49236db209df92beb75d54
[ "Markdown", "Python" ]
2
Python
KSMubasshir/algo-trading
9e3481accb8d5eefa475228d9b9d7a584d9fb791
246614b88e70804fa4547e0b8a6d6e5b3092b60a
refs/heads/master
<file_sep>import renderMiniImg from "./miniature.js"; import debounce from "./debounce.js"; function filterMin(array) { const RANDOM_MINS_NUMBER = 10; const filterForm = document.querySelector(`.filters`); const filterRadios = filterForm.elements.filter; const randomMins = new Set(); const discussedMins = array.slice(); filterForm.classList.remove(`hidden`); filterRadios.forEach((elem) => { elem.addEventListener(`change`, function(evt) { randomMins.clear(); switch (evt.target.id) { case `filter-popular`: debounce(renderMiniImg, array); break; case `filter-random`: while (randomMins.size < RANDOM_MINS_NUMBER) { randomMins.add(getRandomElement(array)); } debounce(renderMiniImg, Array.from(randomMins)); break; case `filter-discussed`: discussedMins.sort((a, b) => b.comments.length - a.comments.length); debounce(renderMiniImg, discussedMins); break; } }); }); } function getRandomElement(array) { return array[Math.floor(Math.random() * array.length)]; } export default filterMin; <file_sep>const commentsList = document.querySelector(`.social__comments`); const bigImg = document.querySelector(`.gallery-overlay`); const loadmoreButton = bigImg.querySelector(`.comments-loadmore`); function renderMiniImg(array) { const miniTemplate = document.querySelector(`#picture-template`); const fragment = document.createDocumentFragment(); const pictures = document.querySelector(`.pictures`); array.forEach((elem) => { const miniImg = miniTemplate.cloneNode(true).content.firstElementChild; fragment.append(miniImg); miniImg.firstElementChild.src = elem.url; miniImg.querySelector(`.picture-comments`).innerHTML = elem.comments.length; miniImg.querySelector(`.picture-likes`).innerHTML = elem.likes; bindMiniImg(miniImg, elem); }); pictures.innerHTML = ``; pictures.append(fragment); } function bindMiniImg(img, elem) { const DEFAULT_COMMENTS_NUMBER = 5; const closeButton = bigImg.querySelector(`.gallery-overlay-close`); img.addEventListener(`click`, function(evt) { evt.preventDefault(); bigImg.classList.remove(`hidden`); (elem.comments.length > DEFAULT_COMMENTS_NUMBER) ? loadmoreButton.classList.remove(`hidden`) : loadmoreButton.classList.add(`hidden`); bigImg.querySelector(`.gallery-overlay-image`).src = img.firstElementChild.src; bigImg.querySelector(`.likes-count`).innerHTML = img.querySelector(`.picture-likes`).innerHTML; bigImg.querySelector(`.comments-count`).innerHTML = img.querySelector(`.picture-comments`).innerHTML; commentsList.innerHTML = ``; elem.comments.forEach((comment, index) => { const mimiImgElement = (index > 4) ? `<li class="social__comment social__comment--text hidden"> <img class="social__picture" src=${comment.avatar}></img>${comment.message}<li>` : `<li class="social__comment social__comment--text"> <img class="social__picture" src=${comment.avatar}></img>${comment.message}<li>`; commentsList.insertAdjacentHTML(`beforeend`, mimiImgElement); }); closeButton.addEventListener(`click`, hideBigImg); closeButton.addEventListener(`keydown`, enterPressHandler); window.addEventListener(`keydown`, escPressHandler); loadmoreButton.addEventListener(`click`, loadmoreClickHandler); }); } function loadmoreClickHandler(evt) { let openCommentsCounter = 0; Array.from(commentsList.children).forEach((elem) => { if (!elem.classList.contains(`hidden`) && elem.classList.contains(`social__comment--text`)) { openCommentsCounter += 2; } }); for (let i = openCommentsCounter; i < openCommentsCounter + 10; i++) { if (i === commentsList.children.length) { evt.target.classList.add(`hidden`); return; } commentsList.children[i].classList.remove(`hidden`); } } function enterPressHandler(evt) { const ESC_CODE = `Enter`; if (evt.code === ESC_CODE) { hideBigImg(); } } function escPressHandler(evt) { const ESC_CODE = `Escape`; if (evt.code === ESC_CODE) { hideBigImg(); } window.removeEventListener(`keydown`, escPressHandler); } function hideBigImg() { bigImg.classList.add(`hidden`); loadmoreButton.removeEventListener(`click`, loadmoreClickHandler); } export default renderMiniImg; <file_sep>import style from "./css/main.css"; import { loadImages } from "./js/loader.js"; import userInput from "./js/upload.js"; import draggablePin from "./js/slider.js"; loadImages(); // import getYear from "./js/webformyself.js"; <file_sep>const DEBOUNCE_TIMEOUT = 500; let timeout = null; function debounce(func, ...args) { if (timeout) { clearTimeout(timeout); } timeout = setTimeout(function() { func.call(null, ...args); }, DEBOUNCE_TIMEOUT); } export default debounce; <file_sep>const path = require("path"); const webpack = require("webpack"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const PATHS = { src: path.join(__dirname, "../src"), build: path.join(__dirname, "../build") }; module.exports = { context: path.resolve(__dirname, "./src"), externals: { paths: PATHS }, entry: { bundle: `${PATHS.src}/index.js` }, output: { filename: "./js/[name].js", path: PATHS.build }, watch: true, module: { rules: [ // { // enforce: "pre", // test: /\.js$/, // exclude: /node_modules/, // use: { // loader: "eslint-loader" // } // }, // { // test: /\.js$/, // exclude: /node_modules/, // use: { // loader: "babel-loader", // options: { // presets: ["env"] // } // } // }, { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, { loader: "css-loader", options: { sourceMap: true } } // , // "postcss-loader" ] }, { test: /\.(jpe?g|png|gif|svg)$/, use: { loader: "url-loader", options: { name: "[name].[ext]", outputPath: `${PATHS.build}/img` } } } // { // test: /test\.js$/, // use: "mocha-loader", // exclude: /node_modules/ // } // { // test: /\.svg$/, // loader: "svg-sprite-loader", // include: /.*sprite\.svg/ // } ] }, plugins: [ new HtmlWebpackPlugin({ template: `${PATHS.src}/index.html` }), new MiniCssExtractPlugin({ filename: "css/style.css" }), new CopyWebpackPlugin([ { from: `${PATHS.src}/img`, to: `${PATHS.build}/img` }, { from: `${PATHS.src}/photos`, to: `${PATHS.build}/photos` } ]), new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }) ], resolve: { extensions: [".js", ".json", ".jsx", "*"] } }; <file_sep>import setSlider from "./slider.js"; function readImg(file) { const reader = new FileReader(); reader.readAsDataURL(file); reader.addEventListener(`load`, function(evt) { const IMAGE_HEIGHT = 500; const imageURL = evt.target.result; const imagePreview = document.querySelector(`.effect-image-preview`); document.querySelector(`.upload-overlay`).classList.remove(`hidden`); setSlider(); imagePreview.src = imageURL; document.querySelectorAll(`.upload-effect-preview`).forEach((elem) => { elem.style.backgroundImage = `url(${imageURL})`; }); imagePreview.width = IMAGE_HEIGHT; }); } export default readImg; <file_sep>import { validateForm, hideUserMistake } from "./validateForm.js"; import readImg from "./reader.js"; import sendData from "./sender.js"; const SCALE_DELTA = 25; const userInput = document.querySelector(`#upload-file`); const uploadMenu = document.querySelector(`.upload-overlay`); const decButton = uploadMenu.querySelector(`.upload-resize-controls-button-dec`); const incButton = uploadMenu.querySelector(`.upload-resize-controls-button-inc`); const resizeValue = uploadMenu.querySelector(`.upload-resize-controls-value`); const uploadImage = uploadMenu.querySelector(`.effect-image-preview`); const uploadForm = document.querySelector(`.upload-form`); const hashtagInput = uploadForm.elements.hashtags; const commentsTextarea = uploadForm.elements.description; const submitButton = uploadForm.querySelector(`.upload-form-submit`); userInput.addEventListener(`change`, function(evt) { readImg(evt.target.files[0]); }); uploadMenu.querySelector(`#upload-cancel`).addEventListener(`click`, hideUploadMenu); addEscPressHandler(); function escPressHandler(evt) { const ESC_CODE = `Escape`; if (evt.code === ESC_CODE) { hideUploadMenu(); } removeEscPressHandler(); } function hideUploadMenu() { uploadMenu.classList.add(`hidden`); uploadImage.style = ``; uploadImage.className = `effect-image-preview`; document.querySelector(`.upload-effect-level-val`).style.width = `100%`; document.querySelector(`.upload-effect-level-pin`).style.left = `100%`; hideUserMistake(hashtagInput); hideUserMistake(commentsTextarea); } decButton.addEventListener(`click`, function() { let currentVal = parseInt(resizeValue.value, 10); if (currentVal >= 50) { resizeValue.value = `${currentVal -= SCALE_DELTA}%`; scaleImage(currentVal); } }); incButton.addEventListener(`click`, function() { let currentVal = parseInt(resizeValue.value, 10); if (currentVal <= 75) { resizeValue.value = `${currentVal += SCALE_DELTA}%`; scaleImage(currentVal); } }); function scaleImage(val) { if (val === 100) { uploadImage.style = ``; return; } uploadImage.style.transform = `scale(${val / 100})`; } function addEscPressHandler() { window.addEventListener(`keydown`, escPressHandler); } function removeEscPressHandler() { window.removeEventListener(`keydown`, escPressHandler); } submitButton.addEventListener(`mousedown`, function(evt) { const isValid = validateForm(); if (!isValid) { evt.preventDefault(); return; } }); uploadForm.addEventListener(`submit`, function(evt) { evt.preventDefault(); const formdata = new FormData(uploadForm); sendData(formdata); }); hashtagInput.addEventListener(`focus`, function() { removeEscPressHandler(); }); hashtagInput.addEventListener(`blur`, function() { addEscPressHandler(); }); commentsTextarea.addEventListener(`focus`, function() { removeEscPressHandler(); }); commentsTextarea.addEventListener(`blur`, function() { addEscPressHandler(); }); export default userInput; <file_sep>function setSlider() { const draggablePin = document.querySelector(`.upload-effect-level-pin`); const slider = document.querySelector(`.upload-effect-level`); const sliderLine = document.querySelector(`.upload-effect-level-line`); const sliderLineCoordX = sliderLine.getBoundingClientRect().x; const sliderValueLine = document.querySelector(`.upload-effect-level-val`); const uploadImage = document.querySelector(`.effect-image-preview`); const effectRadios = document.querySelector(`.upload-form`).elements.effect; let currentFilter = null; effectRadios.forEach((elem) => { elem.addEventListener(`change`, function(evt) { uploadImage.classList.remove(currentFilter); currentFilter = evt.target.id.split(`upload-`).join(``); sliderValueLine.style.width = `100%`; draggablePin.style.left = `100%`; if (currentFilter === `effect-none`) { slider.classList.add(`hidden`); } else { slider.classList.remove(`hidden`); } uploadImage.style.filter = ``; uploadImage.classList.add(currentFilter); }); }); draggablePin.addEventListener(`mousedown`, function(downEvt) { downEvt.preventDefault(); let startCoordX = downEvt.clientX; downEvt.target.addEventListener(`mousemove`, pinMousemoveHandler); function pinMousemoveHandler(moveEvt) { moveEvt.preventDefault(); const shift = moveEvt.clientX - startCoordX; startCoordX = moveEvt.clientX; if (startCoordX < sliderLineCoordX) { draggablePin.style.left = 0 + `px`; } else if (startCoordX > sliderLineCoordX + sliderLine.clientWidth) { draggablePin.style.left = sliderLine.clientWidth + `px`; } else { draggablePin.style.left = draggablePin.offsetLeft + shift + `px`; } const intensity = parseInt(draggablePin.style.left, 10) / sliderLine.clientWidth; sliderValueLine.style.width = intensity * 100 + `%`; switch (currentFilter) { case `effect-chrome`: uploadImage.style.filter = `grayscale(${intensity})`; break; case `effect-sepia`: uploadImage.style.filter = `sepia(${intensity})`; break; case `effect-marvin`: uploadImage.style.filter = `invert(${intensity * 100}%)`; break; case `effect-phobos`: uploadImage.style.filter = `blur(${intensity * 5}px)`; break; case `effect-heat`: uploadImage.style.filter = `brightness(${1 + intensity * 2})`; break; } } draggablePin.addEventListener(`mouseup`, pinMouseUpHandler); function pinMouseUpHandler(upEvt) { upEvt.preventDefault(); upEvt.target.removeEventListener(`mousemove`, pinMousemoveHandler); draggablePin.removeEventListener(`mouseup`, pinMouseUpHandler); } }); } export default setSlider; <file_sep>function checkAndLogAge(year, checkYear, testee) { if (getYear(year) > checkYear) { console.log(`${testee} старше ${checkYear} лет`); } else { console.log(`${testee} не старше ${checkYear} лет`); } } function getYear(year) { const CURRENT_YEAR = 2019; return CURRENT_YEAR - year; } checkAndLogAge(2001, 18, `Максон`); export default getYear;
9809a25d71d0d32fc6eb29b6840a98c1d788aadc
[ "JavaScript" ]
9
JavaScript
financialmonster/kekstagram
986fdcdb9e1e22a8b78705ba786d7f4ff08beb66
3c5837eb074e506d35f480de2a58656abb4035e7
refs/heads/master
<repo_name>OSn-project/nmare<file_sep>/lexer.h #ifndef __NMARE_PARSER_H__ #define __NMARE_PARSER_H__ #include <stdio.h> #include <base/string.h> #include "token.h" class Lexer { BString buffer; // Text since the last token that hasn't been parsed yet enum { NORMAL, IGNORE_LINE, // Ignore until the end of the line READ_LITERAL // Read into the buffer until the next `"` } state; public: Token *tokens; Lexer(); ~Lexer(); bool parse(FILE *file); private: void read_literal(); void reset(); // Clears the buffer of the currently read token void create_token(); // Create a token from the current state. void add(Token *tok); }; #endif <file_sep>/Makefile TARGET = nmare LIBBASE_SRC = ../OSn/root/libs/libbase LIBS = $(LIBBASE_SRC)/src/libbase.a CC = clang++ CFLAGS = -g -O0 -Wall -isystem $(LIBBASE_SRC)/include .PHONY: default all clean default: $(TARGET) all: default OBJECTS = main.o lexer.o token.o %.o: %.cpp $(CC) $(CFLAGS) -c $< -o $@ .PRECIOUS: $(TARGET) $(OBJECTS) $(TARGET): $(OBJECTS) $(CC) $(OBJECTS) -Wall $(LIBS) -o $@ clean: -rm -f *.o -rm -f $(TARGET) <file_sep>/token.h #ifndef __NMARE_TOKEN_H__ #define __NMARE_TOKEN_H__ #include <osndef.h> #include <base/string.h> #include <base/listnode.h> enum TokenType { UNKNOWN = 0, IDENTIFIER, STR_LITERAL, ASSIGNMENT, ADDITION, DICT_OPEN, DICT_CLOSE, }; struct Token : public BListNode { TokenType type; BString text; /* Functions */ static const char *type_name(TokenType type); static void print(Token *token); }; #endif <file_sep>/main.cpp #include <stdio.h> #include <stdlib.h> #include <base/string.h> #include "lexer.h" int main(int argc, char *argv[]) { if (argc <= 1) { printf("%s <file>\n", argv[0]); exit(1); } FILE *file = fopen(argv[1], "r"); if (file == NULL) { fprintf(stderr, "[ERROR] Error opening file:\n%s\n", argv[0]); exit(1); } { Lexer lexer; lexer.parse(file); } fclose(file); return 0; } <file_sep>/token.cpp #include <stdlib.h> #include <base/listnode.h> #include "token.h" const char *Token :: type_name(TokenType type) { switch (type) { case IDENTIFIER: return "IDENTIFIER"; case STR_LITERAL: return "STR_LITERAL"; case ASSIGNMENT: return "ASSIGNMENT"; case ADDITION: return "ADDITION"; case DICT_OPEN: return "DICT_OPEN"; case DICT_CLOSE: return "DICT_CLOSE"; default: return "UNKNOWN"; } } #include <stdio.h> void Token :: print(Token *token) { printf("{type = %s, text = \"%s\"}\n", Token::type_name(token->type), token->text.c_str()); } <file_sep>/lexer.cpp #include <stdlib.h> #include <stdint.h> #include <ctype.h> #include <string.h> #include <base/string.h> #include <base/listnode.h> #include "lexer.h" #include "token.h" static char operators[] = "{}\"+="; Lexer :: Lexer() { this->reset(); this->tokens = NULL; } Lexer :: ~Lexer() { for (Token *token = this->tokens; token != NULL; token = (Token *) token->next) { delete token; } } void Lexer :: reset() { this->buffer.clear(); } bool Lexer :: parse(FILE *file) { /* Go through each character of the file, appending it * * to a buffer. When it is determined that the end of a * * token has been reached, create it. */ for (int32_t byte; (byte = fgetc(file)) != EOF;) { /* Both of these decisions cause us to create a token * * from what was already in the buffer because of the * * byte that we've just read. */ if (isspace(byte)) { /* If we have encountered whitespace, we have either reached * * the end of a token or are within a larger block of whitespace. * * In the former case, we need the token to be appended to the list,* * and in the latter case the function will return immediately * * since buffer is empty. */ this->create_token(); continue; } if (strchr(operators, byte) != NULL) { /* If we've encountered an operator, we have to save the pending token first. */ this->create_token(); } this->buffer.append_c(byte); /* The following decisions are made based * * upon the text in the buffer, now that the * * byte has been added to it. */ if (strchr(operators, byte) != NULL) { /* If the current character is an operator, append it to the list. * * Multiple-character operators are dealt with by ->create_token() too. */ this->create_token(); } if ((char) byte == '"') { while ((byte = fgetc(file)) != '"') { if (byte == EOF) { #error } this->buffer.append_c((char) byte); } { Token *token = new Token(); token->text.set(buffer); BListNode::append(token, (BListNode **) &this->tokens); } } } return true; } void Lexer :: create_token() { /* Here we make the judgement of what the token actually *is*, and then add it to the list */ Token *token = new Token(); if (this->buffer.length() == 0) { return; } /* Literals */ else if (BString::equals(&this->buffer, "\"")) { /* We're either at the start of the end of a string literal */ token->type = STR_LITERAL; // if () } /* Brackets */ else if (BString::equals(&this->buffer, "=")) { token->type = ASSIGNMENT; } else if (BString::equals(&this->buffer, "+")) { token->type = ADDITION; } else if (BString::equals(&this->buffer, "{")) { token->type = DICT_OPEN; } else if (BString::equals(&this->buffer, "}")) { token->type = DICT_CLOSE; } /* Else it must be an identifier */ else { token->type = IDENTIFIER; token->text.set(&this->buffer); } Token::print(token); BListNode::append(token, (BListNode **) &this->tokens); this->reset(); return; error: delete token; this->reset(); }
aaa8813eb9f3bb0fec9dca1d160975edd1556c9e
[ "C", "Makefile", "C++" ]
6
C++
OSn-project/nmare
91012a3ea631a23a0e474afdcda26cbf5a36f780
7923121630f537f052eee4ceb38c7bffa07c79d1
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class TreeRegrow: MonoBehaviour { public static TreeRegrow instance; public GameObject sapling; void Start(){ instance = this; } public void NewTree(Vector3 position){ GameObject babytree = Instantiate (sapling); babytree.transform.position = position; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public partial class Elephant: MonoBehaviour { // --------------------------------------------------------- void OnTriggerEnter(Collider other){ print ("trigger: " + other.gameObject.tag); if (other.gameObject.tag == "Key") { has_key = true; Destroy (other.gameObject); }else if (other.gameObject.tag == "Help Point") { if (other.gameObject.name == "Help Point A") { HUD.instance.toDisplay.Enqueue (0); needs_help = true; Destroy (other.gameObject); } else if (other.gameObject.name == "Help Point B") { HUD.instance.toDisplay.Enqueue (1); needs_help = true; Destroy (other.gameObject); } else if (other.gameObject.name == "Help Point C") { HUD.instance.toDisplay.Enqueue (2); needs_help = true; Destroy (other.gameObject); } else if (other.gameObject.name == "Help Point D") { HUD.instance.toDisplay.Enqueue (3); needs_help = true; Destroy (other.gameObject); } else if (other.gameObject.name == "Help Point Tree") { if (water_meter > 0) { HUD.instance.toDisplay.Enqueue (2); needs_help = true; Destroy (other.gameObject); } } } else if (other.gameObject.tag == "Water") near_water = true; } void OnTriggerExit(Collider other){ if (other.gameObject.tag == "Water") near_water = false; } void OnCollisionEnter(Collision coll){ print ("collision: " + coll.gameObject.tag); if (coll.gameObject.tag == "Ground") { rb.velocity = Vector3.zero; jumping = false; } else if (coll.gameObject.tag == "Baby Elephant") { PlayElephantSound (); print ("You win!"); HUD.instance.ShowWinSequence (); } else if (coll.gameObject.tag == "Cage") { if (has_key) { has_key = false; Destroy (coll.gameObject); } } else if (coll.gameObject.tag == "Spikes" || coll.gameObject.tag == "Wildfire") { PlaySpikeSound (); transform.position = init_pos; spiked = true; GetComponent<SpriteRenderer> ().enabled = false; GetComponent<Rigidbody> ().isKinematic = true; if (direction == "right") { pause_elephant.GetComponent<SpriteRenderer> ().flipX = false; } else { pause_elephant.GetComponent<SpriteRenderer> ().flipX = true; } } } void RespawnElephant(){ pause_elephant.SetActive (true); Color c = pause_elephant.GetComponent<SpriteRenderer> ().color; if (c.a == 0f) { lives -= 1; } c.a += 0.01f; pause_elephant.GetComponent<SpriteRenderer> ().color = c; if (pause_elephant.GetComponent<SpriteRenderer> ().color.a >= 0.9f) { c = pause_elephant.GetComponent<SpriteRenderer> ().color; c.a = 0f; pause_elephant.GetComponent<SpriteRenderer> ().color = c; pause_elephant.SetActive (false); spiked = false; GetComponent<SpriteRenderer> ().enabled = true; GetComponent<Rigidbody> ().isKinematic = false; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public partial class Tree: MonoBehaviour { public int grow_time = 0; public bool reminder_tree = false; public int max_growth = 20; public bool to_knock_down = false; public bool knocked_down = false; public bool started_growing = false; public int growth = 0; public Vector3 initial_pos; public GameObject sapling; void Update(){ if (!started_growing) initial_pos = this.transform.position; bool Z_Key = Input.GetKeyDown (KeyCode.Z); bool Z_up = Input.GetKeyUp (KeyCode.Z); if (Z_Key) { GetComponent<BoxCollider> ().enabled = true; } if (Z_up && !knocked_down){ GetComponent<BoxCollider> ().enabled = false; } Grow (); if (growth >= max_growth && !knocked_down) { Blink (); } if (knocked_down) { Fade (); if (GetComponent<SpriteRenderer> ().color.a <= 0.002f) { // print ("hello dead tree"); // print(initial_pos); TreeRegrow.instance.NewTree (initial_pos); Destroy (this.gameObject); } } } void OnCollisionEnter(Collision other){ if (other.gameObject.tag == "Elephant") { if (!to_knock_down && !knocked_down && growth >= max_growth) { Color c = this.GetComponent<SpriteRenderer> ().color; c.a = 1f; this.GetComponent<SpriteRenderer> ().color = c; to_knock_down = true; KnockDown (); } } } void Grow(){ if (grow_time > 0) { started_growing = true; grow_time -= 1; if (growth < max_growth) { Vector3 scale = this.transform.localScale; scale.x += 0.1f; scale.y += 0.1f; this.transform.localScale = scale; Vector3 pos = this.transform.position; pos.y += 0.293f; this.transform.position = pos; growth += 1; } if (reminder_tree && growth >= max_growth) { Elephant.instance.needs_help = true; HUD.instance.toDisplay.Enqueue (3); reminder_tree = false; } } } //Grow void KnockDown(){ if (to_knock_down) { Elephant.instance.PlayTreeSound (); knocked_down = true; to_knock_down = false; if (Elephant.instance.direction == "right") { Quaternion target = Quaternion.Euler (0f, 0f, -90f); this.transform.rotation = target; Vector3 pos = this.transform.position; pos.y -= 8.14f; pos.x = Elephant.instance.transform.position.x + 10.2f; this.transform.position = pos; } else if (Elephant.instance.direction == "left") { Quaternion target = Quaternion.Euler (0f, 0f, 90f); this.transform.rotation = target; Vector3 pos = this.transform.position; pos.y -= 7.64f; pos.x = Elephant.instance.transform.position.x - 10.2f; this.transform.position = pos; } this.GetComponent<BoxCollider> ().enabled = true; } } void Fade(){ Color c = this.GetComponent<SpriteRenderer> ().color; c.a -= 0.002f; this.GetComponent<SpriteRenderer> ().color = c; } private int blink_time = 10; void Blink(){ blink_time -= 1; if (blink_time <= 0) { blink_time = 10; Color c = this.GetComponent<SpriteRenderer> ().color; if (c.a == 1) { c.a = 0.5f; this.GetComponent<SpriteRenderer> ().color = c; } else { c.a = 1f; this.GetComponent<SpriteRenderer> ().color = c; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class LevelSelect : MonoBehaviour { public static LevelSelect instance; public GameObject[] upper_levels; public GameObject[] lower_levels; public GameObject selector; void Awake() { LevelSelect.instance = this; } // Use this for initialization void Start () { } private bool Right; private bool Left; private bool Space; private bool Down; private bool Up; private bool Q_key; void Update(){ Right = Input.GetKeyDown (KeyCode.RightArrow); Left = Input.GetKeyDown (KeyCode.LeftArrow); Down = Input.GetKeyDown (KeyCode.DownArrow); Up = Input.GetKeyDown (KeyCode.UpArrow); Q_key = Input.GetKeyDown (KeyCode.Q); moveSelector (Right, Left, Up, Down); Space = Input.GetKeyDown (KeyCode.Space); if (Q_key) { Application.Quit (); } if (Space) { if (top) { if (selector_position == 0) { SceneManager.LoadScene ("Level_one", LoadSceneMode.Single); } else if (selector_position == 1) { SceneManager.LoadScene ("Level_two", LoadSceneMode.Single); } else if (selector_position == 2) { SceneManager.LoadScene ("Level_three", LoadSceneMode.Single); } } else { if (selector_position == 0) { SceneManager.LoadScene ("Level_four", LoadSceneMode.Single); } else if (selector_position == 1) { SceneManager.LoadScene ("Level_five", LoadSceneMode.Single); } else if (selector_position == 2) { SceneManager.LoadScene ("Level_six", LoadSceneMode.Single); } } } } private int selector_position = 0; private bool top = true; void moveSelector(bool Right, bool Left, bool Up, bool Down){ if (Down && top) { top = false; GameObject level = upper_levels [selector_position]; float adjust = selector.transform.position.y; adjust -= level.transform.position.y; level = lower_levels [selector_position]; //print (level.transform.position.y); adjust += level.transform.position.y; adjust -= selector.transform.position.y; selector.transform.position += new Vector3 (0, adjust, 0); } else if (Up && !top) { GameObject level = upper_levels [selector_position]; float adjust = selector.transform.position.y; adjust -= level.transform.position.y; level = lower_levels [selector_position]; //print (level.transform.position.y); adjust += level.transform.position.y; adjust -= selector.transform.position.y; selector.transform.position += new Vector3 (0, -1 * adjust, 0); top = true; } else if (Right && selector_position < 2) { selector_position += 1; GameObject level = upper_levels [selector_position]; float adjust = level.transform.position.x; adjust -= selector.transform.position.x; //print (level.transform.position); //print (level.name); selector.transform.position += new Vector3 (adjust, 0, 0); } else if(Left && selector_position > 0){ selector_position -= 1; GameObject level = upper_levels [selector_position]; //print (level.name); float adjust = level.transform.position.x; adjust -= selector.transform.position.x; selector.transform.position += new Vector3 (adjust, 0, 0); } } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public partial class Elephant: MonoBehaviour { public static Elephant instance; public int lives = 3; public bool has_key = false; public bool jumping = false; public bool walking = false; public bool drinking = false; public bool knocked_tree = false; public bool spiked = false; public GameObject pause_elephant; public bool needs_help = false; public int water_meter = 0; public int max_water = 20; public Sprite[] walking_sprites; public Sprite[] drinking_sprites; public Sprite normal_sprite; public Sprite trunk_up_sprite; public GameObject water_drip; protected bool Spacebar; protected bool LeftArrow; protected bool RightArrow; protected bool RightArrow_up; protected bool LeftArrow_up; protected bool Z_Key; protected bool X_Key; protected bool X_Keyup; protected bool Spacebar_up; protected bool start_spraying; public bool near_water = false; protected Rigidbody rb; protected Vector3 init_pos; protected int drip_delay = 0; public string direction = "right"; // Use this for initialization // --------------------------------------------------------- void Start () { if (instance != null) print("multiple elephants!!"); instance = this; init_pos = this.transform.position; rb = GetComponent<Rigidbody> (); } // Update is called once per frame // --------------------------------------------------------- private float right_prev = 0f; private float left_prev = 0f; private float water_drink_fraction = 0f; void Update () { animation_state_machine.Update (); if (animation_state_machine.IsFinished ()) { animation_state_machine.ChangeState (NextAnimationState ()); } float horizontal = Input.GetAxis ("Horizontal"); RightArrow = horizontal > 0.0f; LeftArrow = horizontal < 0.0f; Spacebar = Input.GetKeyDown (KeyCode.Space); Z_Key = Input.GetKeyDown (KeyCode.Z); X_Key = Input.GetKeyDown (KeyCode.X); X_Keyup = Input.GetKeyUp (KeyCode.X); Vector3 vel = rb.velocity; vel.x = 0f; rb.velocity = vel; // CHECK IF BUTTON STILL PRESSED if (RightArrow && right_prev > horizontal){ RightArrow = false; } else if (LeftArrow && left_prev < horizontal) { LeftArrow = false; } if (RightArrow) right_prev = horizontal; else right_prev = 0f; if (LeftArrow) left_prev = horizontal; else left_prev = 0f; //-------------------------- if (rb.velocity.x <= 0.5) { walking = false; } if (rb.velocity.y > 0.05 || rb.velocity.y < -0.05) { jumping = true; } else { jumping = false; } if (RightArrow && !drinking) { direction = "right"; walking = true; vel.x = 8f; rb.velocity = vel; GetComponent<SpriteRenderer> ().flipX = false; } else if (LeftArrow && !drinking) { direction = "left"; walking = true; vel.x = -8f; rb.velocity = vel; GetComponent<SpriteRenderer> ().flipX = true; } Spacebar_up = Input.GetKeyUp (KeyCode.Space); if (Spacebar) { if (!jumping) Jump (); } else if (Spacebar_up) { Vector3 jump_vel = rb.velocity; if (jump_vel.y > 0f) { jump_vel.y = 0f; rb.velocity = jump_vel; } } if (X_Key && near_water) { print ("X"); drinking = true; animation_state_machine.ChangeState (new State_Animation_Drinking (8, this)); } if (drinking) { if (water_meter < max_water) { water_drink_fraction += 0.1f; if (water_drink_fraction >= 1f) { water_meter += 1; water_drink_fraction = 0f; } } } if (X_Key && !near_water && water_meter > 0 && !start_spraying && !spiked) { start_spraying = true; } if (X_Keyup) { drinking = false; animation_state_machine.ChangeState (new State_Animation_Movement (8, this)); drip_delay = 0; start_spraying = false; } if (start_spraying && !walking && !jumping) { animation_state_machine.ChangeState (new State_Animation_TrunkUp (16, this)); SprayWater (); } else { start_spraying = false; drip_delay = 0; } if (Z_Key) { print ("Z"); } // Spike return: if (spiked) { RespawnElephant (); } } // --------------------------------------------------------- void Jump(){ PlayJumpSound (); animation_state_machine.ChangeState (new State_Animation_Flying (12, this)); jumping = true; Vector3 vel = rb.velocity; vel.y = 15f; rb.velocity = vel; } void SprayWater(){ drip_delay -= 1; if (drip_delay <= 0 && water_meter > 0) { PlayWaterSound (); water_meter -= 1; GameObject droplet = Instantiate (water_drip); if (direction == "right") { droplet.transform.position = this.transform.position; droplet.transform.position += new Vector3 (2.5f, -0.6f, 0); droplet.GetComponent<Rigidbody> ().velocity = new Vector3 (2.0f, -4.0f, 0.0f); } else if (direction == "left") { droplet.transform.position = this.transform.position; droplet.transform.position += new Vector3 (-2.5f, -0.6f, 0); droplet.GetComponent<Rigidbody> ().velocity = new Vector3 (-2.0f, -4.0f, 0.0f); } drip_delay = 15; } } //------------- } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public partial class Elephant: MonoBehaviour { public Sprite flying_sprite; protected StateMachine animation_state_machine = new StateMachine(); public class State_Animation_Movement : State { private float elapsedTime = 0.0f; private uint sprite_index = 0; private float spriteChangeRate; private Elephant Ella; public State_Animation_Movement(float spriteChangeRate, Elephant Ella) { this.spriteChangeRate = spriteChangeRate; elapsedTime = spriteChangeRate; this.Ella = Ella; } public override void OnFinish() { Ella.GetComponent<SpriteRenderer> ().sprite = Ella.normal_sprite; } public override void OnUpdate (float time_delta_fraction) { if (Ella.walking) elapsedTime += 1; if (!Ella.walking) { Ella.GetComponent<SpriteRenderer> ().sprite = Ella.normal_sprite; return; } else if (Ella.jumping) { ConcludeState (); } if (elapsedTime >= spriteChangeRate) { Ella.GetComponent<SpriteRenderer> ().sprite = Ella.walking_sprites [sprite_index]; sprite_index += 1; if (sprite_index >= Ella.walking_sprites.Length) sprite_index = 0; elapsedTime = 0; } } } public class State_Animation_Flying : State{ private float spriteChangeRate; private float elapsedTime = 0.0f; private Elephant Ella; public State_Animation_Flying(float spriteChangeRate, Elephant Ella) { this.spriteChangeRate = spriteChangeRate; elapsedTime = spriteChangeRate; this.Ella = Ella; } public override void OnFinish() { Ella.GetComponent<SpriteRenderer> ().sprite = Ella.normal_sprite; } public override void OnUpdate (float time_delta_fraction) { if (!Ella.jumping) ConcludeState (); if (Ella.jumping) elapsedTime += 1; if (Ella.drinking || Ella.walking && !Ella.jumping) { Ella.GetComponent<SpriteRenderer> ().sprite = Ella.normal_sprite; ConcludeState(); } if (elapsedTime >= spriteChangeRate) { if (Ella.GetComponent<SpriteRenderer> ().sprite != Ella.flying_sprite) Ella.GetComponent<SpriteRenderer> ().sprite = Ella.flying_sprite; else Ella.GetComponent<SpriteRenderer> ().sprite = Ella.normal_sprite; elapsedTime = 0; } } } public class State_Animation_Drinking : State { private float elapsedTime = 0.0f; private uint sprite_index = 0; private float spriteChangeRate; private Elephant Ella; public State_Animation_Drinking(float spriteChangeRate, Elephant Ella) { this.spriteChangeRate = spriteChangeRate; elapsedTime = spriteChangeRate; this.Ella = Ella; } public override void OnFinish() { Ella.GetComponent<SpriteRenderer> ().sprite = Ella.normal_sprite; } public override void OnUpdate (float time_delta_fraction) { if (Ella.drinking) elapsedTime += 1; if (!Ella.drinking || Ella.walking || Ella.jumping) { Ella.GetComponent<SpriteRenderer> ().sprite = Ella.normal_sprite; ConcludeState(); } if (elapsedTime >= spriteChangeRate) { Ella.GetComponent<SpriteRenderer> ().sprite = Ella.drinking_sprites [sprite_index]; if (sprite_index == 0) Elephant.instance.PlaySlurpSound (); sprite_index += 1; if (sprite_index >= Ella.drinking_sprites.Length) sprite_index = 0; elapsedTime = 0; } } } public class State_Animation_TrunkUp : State { private Elephant Ella; public State_Animation_TrunkUp(float spriteChangeRate, Elephant Ella) { this.Ella = Ella; } public override void OnUpdate (float time_delta_fraction) { Ella.GetComponent<SpriteRenderer> ().sprite = Ella.trunk_up_sprite; if (Ella.drinking || Ella.walking || Ella.jumping) { ConcludeState(); } } } public virtual State NextAnimationState() { if (Elephant.instance.drinking) return new State_Animation_Drinking (8, instance); else if (Elephant.instance.jumping) return new State_Animation_Flying (12, instance); return new State_Animation_Movement(8, instance); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public partial class Elephant: MonoBehaviour { public AudioSource jump_sound; public AudioSource water_sound; public AudioSource slurp_sound; public AudioSource elephant_sound; public AudioSource fall_sound; public AudioSource spike_sound; public AudioSource sizzle_sound; void PlayJumpSound(){ if (rb.isKinematic == false) jump_sound.Play (); } void PlayWaterSound(){ water_sound.Play (); } void PlaySlurpSound(){ slurp_sound.Play (); } void PlayElephantSound(){ elephant_sound.Play (); } public void PlayTreeSound(){ fall_sound.Play (); } public void PlaySizzleSound(){ sizzle_sound.Play (); } void PlaySpikeSound(){ spike_sound.Play (); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public partial class Wildfire: MonoBehaviour { public Sprite normal_sprite; public Sprite bright_sprite; private Rigidbody rb; protected StateMachine animation_state_machine = new StateMachine(); void Awake(){ rb = this.GetComponent<Rigidbody>(); } private bool wasPositive = false; void Update(){ animation_state_machine.Update (); if (animation_state_machine.IsFinished ()) { animation_state_machine.ChangeState (NextAnimationState ()); } Vector3 vel = rb.velocity; if (!wasPositive && rb.velocity.x >= -0.05f) { vel.x = 4; wasPositive = true; } else if (rb.velocity.x <= 0.05f) { vel.x = -4; wasPositive = false; } rb.velocity = vel; } // --------------------------------------------------------- void OnCollisionEnter(Collision coll){ print ("wildfire collision: " + coll.gameObject.tag); if (coll.gameObject.tag == "Droplet") { Destroy (this.gameObject); } } public virtual State NextAnimationState() { return new State_Animation_Wildfire(8, this); } public class State_Animation_Wildfire : State{ private float spriteChangeRate; private float elapsedTime = 0.0f; private Wildfire fire; public State_Animation_Wildfire(float spriteChangeRate, Wildfire thisfire) { this.spriteChangeRate = spriteChangeRate; elapsedTime = spriteChangeRate; this.fire = thisfire; } public override void OnFinish() { fire.GetComponent<SpriteRenderer> ().sprite = fire.normal_sprite; } public override void OnUpdate (float time_delta_fraction) { elapsedTime += 1; if (elapsedTime >= spriteChangeRate) { if (fire.GetComponent<SpriteRenderer> ().sprite != fire.normal_sprite) fire.GetComponent<SpriteRenderer> ().sprite = fire.normal_sprite; else fire.GetComponent<SpriteRenderer> ().sprite = fire.bright_sprite; elapsedTime = 0; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public partial class Droplet: MonoBehaviour { // --------------------------------------------------------- void OnTriggerEnter(Collider other){ print ("droplet trigger: " + other.gameObject.tag); Destroy (this.gameObject); } void OnCollisionEnter(Collision coll){ print ("droplet collision: " + coll.gameObject.tag); if (coll.gameObject.tag == "Tree") { print (coll.gameObject.GetComponentInParent<Tree> ().grow_time); coll.gameObject.GetComponentInParent<Tree> ().grow_time = 3; } if (coll.gameObject.tag == "Wildfire") { Elephant.instance.PlaySizzleSound (); Destroy (coll.gameObject); } Destroy (this.gameObject); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class TreeRegen: MonoBehaviour { public bool needs_new_tree = false; public GameObject sapling; void Update(){ if (needs_new_tree) { needs_new_tree = false; Instantiate (sapling); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class HUD : MonoBehaviour { public AudioSource gameSound; public AudioSource loseSound; public int max_score; public static HUD instance; public Text helping_text; public Text score_text; private bool game_over = false; public GameObject game_over_hud; public bool win = false; public GameObject win_screen_hud; public GameObject[] drips; public GameObject[] life_images; public GameObject selector; public int current_level = 0; public Image key_image; protected bool return_key; void Awake() { HUD.instance = this; } // Use this for initialization void Start () { if (SceneManager.GetActiveScene ().name == "Level_one") { toDisplay.Enqueue (0); toDisplay.Enqueue (1); toDisplay.Enqueue (2); } else if (SceneManager.GetActiveScene ().name == "Level_three") { toDisplay.Enqueue (0); } else if (SceneManager.GetActiveScene ().name == "Level_four") { toDisplay.Enqueue (0); toDisplay.Enqueue (1); } } // Update is called once per frame private int flash_delay = 10; private int number_flashes = 0; private bool finished_flashing = false; public string[] helping_text_arr; public Text time_text; private float time = 0; private int display_time = 0; // public string[] helping_text_arr = { "take the key to the cage to free the baby elephant", // "use the left & right arrow keys to explore the level", // "click space to jump" }; void Update () { return_key = Input.GetKeyDown (KeyCode.Return); if (return_key) { SceneManager.LoadScene ("Level_Select", LoadSceneMode.Single); } DisplayMessage (); if (time_text != null && !win && !game_over) { time += Time.deltaTime; if (time >= 1) { display_time += 1; time = 0; } time_text.text = "time: " + display_time.ToString (); } if (Elephant.instance.has_key) { key_image.enabled = true; } else { key_image.enabled = false; } if (drips != null) { int i = 0; for (; i < Elephant.instance.water_meter; ++i) { GameObject drip = drips [i]; drip.SetActive (true); } while (i < drips.Length) { GameObject drip = drips [i]; drip.SetActive (false); i++; } } if (Elephant.instance.lives == 0) { Elephant.instance.gameObject.SetActive (false); if (!game_over) { ShowGameOver (); } game_over = true; print ("he's dead jim"); } if (life_images != null) { int i = 0; for (; i < Elephant.instance.lives && i < life_images.Length; ++i) { GameObject life = life_images [i]; life.SetActive (true); } while (i < life_images.Length) { GameObject life = life_images [i]; life.SetActive (false); i++; } } if (game_over) { if (Input.GetKeyDown (KeyCode.Space)) SceneManager.LoadScene (SceneManager.GetActiveScene().buildIndex, LoadSceneMode.Single); } if (win) { bool Start = Input.GetKeyDown (KeyCode.Space); if (Start) { //replace with correct level if (current_level == 1) SceneManager.LoadScene ("level_two", LoadSceneMode.Single); else if (current_level == 2) SceneManager.LoadScene ("level_three", LoadSceneMode.Single); else if (current_level == 3) SceneManager.LoadScene ("level_four", LoadSceneMode.Single); else if (current_level == 4) SceneManager.LoadScene ("level_five", LoadSceneMode.Single); else if (current_level == 5) SceneManager.LoadScene ("level_six", LoadSceneMode.Single); else if (current_level == 6) SceneManager.LoadScene (0, LoadSceneMode.Single); return; } } } public void ShowWinSequence(){ win = true; score_text.text = "Score: "; int score = max_score; score -= (3 - Elephant.instance.lives) * 200; score -= display_time; score_text.text += score; Elephant.instance.gameObject.SetActive (false); win_screen_hud.SetActive (true); // print ("You win!"); } public void ShowGameOver() { gameSound.Pause (); loseSound.Play (); game_over_hud.SetActive (true); } private int text_display_time = 300; private bool message_finished = true; public Queue<int> toDisplay = new Queue<int>(); private int displayed_index = -1; private int helping_index = -1; public void DisplayMessage() { if (Elephant.instance.needs_help || toDisplay.Count > 0) { if (message_finished) { if (displayed_index == helping_index && toDisplay.Count > 0) { print ("change message"); helping_index = toDisplay.Dequeue (); if (helping_index != displayed_index) { Elephant.instance.needs_help = false; helping_text.enabled = true; helping_text.text = helping_text_arr [helping_index]; displayed_index = helping_index; message_finished = false; } } else { if (helping_index < helping_text_arr.Length) { Elephant.instance.needs_help = false; helping_text.enabled = true; helping_text.text = helping_text_arr [helping_index]; displayed_index = helping_index; message_finished = false; } } } else { if (displayed_index != helping_index) { toDisplay.Enqueue (helping_index); print (toDisplay); } } } if (helping_text.enabled) { text_display_time -= 1; if (text_display_time <= 0) { message_finished = true; helping_text.enabled = false; Elephant.instance.needs_help = false; text_display_time = 300; } } } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Camera: MonoBehaviour { public bool show_level = true; public float max_zoom_out; public Elephant elephant; Camera camera; // Use this for initialization // --------------------------------------------------------- void Start () { camera = GetComponent<Camera>(); } // Update is called once per frame // --------------------------------------------------------- //private int level_show_time = 100; private bool start_zoom_out = false; private bool start_zoom_in = false; private float min_zoom = -16f; void Update () { if (show_level) { if (Elephant.instance.walking || Elephant.instance.GetComponent<Rigidbody> ().velocity.y > 0.2f) { show_level = false; Vector3 position = transform.position; position.z = -26f; transform.position = position; } } if (!show_level) { Vector3 position = elephant.transform.TransformPoint (new Vector3 (-3f, 1.5f, -26f)); Vector3 camera_position = transform.position; camera_position.x = position.x; camera_position.y = position.y; transform.position = camera_position; } bool Up_arrow = Input.GetKeyDown (KeyCode.UpArrow); bool Up_arrow_up = Input.GetKeyUp (KeyCode.UpArrow); bool Down_arrow = Input.GetKeyDown (KeyCode.DownArrow); bool Down_arrow_up = Input.GetKeyUp (KeyCode.DownArrow); if (Up_arrow) start_zoom_in = true; else if (Up_arrow_up) start_zoom_in = false; if (Down_arrow) start_zoom_out = true; else if (Down_arrow_up) start_zoom_out = false; if (start_zoom_out) ZoomOut (); if (start_zoom_in) ZoomIn (); } void ZoomOut(){ if (transform.position.z > max_zoom_out) { Vector3 pos = transform.position; pos.z -= 0.5f; transform.position = pos; } } void ZoomIn(){ if (transform.position.z < min_zoom) { Vector3 pos = transform.position; pos.z += 0.5f; transform.position = pos; } } }
6e487af7a4832af21bc14e1b6726db2faaf067b6
[ "C#" ]
12
C#
cngreen/Elephant_Escape
74c33be7ee842ac00119b085bb7eaafb657c8e18
855a6e26d4f839b7f342adf7d26889a9513e24cd
refs/heads/master
<file_sep>package com.onetoone; import java.sql.Date; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class AppStarterOneToOne { private static LockerDao lockerDao = new LockerDao(); public static void main(String[] args) { // addCustomerAndLocker(); // addLockerToExistingCustomer(); getCustomer(); // deleteLocker(); // getLockers(); // assignExistingLockerToCustomer(); System.out.println("Done"); } private static void assignExistingLockerToCustomer() { System.out.println("Enter the customer id"); Scanner sc = new Scanner(System.in); int custId = sc.nextInt(); sc.nextLine(); System.out.println("Select one of the following empty lockers"); getLockers(); String lockerId = sc.nextLine(); lockerDao.addExistingLockerToCustomer(custId, lockerId); System.out.println("locker "+lockerId+" added to "+custId+" successfully"); } private static void getLockers() { List<String> list = lockerDao.getAvailableLockers(); String res = String.join(",", list); System.out.println(res); } /* L105 */ private static void deleteLocker() { System.out.println("Enter your customer id"); lockerDao.deleteLocker(new Scanner(System.in).nextInt()); System.out.println("locker deleted successfully"); } /* 101 */ private static void getCustomer() { System.out.println("Enter customer id"); int custId = new Scanner(System.in).nextInt(); Customer customer = lockerDao.getCustomer(custId); System.out.println(customer); } /* 103 L103 small 1500 */ private static void addLockerToExistingCustomer() { System.out.println("Enter the customer id"); Scanner sc = new Scanner(System.in); int custId = sc.nextInt(); sc.nextLine(); Locker locker = new Locker(); System.out.println("Enter the locker number"); locker.setLockerId(sc.nextLine()); System.out.println("Enter the locker type"); locker.setLockerType(sc.nextLine()); System.out.println("Enter the locker Rent"); locker.setRent(sc.nextInt()); LockerDao lockerDao = new LockerDao(); lockerDao.addLockerToCustomer(custId, locker); System.out.println("Locker added to customer id = "+custId); } /* 101 <NAME> 06/01/1995 layout-101 9638527417 L101 small 500 */ private static void addCustomerAndLocker() { Scanner sc = new Scanner(System.in); System.out.println("Enter the username"); String customerName = sc.nextLine(); System.out.println("Enter DOB in MM/dd/yyyy"); String datestr = sc.nextLine(); // SimpleDateFormat formatter = new SimpleDateFormat("mm/dd/yyyy"); DateTimeFormatter frmt = DateTimeFormatter.ofPattern("MM/dd/yyyy"); Date dob = java.sql.Date.valueOf(LocalDate.parse(datestr, frmt)); // Date dob = (Date) formatter.parse(datestr); System.out.println("Enter the address"); String addr = sc.nextLine(); System.out.println("Enter phone number"); String phone = sc.nextLine(); Locker locker = null; System.out.println("Do you want to provide locker for this customer? y/n"); if("y".equalsIgnoreCase(sc.nextLine())){ System.out.println("Enter the locker number"); String lockernumber = sc.nextLine(); System.out.println("Enter the locker type"); String loctype = sc.nextLine(); System.out.println("Enter the rent paid"); int rent = sc.nextInt(); sc.nextLine(); locker = new Locker(); locker.setLockerId(lockernumber); locker.setLockerType(loctype); locker.setRent(rent); } Customer customer = new Customer(); customer.setCustomerName(customerName); customer.setDateOfBirth(dob); customer.setAddress(addr); customer.setPhoneNumber(phone); customer.setLocker(locker); LockerDao lockerService = new LockerDao(); lockerService.addCustomerWithLocker(customer); } } <file_sep>package com.employeeAccount; import java.util.Scanner; public class Main { private static EmployeeAccountService service = new EmployeeAccountService(); public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num = 0; loop1:while(true){ System.out.println("press\n1: add employee\n2: get employee"); num = sc.nextInt(); sc.nextLine(); switch (num){ case 1 : service.AddEmployee(); break; case 2 : service.getEmployee(); default: System.out.println("Exiting"); break loop1; } } } } <file_sep>package org.example.configurationsDemo; import org.hibernate.Session; import org.hibernate.Transaction; import java.util.List; public class EmployeeCrudOperations implements EmployeeCrudInterface{ @Override public List<Employee> listEmployees(Session session) { Transaction tx = session.beginTransaction(); // List<Employee> emps = session.createSQLQuery("select * from Employee").list(); List<Employee> emps = session.createQuery("FROM Employee").list(); tx.commit(); return emps; } @Override public void addEmployee(Employee employee, Session session) { Transaction tx = session.beginTransaction(); session.save(employee); tx.commit(); } @Override public void updateEmployee(int empId, int salary, Session session) { Transaction tx = session.beginTransaction(); tx.commit(); } @Override public void deleteEmployee(int empId, Session session) { Transaction tx = session.beginTransaction(); tx.commit(); } } <file_sep>create table MOVIE_MANAGER (MOVIEID varchar(20) primary key, MOVIENAME varchar(20), LANGUAGE varchar(20), RELEASEDIN DATE, REVENUEINDOLLARS int); alter table MOVIE_MANAGER MODIFY REVENUEINDOLLARS DOUBLE; insert into MOVIE_MANAGER values ('1001', 'Avatar 2', 'English', '2022-12-16', 2.74); alter table movie_manager MODIFY column MOVIEID int; describe movie_manager; alter table movie_manager MODIFY column MOVIEID int AUTO_INCREMENT;<file_sep>package com.onetoone; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.sql.Date; @Entity @Table(name = "CUSTOMER") @GenericGenerator(name = "idgen", strategy = "increment") public class Customer { @Id @GeneratedValue(generator = "idgen") private int CustomerId; private String CustomerName; private Date dateOfBirth; private String address; private String phoneNumber; // , orphanRemoval = true @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = "LOCKERID", unique = true) private Locker locker; public Customer() { } public Customer(int customerId, String customerName, Date dateOfBirth, String address, String phoneNumber, Locker locker) { CustomerId = customerId; CustomerName = customerName; this.dateOfBirth = dateOfBirth; this.address = address; this.phoneNumber = phoneNumber; this.locker = locker; } public int getCustomerId() { return CustomerId; } public void setCustomerId(int customerId) { CustomerId = customerId; } public String getCustomerName() { return CustomerName; } public void setCustomerName(String customerName) { CustomerName = customerName; } public Date getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public Locker getLocker() { return locker; } public void setLocker(Locker locker) { this.locker = locker; } @Override public String toString() { return "Customer{" + "CustomerId=" + CustomerId + ", CustomerName='" + CustomerName + '\'' + ", dateOfBirth=" + dateOfBirth + ", address='" + address + '\'' + ", phoneNumber='" + phoneNumber + '\'' + ", locker=" + locker + '}'; } } <file_sep>package com.jakty.moviemanager; import org.hibernate.Session; import java.sql.Date; public interface MovieDaoInterface { public boolean addMovie(Movie movie); public void showMovie(); public Movie updateMovieReleaseDate(Integer movieId, Date releaseDate); public boolean deleteMovie(Integer movieId); }
e18220b9d9015d8a7b6ff8c7d7843905911fe439
[ "Java", "SQL" ]
6
Java
Gopiselvam/HibernateMysql
1b653ce921e180ae42f6420b1ad0b76f366e0d04
6923fe6885ba358202cd0d4ff7a16367bd9ac2a4
refs/heads/main
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using WAD_01.Models; namespace WAD_01.ViewModels { public class CustomerViewModels { public CustomerViewModels() { } public CustomerViewModels(Customer customer) { Id = customer.Id; FullName = customer.FullName; Address = customer.Address; Phone = customer.Phone; Gender = customer.Gender; TypeId = customer.TypeId; TypeName = customer.CustomerType.TypeName; } public string Id { get; set; } public string FullName { get; set; } public string Address { get; set; } public string Phone { get; set; } public bool Gender { get; set; } public int TypeId { get; set; } public string TypeName { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; using System.Web; using WAD_01.Models; namespace WAD_01.Reponsitory { public class Responsitory<T> : IResponsitory<T> where T : class, new() { private readonly ApplicationDbContext cnn; private readonly DbSet<T> tbl; public Responsitory() { cnn = new ApplicationDbContext(); tbl = cnn.Set<T>(); } public bool Delete(object id) { try { var entity = Get(id); if (entity == null) { return false; } tbl.Remove(entity); cnn.SaveChanges(); return true; } catch (Exception) { return false; } } public bool Delete(T entity) { try { tbl.Remove(entity); cnn.SaveChanges(); return true; } catch (Exception) { return false; } } public IEnumerable<T> Get() { return tbl.AsEnumerable(); } public IEnumerable<T> Get(Expression<Func<T, bool>> predicate) { return tbl.Where(predicate).AsEnumerable(); } public T Get(object id) { return tbl.Find(id); } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace WAD_01.Models { public class Customer { [Key] public string Id { get; set; } public string FullName { get; set; } public string Address { get; set; } public string Phone { get; set; } public bool Gender { get; set; } public int TypeId { get; set; } [ForeignKey("TypeId")] public virtual CustomerType CustomerType { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using WAD_01.Models; using WAD_01.Reponsitory; using WAD_01.ViewModels; namespace WAD_01.Controllers { public class CustomerController : Controller { private IResponsitory<Customer> customers; private IResponsitory<CustomerType> customerType; public CustomerController() { customers = new Responsitory<Customer>(); customerType = new Responsitory<CustomerType>(); } // GET: Customer public ActionResult Index() { var customerTypes = customerType.Get().ToList(); customerTypes.Add(new CustomerType { TypeId = 0, TypeName = "--Select customer type--" }); ViewBag.Type = new SelectList(customerTypes, "TypeId", "TypeName", 0); return View(); } public ActionResult GetData(int type = 0, string name = null) { var data = customers.Get(); if (type != 0 && name != null) { data = data.Where(x => x.TypeId == type && x.FullName.Contains(name)); } return Json(new { statusCode = 200, message = "Thành công", data = data.Select(y => new CustomerViewModels(y)) }, JsonRequestBehavior.AllowGet); } [HttpPost] public ActionResult Delete(string id) { try { var data = customers.Get(x => x.Id == id); if (data == null) { return Json(new { statusCode = 404, message = "Thất bại", }, JsonRequestBehavior.AllowGet); } customers.Delete(id); //using (var _context = new ApplicationDbContext()) //{ // var a = id.ToLower(); // var dataa = _context.Customers.FirstOrDefault(x => x.Id.ToLower().Equals(a)); // if (dataa == null) // { // return Json(new // { // statusCode = 404, // message = "Thất bại", // }, JsonRequestBehavior.AllowGet); // } // _context.Customers.Remove(dataa); // //customers.Delete(id); return Json(new { statusCode = 200, message = "Thành công", }, JsonRequestBehavior.AllowGet); //} //var data = customers.Get(); } catch { return Json(new { statusCode = 404, message = "Thất bại", }, JsonRequestBehavior.AllowGet); } } } } <file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using WAD_01.Migrations; namespace WAD_01.Models { public class ApplicationDbContext : DbContext { public ApplicationDbContext() : base("name=DBConnectionString") { Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>()); } public virtual DbSet<CustomerType> CustomerTypes { get; set; } public virtual DbSet<Customer> Customers { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace WAD_01.Reponsitory { public interface IResponsitory<T> where T : class, new() { IEnumerable<T> Get(); IEnumerable<T> Get(Expression<Func<T, bool>> predicate); T Get(object id); bool Delete(object id); bool Delete(T entity); } } <file_sep>namespace WAD_01.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using WAD_01.Models; internal sealed class Configuration : DbMigrationsConfiguration<WAD_01.Models.ApplicationDbContext> { public Configuration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = true; ContextKey = "WAD_01.ApplicationDbContext"; } protected override void Seed(WAD_01.Models.ApplicationDbContext context) { context.CustomerTypes.AddOrUpdate(x => x.TypeId, new CustomerType() { TypeId = 1, TypeName = "VIP", }, new CustomerType() { TypeId = 2, TypeName = "Normal", } ); context.Customers.AddOrUpdate(x => x.Id, new Customer() { Id = "C0001", FullName = "<NAME>", Address = "HCM", Phone = "0973086596", Gender = true, TypeId = 1, }, new Customer() { Id = "C0002", FullName = "<NAME>", Address = "HCM", Phone = "0973086591", Gender = false, TypeId = 2, }, new Customer() { Id = "C0003", FullName = "<NAME>", Address = "HN", Phone = "0973086592", Gender = false, TypeId = 2, }, new Customer() { Id = "C0004", FullName = "<NAME>", Address = "HN", Phone = "0973086593", Gender = false, TypeId = 1, } ); } } }
e15e6d684de5be50fc1e3cf49dbc1d22d446f113
[ "C#" ]
7
C#
thuyetbn/csharp-wad-exam
0e8b05749a67c16829fb97717509f94676c5ad8d
971dd69d671576e71a5946b076ba08d2ff99d402
refs/heads/master
<repo_name>montalvomiguelo/php-conceptos<file_sep>/library/Request.php <?php /** * Cada clase tiene su propio archivo. * Nombre de la clase es igual al nombre del archivo. */ class Request { protected $requestUrl; public function __construct($requestUrl) { $this->requestUrl = $requestUrl; } public function getRequestUrl() { return $this->requestUrl; } public function execute() { $requestUrl = $this->getRequestUrl(); $controllerClassName = $requestUrl->getControllerClassName(); $controllerFileName = $requestUrl->getControllerFileName(); $actionMethodName = $requestUrl->getActionMethodName(); $params = $requestUrl->getParams(); // Esto se hace con manejo de excepciones try/catch if (!file_exists($controllerFileName)) { $controllerClassName = 'errorController'; $controllerFileName = 'controllers/errorController.php'; } // Require al FileName require $controllerFileName; // Instanciamos una clase dinámicamente con ayuda de los métodos que ya hemos creado. $controller = new $controllerClassName(); // Ejecutamos el método del controlador con los parámetros que necesita // Recibimos la respuesta generada por el controlador. $response = call_user_func_array([$controller, $actionMethodName], $params); $this->executeResponse($response); } public function executeResponse($response) { // Si es una clase hija de Response(algún tipo de respuesta), // entonces ejecutamos su método execute() if ($response instanceof Response) { $response->execute(); } else { exit('Respuesta no válida'); } } } <file_sep>/views/list.tpl.php <div class="container"> <div class="row"> <div class="col s12"> <h1 class="header"><?= $title; ?></h1> <ul class="collection"> <?php foreach ( $films as $film ) : ?> <li class="collection-item avatar"> <i class="mdi-av-videocam circle"></i> <span class="title"><?php echo $film['title']; ?></span> <p><strong>Rate: </strong><?php echo $film['rating']; ?> <br> <strong>Rental Rate</strong>: <?php echo $film['rental_rate']; ?> </p> <a href="<?php echo BASE_URL . '/films/single/' . $film['film_id']; ?>" class="secondary-content"><i class="mdi-action-grade"></i></a> </li> <?php endforeach; ?> </ul> <!-- Films list --> <ul id="pagination" class="pagination"> <li class="waves-effect <?php echo ($pagesLimit <= $limit ? 'disabled' : ''); ?>"> <a href="<?php echo ( $pagesStart > $limit ? BASE_URL . '/list?page=' . ($pagesStart - 1) : '' ); ?>"><i class="mdi-navigation-chevron-left"></i></a> </li> <?php for ($i = $pagesStart; $i <= $pagesLimit; $i++) : ?> <li class="waves-effect <?php echo ($p == $i ? 'active' : ''); ?>"><a href="<?php echo BASE_URL . "/list?page=$i"; ?>"><?= $i; ?></a></li> <?php endfor; ?> <li class="waves-effect <?php echo ($pagesLimit >= $pagesTotal ? 'disabled' : ''); ?>"> <a href="<?php echo ($pagesLimit < $pagesTotal ? BASE_URL . '/list?page=' . ($pagesLimit + 1): ''); ?>"><i class="mdi-navigation-chevron-right"></i></a> </li> </ul> <!-- Films pagination --> </div> </div> </div> <file_sep>/library/ResponseJson.php <?php class ResponseJson extends Response { protected $array; public function __construct($array) { $this->array = $array; } public function getArray() { return $this->array; } public function execute() { $array = $this->getArray(); echo json_encode($array); } } <file_sep>/library/Inflector.php <?php /** * Clases estáticas no se instanciían solo tienen métodos de utiliería. * Son funciones agrupadas en una clase. * Podemos usar los 4 puntos :: para acceder a esos métodos. */ class Inflector { // Al trabajar con métodos estáticos debemos agregar la palabra // static. public static function camel($value) { // Dividimos la cadena por guines $segments = explode('-', $value); // Iterar cada posición de los segmentos. // Pasamos por referencia por que necesitamos modificarlo array_walk($segments, function(&$item) { $item = ucfirst($item); }); // Une los pedacitos de los segmentos y los regresa return implode('', $segments); } public static function lowerCamel($value) { // Para utilizar un método estático dentro de la clase estática, // Utilizamos ClassName::metodo() y no ->. // También podemos usar static::metodo() // lcfirst convierte la primera letra de la cadena en minúscula, // lo controario a ucfirst return lcfirst(Inflector::camel($value)); // return static::camel($value); } } <file_sep>/README.md # php-conceptos ###Conceptos básicos PHP Prácticas del curso impartido por <NAME> <file_sep>/views/film.tpl.php <div class="container"> <div class="row"> <div class="col s12"> <h1 class="header"><?= $film['title']; ?></h1> <p><?= $film['description']; ?></p> <p><strong>Release year:</strong> <?= $film['release_year']; ?></p> <p><strong>Rating:</strong> <?= $film['rating']; ?></p> <p><strong>Rating Rate:</strong> <?= $film['rental_rate']; ?></p> <p><strong>Special features: </strong><?= $film['special_features']; ?></p> <p><strong>Length: </strong><?= $film['length']; ?></p> </div> </div> </div> <file_sep>/views/404.tpl.php <div class="container"> <div class="row"> <div class="col s12"> <h1 class="header center-align"><?= $title; ?></h1> <p class="center-align">Lo siento, la página que tu tratabas de mirar no existe.</p> <p class="header center-align" style="font-size: 4.2rem; font-family:'Lucida Console', Monaco, monospace;">¯\_(⊙︿⊙)_/¯</p> </div> </div> </div> <file_sep>/controllers/errorController.php <?php class ErrorController { public function indexAction() { // Mandamos a la cabecera del navegador diciendo que hubo un error 404 header("HTTP/1.0 404 Not Found"); $view = new View('404', ['title' => 'Error 404']); return $view; } } <file_sep>/views/home.tpl.php <div class="container"> <div class="row"> <div class="col s12"> <h1 class="header"><?= $title; ?></h1> <ul class="collection"> <?php foreach ( $films as $film ) : ?> <li class="collection-item avatar"> <i class="mdi-av-videocam circle"></i> <span class="title"><?php echo $film['title']; ?></span> <p><strong>Rate: </strong><?php echo $film['rating']; ?> <br> <strong>Rental Rate</strong>: <?php echo $film['rental_rate']; ?> </p> <a href="<?php echo BASE_URL . '/films/single/' . $film['film_id']; ?>" class="secondary-content"><i class="mdi-action-grade"></i></a> </li> <?php endforeach; ?> </ul> </div> </div> </div> <file_sep>/controllers/HomeController.php <?php /** * Lógica de programación */ class HomeController { public function indexAction() { $title = 'Rental Rate'; // Instancia de la conexión a la DB $dbh = new Database(); // Custom query $films = $dbh->query('SELECT * FROM film ORDER BY rental_rate DESC LIMIT 10'); $vars = array( 'films' => $films, 'title' => $title ); $view = new View('home', $vars); return $view; } } <file_sep>/config.php <?php /** * Errores en php * Fatales.- Terminan la ejecución de la aplicación (require()) * Warnings.- Cuando un tratas de incluir algo que no existe, etc (include()) * Notice.- Error no tan importante, como cuando usas una variable no definida */ // Mostrar errores, estamos en desarrollo ini_set('display_errors', 'on'); // En el php.ini se establecen los settings, modificable en tiempo real error_reporting(E_ALL); // Php... quiero ver todos los errores // Constantes para la conexión a la base de datos define('DB_HOST', 'localhost'); define('DB_NAME', 'sakila'); define('DB_USER', 'root'); define('DB_PASS', '<PASSWORD>'); // Base url define('BASE_URL', '/hello-php'); <file_sep>/index.php <?php /** * Este es nuestro FRONTEND CONTROLLER * se encarga de realizar las configuraciones necesarias para que * nuestra aplicación funcione correctamente. * Se encargará de hacer checkeos de seguridad para dejar a los * controladores limpios. */ require_once('config.php'); // Settings de la aplicación // Library require_once('library/Database.php'); // PDO para conexión a la base de datos require 'library/Request.php'; require 'library/RequestUrl.php'; require 'library/Inflector.php'; require 'library/Response.php'; require 'library/View.php'; require 'library/ResponseJson.php'; if (empty($_GET['url'])) { $url = ''; } else { $url = $_GET['url']; } $requestUrl = new RequestUrl($url); $request = new Request($requestUrl); $request->execute(); <file_sep>/controllers/SearchController.php <?php class SearchController { public function indexAction() { $title = 'Search'; if (isset($_GET['s'])) { $s = $_GET['s']; $dbh = new Database(); $films = $dbh->query("SELECT * FROM film WHERE title LIKE :term", [':term' => "%$s%"]); } $view = new View('search', compact('title', 'films', 's')); return $view; } } <file_sep>/library/Response.php <?php /** * La respuesta puede ser de muchos tipos: html, json, csv, etc. * * Clases abstractas, nos sirven para definir una interface o contrato para enviarle * la respuesta al usuario. * */ abstract class Response { /** * Las clases hijas DEBEN implementar el método abstracto execute() */ abstract function execute(); } <file_sep>/library/Database.php <?php /** * Todos los métodos relacionados con la base de datos * están agrupados en esta clase. * */ class Database { protected $conn; public function __construct() { // Conexión con PDO a la base de datos // El constructor try / catch nos ayuda a manejar errores y Excepciones try{ // Creamos el objeto PDO $conn = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS); // Establecemos que el objeto $db nos lance cualquier tipo de Exeption cuando lo manipulemos... $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Use the native server-side prepared statements $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $this->conn = $conn; } catch(Exception $e) { // Si algo falla en la conexión, queremos caputurar la Exeption y hacer algo... // $e es un objeto instancia de Exception echo $e->getMessage(); die(); } } public function getConn() { return $this->conn; } public function all($table) { /** * Query method. */ try { $conn = $this->getConn(); $results = $conn->query("SELECT * FROM $table"); return $results->fetchAll(\PDO::FETCH_ASSOC); } catch(\Exception $e) { echo $e->getMessage(); die(); } } function query($query, $bindings = array()) { try { /** * Prepared Statements */ $conn = $this->getConn(); $results = $conn->prepare($query); $results->execute($bindings); return $results; } catch(\Exception $e) { echo $e->getMessage(); die(); } } function find($table, $key, $value) { $conn = $this->getConn(); $query = $this->query("SELECT * FROM $table WHERE $key = :value LIMIT 1", [':value' => $value], $conn); return $query->fetch(\PDO::FETCH_ASSOC); } } <file_sep>/controllers/RestController.php <?php class RestController { public function indexAction() { $title = 'Rest'; $view = new View('rest', array( 'title' => $title )); return $view; } public function rentalRateAction() { $dbh = new Database(); $films = $dbh->query('SELECT * FROM film ORDER BY rental_rate DESC LIMIT 10'); $filmsArr = array(); // Todo refactor this foreach ($films as $film) { $filmsArr[] = $film; } $data = new ResponseJson($filmsArr); return $data; } public function filmsAction($params) { $limit = 10; $p = ( isset($params) ? $params : 1 ); // Si traemos el parámetro de la página lo asignamos, en caso contrario sera 1 $start = ($p-1) * $limit; $dbh = new Database(); $films = $dbh->query('SELECT * FROM film LIMIT :start, :limit', [':start' => $start, ':limit' => $limit]); // Todo refactor this $filmsArr = array(); foreach ($films as $film) { $filmsArr[] = $film; } $data = new ResponseJson($filmsArr); return $data; } public function filmAction($params) { $dbh = new Database(); $film = $dbh->find('film', 'film_id', $params); $data = new ResponseJson($film); return $data; } } <file_sep>/controllers/ListController.php <?php class ListController { public function indexAction() { $title = 'View List'; $limit = 10; // Si traemos el parámetro de la página lo asignamos, en caso contrario sera 1 $p = ( isset($_GET['page']) ? intval($_GET['page']) : 1 ); $start = ($p-1) * $limit; $dbh = new Database(); $films = $dbh->query('SELECT * FROM film LIMIT :start, :limit', [':start' => $start, ':limit' => $limit]); $filmsCount = count( $dbh->all('film') ); $pagesTotal = (ceil( $filmsCount / $limit )); $pagesLimit = ceil($p / $limit) * $limit; $pagesStart = $pagesLimit - $limit + 1; $view = new View('list', compact('p', 'films', 'title', 'filmsCount', 'pagesTotal', 'pagesLimit', 'pagesStart', 'limit')); return $view; } } <file_sep>/views/layout.tpl.php <?php /** * Lógica de presentación */ ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <title><?= $title; ?></title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.96.1/css/materialize.min.css"> <style> p { color: rgba(0, 0, 0, 0.71); } .header { color: #ee6e73; font-weight: 300; } </style> </head> <body> <nav> <div class="nav-wrapper container"> <a id="logo-container" href="<?= BASE_URL; ?>" class="brand-logo">Films</a> <ul class="right hide-on-med-and-down"> <li><a href="<?= BASE_URL; ?>/films"><i class="mdi-action-view-list"></i></a></li> <li><a href="<?= BASE_URL; ?>/search"><i class="mdi-action-search"></i></a></li> <li><a href="<?= BASE_URL; ?>/rest"><i class="mdi-navigation-more-vert"></i></a></li> </ul> <ul id="nav-mobile" class="side-nav"> <li><a href="<?= BASE_URL; ?>/list">View list</a></li> <li><a href="<?= BASE_URL; ?>/search">Search</a></li> <li><a href="<?= BASE_URL; ?>/rest">REST</a></li> </ul> <a href="#" data-activates="nav-mobile" class="button-collapse"><i class="mdi-navigation-menu"></i></a> </div> </nav> <?= $tpl_content; ?> <footer class="page-footer"> <div class="container"> <div class="row"> <div class="col l6 s12"> <h5 class="white-text">Films</h5> <p class="grey-text text-lighten-4">The most popular films.</p> </div> <div class="col l4 offset-l2 s12"> <h5 class="white-text">Quick links</h5> <ul> <li><a class="grey-text text-lighten-3" href="<?= BASE_URL; ?>/films">View list</a></li> <li><a class="grey-text text-lighten-3" href="<?= BASE_URL; ?>/search">Search</a></li> <li><a class="grey-text text-lighten-3" href="<?= BASE_URL; ?>/rest">REST</a></li> </ul> </div> </div> </div> <div class="footer-copyright"> <div class="container"> © <?= date('Y'); ?> Copyright Text <a class="grey-text text-lighten-4 right" href="<?= BASE_URL; ?>">Home</a> </div> </div> </footer> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.96.1/js/materialize.min.js"></script> <script> // Initialize collapse button $(".button-collapse").sideNav(); // Pagination disabled buttons $('.pagination').on('click', '.disabled a', function(e) { e.preventDefault(); }); </script> </body> </html> <file_sep>/library/View.php <?php /** * La clase View es hija de Response(abstracta). * Cada respuesta necesita la implementación concreta de los métodos * abstractos */ class View extends Response { // Propiedades de la clase View: protected $template; protected $layout = 'layout'; protected $vars = array(); // Obligatorio $template y vars para crear una instancia de Vista. public function __construct($template, $vars = array()) { $this->template = $template; $this->vars = $vars; } public function getVars() { return $this->vars; } public function getTemplate() { return $this->template; } public function getTemplateFileName() { $template = $this->getTemplate(); return "views/$template.tpl.php"; } public function getLayout() { return $this->layout; } public function getLayoutFile() { $layout = $this->layout; return "views/$layout.tpl.php"; } // Implementamos el método abstracto execute (obligatorio) public function execute() { $vars = $this->getVars(); $template = $this->getTemplate(); // Le pasamos las variables que queremos que la función tenga acceso. (Encapsulamiento / Restringir acceso) call_user_func(function() use ($template, $vars) { extract($vars); // Para toda la salida de texto enviada al cliente y almacenarlo en una variable. ob_start(); $templateFileName = $this->getTemplateFileName(); require $templateFileName; // Asignamos a una variable la salida del template $tpl_content = ob_get_clean(); // Incluimos el layout común header,footer,sidebar,etc $layoutFile = $this->getLayoutFile(); require $layoutFile; }); } } <file_sep>/views/rest.tpl.php <div class="container"> <div class="s12 col"> <ul class="collection with-header"> <li class="collection-header"><h4><?= $title; ?></h4></li> <li class="collection-item"><div>Rental Rate<a href="<?php echo BASE_URL; ?>/rest/rental-rate" class="secondary-content"><i class="mdi-content-send"></i></a></div></li> <li class="collection-item"><div>Films list<a href="<?php echo BASE_URL; ?>/rest/films/23" class="secondary-content"><i class="mdi-content-send"></i></a></div></li> <li class="collection-item"><div>Film single<a href="<?php echo BASE_URL; ?>/rest/film/23" class="secondary-content"><i class="mdi-content-send"></i></a></div></li> </ul> </div> </div> <file_sep>/library/RequestUrl.php <? /** * Esta clase se encarga de interpretar la url * y despues llamar al controlador indicado. */ class RequestUrl { // Propiedades de la clase. // Suelen ser protected. // Se suelen crear métodos para tener acceso a las propiedades para tener mayor seguridad en la clase. protected $url; protected $controller; protected $defaultController = 'home'; protected $action; protected $defaultAction = 'index'; protected $params = array(); // Valor por defecto, sabemos que esperamos un arreglo aquí. // Método constructor que se llama automáticamente cada vez que se instancía la clase. // Métodos suelen ser public. public function __construct($url) { $this->url = $url; /** * La url va tener varios segmentos * controlador/accion/parametros * la función explode() nos permite * dividir una cadena por un delimitador */ $segments = explode('/', $this->getUrl()); $this->resolveController($segments); $this->resolveAction($segments); $this->resolveParams($segments); } /** * Pasamos $segments por referencia o puntero para poder quitarle * un pedacito y devolverlo sin ese pedacito. * Paso por valor es una copia y nunca se afecta el valor original. */ public function resolveController(&$segments) { // Quita del arreglo el primer elemento y me lo devuelve. $this->controller = array_shift($segments); // Si el controlador es vacio, le asignaremos un valod por defecto. if (empty($this->controller)) { $this->controller = $this->defaultController; } } public function resolveAction(&$segments) { $this->action = array_shift($segments); if (empty($this->action)) { $this->action = $this->defaultAction; } } // Todo lo que resta de la url son parámetros ya no los pasamos por referencia si no por valor. public function resolveParams($segments) { $this->params = $segments; } public function getUrl() { return $this->url; } public function getController() { return $this->controller; } public function getControllerClassName() { // Llamamos al método estático ::camel() de la clase Inflector return Inflector::camel($this->getController()) . 'Controller'; } public function getControllerFileName() { return 'controllers/' . $this->getControllerClassName() . '.php'; } public function getAction() { return $this->action; } public function getActionMethodName() { return Inflector::lowerCamel($this->getAction()) . 'Action'; } public function getParams() { return $this->params; } } <file_sep>/controllers/FilmsController.php <?php class FilmsController { public function indexAction() { $title = 'List View'; $limit = 10; // Si traemos el parámetro de la página lo asignamos, en caso contrario sera 1 $p = ( isset($_GET['page']) ? intval($_GET['page']) : 1 ); $start = ($p-1) * $limit; $dbh = new Database(); $films = $dbh->query('SELECT * FROM film LIMIT :start, :limit', [':start' => $start, ':limit' => $limit]); $filmsCount = count( $dbh->all('film') ); $pagesTotal = (ceil( $filmsCount / $limit )); $pagesLimit = ceil($p / $limit) * $limit; $pagesStart = $pagesLimit - $limit + 1; $view = new View('list', compact('p', 'films', 'title', 'filmsCount', 'pagesTotal', 'pagesLimit', 'pagesStart', 'limit')); return $view; } public function singleAction($film_id) { // Obener un film por idividual // Instanciando la conexión a la base de datos $dbh = new Database(); $film = $dbh->find('film', 'film_id', $film_id); // Si el film existe mando la vista $view = new View('film', compact('film')); return $view; } }
23cd83cf5e7d445364d3bc0243f04f26aa3afdd7
[ "Markdown", "PHP" ]
22
PHP
montalvomiguelo/php-conceptos
d01ce44c4e57cd79d2d8e1810e35a6e46e67f0c0
a1b90c411d79ef88273c805b44514ced868f6029
refs/heads/master
<repo_name>kkirik/mobx-vs-redux<file_sep>/src/redux/counter/constants.ts export const INCREASE_VALUE = 'INCREASE_VALUE'; export const DESCREASE_VALUE = 'DESCREASE_VALUE'; export const RESET_VALUE = 'RESET_VALUE'; <file_sep>/src/redux/counter/action.ts import {RESET_VALUE, INCREASE_VALUE, DESCREASE_VALUE} from './constants'; export interface IIncAction { type: typeof INCREASE_VALUE; } export interface IDecAction { type: typeof DESCREASE_VALUE; } export interface IResetAction { type: typeof RESET_VALUE; } export type CalculationAction = IIncAction | IDecAction | IResetAction; export const increaseAction = (): IIncAction => ({ type: INCREASE_VALUE, }); export const decreaseAction = (): IDecAction => ({ type: DESCREASE_VALUE, }); export const resetAction = (): IResetAction => ({ type: RESET_VALUE, }); <file_sep>/src/redux/store.ts import {createStore, combineReducers} from 'redux'; import {counter} from './counter/reducer'; export type Store = { counter: number; }; export function initStore(initialState?: Store) { return createStore( combineReducers({ counter, }), initialState ); } <file_sep>/src/redux/counter/reducer.ts import {CalculationAction} from './action'; import {RESET_VALUE, INCREASE_VALUE, DESCREASE_VALUE} from './constants'; export function counter(state: number = 0, action: CalculationAction) { switch (action.type) { case INCREASE_VALUE: return state + 1; case DESCREASE_VALUE: return state - 1; case RESET_VALUE: return 0; default: return state; } } <file_sep>/webpack.config.js const path = require('path'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); const root = process.cwd(); const config = { mode: 'development', watch: true, entry: { app: path.join(root, 'src/client.tsx'), }, output: { path: path.join(__dirname, 'assets'), publicPath: '/', filename: '[name].js', chunkFilename: '[name].js', }, resolve: { extensions: ['.ts', '.tsx', '.js'], modules: [root, path.resolve(root, 'src'), 'node_modules'], }, module: { rules: [ { test: /\.(tsx?)$/, loader: 'babel-loader', include: [path.resolve(__dirname, 'src')], }, ], }, optimization: { minimizer: [ new UglifyJsPlugin({ uglifyOptions: { mangle: false, output: { beautify: true, }, }, }), ], }, }; module.exports = config; <file_sep>/src/template.ts export default ({body, title, initialState}: any) => { return ` <!DOCTYPE html> <html> <head> <script>window.__APP_INITIAL_STATE__ = ${initialState}</script> <title>${title}</title> </head> <body> <div id="root">${body}</div> </body> <script src="/assets/app.js"></script> </html> `; };
45ec403a9123a2922e891144a56fb75f3791cb76
[ "JavaScript", "TypeScript" ]
6
TypeScript
kkirik/mobx-vs-redux
7d440d06f6644ebef083606bdf7dbd0181f6cefd
5991855cbc7d5136883cba300b6ca773cad47e07
refs/heads/master
<file_sep>rootProject.name='image-Search-Kotlin' include ':app' <file_sep>package com.example.image_search_kotlin import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.KotlinModule class SearchResult: AppCompatActivity() { var listOfImageDetails: List<ImageDetails>? = null override fun onCreate(savedInstanceState: Bundle?) { Log.i("Test","Testing") super.onCreate(savedInstanceState) setContentView(R.layout.activity_search_results) try { val jsonResponse: String? = getIntent().getStringExtra("JSONResponse") Log.d("ImageDetails Extracting", "Size :") listOfImageDetails = getImageDetailsFromJson(jsonResponse) Log.d("ImageDetails Success", "Size :" + listOfImageDetails!!.size) ConnectionCheck.isNetworkConnected( this ) initRecyclerView() } catch (e: Exception) { Log.d(TAG, "Exception caught : " + e.message) } } private fun initRecyclerView() { Log.d(TAG, "Starting RecyclerView....") val recyclerView: RecyclerView = findViewById<RecyclerView>(R.id.searchResults_recycleView) Log.i("S view ","1234") val recycleViewAdapter: RecycleViewAdapter? = listOfImageDetails?.let { RecycleViewAdapter(it,this) } recyclerView.setLayoutManager(LinearLayoutManager(this)) recyclerView.setHasFixedSize(true) recyclerView.setAdapter(recycleViewAdapter) Log.i("S view ","2444") } // @Throws(JSONException::class, IOException::class) private fun getImageDetailsFromJson(json: String?): List<ImageDetails>? { val mapper = ObjectMapper().registerModule(KotlinModule()) val dataHolder:ResultItemsJsonDataHolder = mapper.readValue(json,ResultItemsJsonDataHolder::class.java) println("Hello World") println(dataHolder.resultItems) Log.i("111","111") return dataHolder.resultItems } @JsonIgnoreProperties(ignoreUnknown = true) private class ResultItemsJsonDataHolder { @JsonProperty("items") var resultItems: List<ImageDetails>? = null } companion object { private const val TAG = "SearchResults" } }<file_sep>package com.example.image_search_kotlin import android.R import android.content.Context import android.content.DialogInterface import android.net.ConnectivityManager import android.app.AlertDialog internal object ConnectionCheck { fun isNetworkConnected(context: Context): Boolean { val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val connected = cm.activeNetworkInfo != null if (!connected) { AlertDialog.Builder(context) .setTitle("NO INTERNET CONNECTION") .setMessage("Oops !!! It seems that you are not connected to the Internet.") .setPositiveButton(R.string.ok, DialogInterface.OnClickListener { dialog, which -> }) .setIcon(R.drawable.ic_dialog_alert) .show() } return connected } }<file_sep># imageSearchKotlin Google Image Search using Kotlin This Demo Application allow user to search images over internet using google api <file_sep>package com.example.image_search_kotlin import android.os.Bundle import androidx.swiperefreshlayout.widget.CircularProgressDrawable import android.widget.ImageView import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.bumptech.glide.Glide import org.w3c.dom.Text class ViewImageDetails : AppCompatActivity() { private var imageTitle: TextView? = null private var imageWidth: TextView? = null private var imageHeight: TextView? = null private var author: TextView? = null private var viewport: TextView? = null private var imageView: ImageView? = null private var imageDetails: ImageDetails = ImageDetails() protected override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_view_image_details) imageView = findViewById(R.id.fullImageView) imageTitle = findViewById(R.id.imageTitle) imageHeight = findViewById(R.id.imageHeightValue) imageWidth = findViewById(R.id.imageWidthValue) viewport = findViewById(R.id.viewportValue) author = findViewById(R.id.authorValue) ConnectionCheck.isNetworkConnected(this) imageDetails = (getIntent().getSerializableExtra("imageDetails") as ImageDetails?)!! setDetails() } fun setDetails() { imageTitle!!.text = imageDetails!!.getTitle() if (!imageDetails!!.isPageMapNull()) { if (!imageDetails!!.getPageMap()!!.isThumbnailsNULL()) { imageWidth?.setText(imageDetails!!.getPageMap()!!.getThumbnails()!![0]?.getWidth()) imageHeight?.setText(imageDetails!!.getPageMap()!!.getThumbnails()!![0]?.getHeight()) } if (!imageDetails!!.getPageMap()!!.isMetaDataNULL()) { viewport?.setText(imageDetails!!.getPageMap()!!.getMetaData()!![0]?.getViewport()) author?.setText(imageDetails!!.getPageMap()!!.getMetaData()!![0]?.getAuthor()) } val circularProgressDrawable = CircularProgressDrawable(this) circularProgressDrawable.setStrokeWidth(10f) circularProgressDrawable.setCenterRadius(30f) circularProgressDrawable.start() //check if thumbnail is present if (!imageDetails!!.getPageMap()!!.isImageNULL()) { val imageSrc = imageDetails!!.getPageMap()!!.getImages()!![0]!!.getSrc() imageView?.let { Glide.with(this) .asBitmap() .load(imageSrc) .placeholder(circularProgressDrawable) .error(R.drawable.image_not_found) .into(it) } } else { Glide.with(this) .asBitmap() .load(R.drawable.image_not_found) } } } companion object { private const val TAG = "ViewImageDetails" } } <file_sep>package com.example.image_search_kotlin import android.content.Context import android.content.Intent import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.RelativeLayout import android.widget.TextView import androidx.annotation.NonNull import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.CircularProgressDrawable import com.bumptech.glide.Glide class RecycleViewAdapter( private val imageDetails: List<ImageDetails>, private val context: Context ) : RecyclerView.Adapter<RecycleViewAdapter.ViewHolder?>() { @NonNull override fun onCreateViewHolder(@NonNull viewGroup: ViewGroup, i: Int): ViewHolder { Log.i("R view ","1") val view = LayoutInflater.from(viewGroup.context) .inflate(R.layout.layout_listimageiteam, viewGroup, false) Log.i("R view ","2") return ViewHolder(view) } override fun onBindViewHolder(@NonNull viewHolder: ViewHolder, position: Int) { Log.i("R view ","checking onBindViewHolder") val imageDetail:ImageDetails = imageDetails[position] var imageSrc: String? = "" val imageTitle = imageDetail.getTitle() val circularProgressDrawable = CircularProgressDrawable(context) circularProgressDrawable.setStrokeWidth(10f) circularProgressDrawable.setCenterRadius(30f) circularProgressDrawable.start() //check if thumbnail is present if (!imageDetail.isPageMapNull()) { Log.i("R view ","checking onBindViewHolder2") if (!imageDetail.getPageMap()!!.isThumbnailsNULL()) { Log.i("R view ","checking onBindViewHolder3") imageSrc = imageDetail.getPageMap()!!.getThumbnails()!![0]?.getSrc() Glide.with(context) .asBitmap() .load(imageSrc) .placeholder(circularProgressDrawable) .error(R.drawable.image_not_found) .into(viewHolder.resultImage) } else { Log.i("R view ","checking onBindViewHolder4") Glide.with(context) .asBitmap() .load(R.drawable.image_not_found) } } Log.i("R view ","checking onBindViewHolder5") viewHolder.resultImageTitle.text = imageTitle viewHolder.resultLayout.setOnClickListener { fun onClick(view:View):Unit{ val intent = Intent(view.context, ViewImageDetails::class.java) intent.putExtra("imageDetails", imageDetail) view.context.startActivity(intent) } onClick(it) } } override fun getItemCount(): Int { Log.i("R view ","9") return imageDetails.size } public class ViewHolder(@NonNull itemView: View) : RecyclerView.ViewHolder(itemView) { var resultImage: ImageView var resultImageTitle: TextView var resultLayout: RelativeLayout init { Log.i("R view ","10") resultImage = itemView.findViewById(R.id.result_image) resultImageTitle = itemView.findViewById(R.id.result_imageTitle) resultLayout = itemView.findViewById(R.id.result_layout) } } } <file_sep>package com.example.image_search_kotlin import android.app.AlertDialog import android.content.Context import android.content.Intent import android.graphics.Color import android.os.AsyncTask import android.os.Bundle import android.util.Log import android.view.Gravity import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.view.inputmethod.InputMethodManager import android.widget.* import androidx.appcompat.app.AppCompatActivity import com.example.image_search_kotlin.SearchResult import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader import java.net.HttpURLConnection import java.net.MalformedURLException import java.net.URL class MainActivity : AppCompatActivity() { private val TAG = "MainActivity" var result: String? = null; var responseCode: Int? = null var responseMessage = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val TAG = "MainActivity" var editText: EditText = findViewById(R.id.editText) as EditText var button: Button = findViewById(R.id.button) as Button button.setOnClickListener(View.OnClickListener { Log.i("out","out") fun onClick(v:View):Unit{ Log.i("Hello","holoe") if (editText.text.toString().isEmpty()) { editText.error = "Please enter something !!!" } else { var searchString:String = editText.text.toString() Log.d(TAG, "Searching for : $searchString") var inputManager :InputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputManager.hideSoftInputFromWindow(currentFocus!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS) Log.d(TAG,"I am here") // looking for val searchStringNoSpaces = searchString.replace(" ", "+") val urlString = getString(R.string.baseUrl) + searchStringNoSpaces + "&key=" + getString(R.string.key) + "&cx=" + getString(R.string.cx) + "&alt=" + getString(R.string.responsetype) var url: URL? = null try { url = URL(urlString) } catch (e: MalformedURLException) { Log.e(TAG, "ERROR converting String to URL $e") } Log.d(TAG, "Url = $urlString") // start AsyncTask var searchTask = GoogleSearchAsyncTask() //val searchTask: com.saurabh.gimagesearch.MainActivity.GoogleSearchAsyncTask = com.saurabh.gimagesearch.MainActivity.GoogleSearchAsyncTask() Log.d("MainActivity", "Checking internet connectivity") if (ConnectionCheck.isNetworkConnected(v.context)) { if (searchTask != null) { searchTask.execute(url) } } } } onClick(it) }) } inner class GoogleSearchAsyncTask : AsyncTask<URL?, Int?, String>() { override fun doInBackground(vararg urls: URL?): String? { val url:URL = urls[0]!! Log.d("MainActivity", "AsyncTask - doInBackground, url=$url") // Http connection // Http connection var httpURLConnection: HttpURLConnection? = null try { httpURLConnection = url.openConnection() as HttpURLConnection } catch (e: IOException) { Log.e("MainActivity", "Http connection ERROR $e") } try { responseCode = httpURLConnection!!.responseCode responseMessage = httpURLConnection.responseMessage } catch (e: IOException) { Log.e("MainActivity", "Http getting response code ERROR $e") } Log.d("MainActivity", "Http response code =$responseCode message=$responseMessage") try { if (responseCode == 200) { // response OK val rd = BufferedReader(InputStreamReader(httpURLConnection!!.inputStream)) val sb = StringBuilder() var count =0 for(line in rd.readLines()){ sb.append(line+"\n") } rd.close() httpURLConnection.disconnect() result = sb.toString() // Log.d("MainActivity", "result=" + result) return result.toString() } } catch (e: IOException) { Log.e("MainActivity", "Http Response ERROR $e") } return null } override fun onProgressUpdate(vararg progress: Int?) { Log.i("Google_Search","onProgressUpdate") Log.d("MainActivity", "AsyncTask - onProgressUpdate, progress=$progress") } override fun onPostExecute(result: String) { Log.i("Google_Search","onPostExecute") Log.d("MainActivity", "AsyncTask - onPostExecute, result=$result") // dialog?.dismiss() val intent = Intent(applicationContext, SearchResult::class.java).apply { putExtra("JSONResponse", result) } startActivity(intent) } } } <file_sep>package com.example.image_search_kotlin import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import java.io.Serializable @JsonIgnoreProperties(ignoreUnknown = true) class ImageDetails : Serializable { val Tag: String = "ImageDetails" @JsonProperty("pagemap") private var pageMap: PageMap? = null private var title: String? = null; fun getTitle(): String? { return title } fun isPageMapNull(): Boolean { return pageMap == null } fun setTitle(title: String?) { this.title = title } fun getPageMap(): PageMap? { println("I am here get") return pageMap } fun setPageMap(pageMap: PageMap?) { println("I am here set") this.pageMap = pageMap } } @JsonIgnoreProperties(ignoreUnknown = true) class PageMap : Serializable { @JsonProperty("cse_thumbnail") private var thumbnails: List<Thumbnail>? = null @JsonProperty("cse_image") private var images: List<Image>? = null @JsonProperty("metatags") private var metaData: List<MetaData>? = null fun getThumbnails(): List<Thumbnail>? { return thumbnails } fun isThumbnailsNULL(): Boolean { return thumbnails == null } fun isImageNULL(): Boolean { return images == null } fun isMetaDataNULL(): Boolean { return metaData == null } fun setThumbnails(thumbnails: List<Thumbnail>?) { this.thumbnails = thumbnails } fun getImages(): List<Image>? { return images } fun setImages(images: List<Image>?) { this.images = images } fun getMetaData(): List<MetaData>? { return metaData } fun setMetaData(metaData: List<MetaData>?) { this.metaData = metaData } } @JsonIgnoreProperties(ignoreUnknown = true) class Thumbnail : Serializable { private var width: String? = null private var height: String? = null private var src: String? = null fun getWidth(): String? { return width } fun setWidth(width: String?) { this.width = width } fun getHeight(): String? { return height } fun setHeight(height: String?) { this.height = height } fun getSrc(): String? { return src } fun setSrc(src: String?) { this.src = src } } @JsonIgnoreProperties(ignoreUnknown = true) class MetaData : Serializable { private var author: String? = null private var viewport: String? = null fun getAuthor(): String? { return author } fun setAuthor(author: String?) { this.author = author } fun getViewport(): String? { return viewport } fun setViewport(viewport: String?) { this.viewport = viewport } } @JsonIgnoreProperties(ignoreUnknown = true) class Image : Serializable { private var src: String? = null fun getSrc(): String? { return src } fun setSrc(src: String?) { this.src = src } }
565849d7cda5a2e71b0bdfd25cb94029463212dd
[ "Markdown", "Kotlin", "Gradle" ]
8
Gradle
MeIbtihajnaeem/imageSearchKotlin
e62264dd4aea29bdf225906a4130ec2d449b96b1
c64218b8397bbd66b94b601a0da2db2e86a413bd
refs/heads/master
<file_sep><?php get_header(); ?> <article> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <header> <h1 id="post-title"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h1> </header> <div id="post-content"> <div class="entry"> <p><?php _e('Publicado em: '); ?><time class="updated" datetime="<?php echo get_the_date('c'); ?>" pubdate="pubdate"><?php the_time('j \d\e F \d\e Y'); ?></time></p> <?php the_content(); ?> <h5>Serviço:</h5> <div class="group"> <div class="agenda-column float-left"> <p> <strong><?php _e('Banda(s):'); ?></strong><br /> <?php $dfw_agenda_bandas = str_replace("\n", '<br />', get_post_meta($post->ID, 'dfw_agenda_bandas', true)); echo $dfw_agenda_bandas; ?> </p> <p> <strong>Local:</strong><br /> <?php echo get_post_meta($post->ID, 'dfw_agenda_local', true); ?> </p> <p> <strong><?php _e('Data/Hora:'); ?></strong><br /> <?php echo get_post_meta($post->ID, 'dfw_agenda_date', true); ?> às <?php echo get_post_meta($post->ID, 'dfw_agenda_date_h', true). ':' . get_post_meta($post->ID, 'dfw_agenda_date_m', true); ?> </p> <p> <strong><?php _e('Endereço:'); ?></strong><br /> <?php $dfw_agenda_end = get_post_meta($post->ID, 'dfw_agenda_end', true); $dfw_agenda_nei = get_post_meta($post->ID, 'dfw_agenda_nei', true); $dfw_agenda_city = get_post_meta($post->ID, 'dfw_agenda_city', true); $dfw_agenda_state = get_post_meta($post->ID, 'dfw_agenda_state', true); echo $dfw_agenda_end . '<br />' . $dfw_agenda_nei . '<br />' . $dfw_agenda_city . '/' . $dfw_agenda_state . ''; ?> </p> <p> <strong><?php _e('Realização:'); ?></strong><br /> <?php $dfw_agenda_prod = get_post_meta($post->ID, 'dfw_agenda_prod', true); $dfw_agenda_prod_s = get_post_meta($post->ID, 'dfw_agenda_prod_s', true); $dfw_agenda_prod_e = get_post_meta($post->ID, 'dfw_agenda_prod_e', true); $dfw_agenda_prod_t = get_post_meta($post->ID, 'dfw_agenda_prod_t', true); if($dfw_agenda_prod_s) { echo '<a href="'. $dfw_agenda_prod_s .'" target="_blank" rel="nofollow">' . $dfw_agenda_prod . '</a>'; } else { echo $dfw_agenda_prod; } if($dfw_agenda_prod_e) { echo '<br /><a href="mailto:'. $dfw_agenda_prod_e .'">'. $dfw_agenda_prod_e .'</a>'; } if($dfw_agenda_prod_t) { echo '<br />'. $dfw_agenda_prod_t; } ?> </p> </div> <div class="agenda-column float-right"> <p> <strong><?php _e('Ingressos:'); ?></strong><br /> <?php $dfw_agenda_tickets = str_replace("\n", '<br />', get_post_meta($post->ID, 'dfw_agenda_tickets', true)); echo $dfw_agenda_tickets; ?> </p> <p> <strong><?php _e('Pontos de venda:'); ?></strong><br /> <?php $dfw_agenda_sale = str_replace("\n", '<br />', get_post_meta($post->ID, 'dfw_agenda_sale', true)); $dfw_agenda_sale = preg_replace("#((http)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)#ie", "'<a href=\"$1\" target=\"_blank\">$1</a>$4'", $dfw_agenda_sale); echo $dfw_agenda_sale; ?> </p> </div> </div> <?php $dfw_google_maps = $dfw_agenda_end . ',' . $dfw_agenda_city . '-' . $dfw_agenda_state; $dfw_google_maps = urlencode($dfw_google_maps); ?> <p><iframe width="620" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.com.br/maps?f=q&amp;source=s_q&amp;hl=pt-BR&amp;geocode=&amp;q=<?php echo $dfw_google_maps; ?>&amp;ie=UTF8&amp;output=embed"></iframe></p> <p><strong><?php _e('Fonte: '); ?></strong><?php $dfw_agenda_source = get_post_meta($post->ID, 'dfw_agenda_source', true); $dfw_agenda_source_s = get_post_meta($post->ID, 'dfw_agenda_source_s', true); if($dfw_agenda_source_s) { echo '<a href="'. $dfw_agenda_source_s .'" target="_blank" rel="nofollow">' . $dfw_agenda_source . '</a>'; } else { echo $dfw_agenda_source; } ?></p> </div> <?php endwhile; endif; ?> </div> </article> <div id="sidebar"> <?php get_sidebar(); ?> </div> <?php get_footer(); ?> <file_sep><?php get_header(); ?> <article> <header> <h2>Agenda de shows</h2> </header> <div class="entry"> <script type="text/javascript"> jQuery(document).ready(function($) { $('#dfw-calendar').fullCalendar({ timeFormat: { '': 'HH:mm' }, header: { left: 'prev,next today', center: 'title', right: 'month,basicWeek,basicDay' }, editable: false, events: [ <?php $dfw_agenda_args = array( 'post_type' => 'agenda', 'posts_per_page' => 30, 'meta_key' => 'dfw_agenda_date', 'meta_value' => dfw_agenda_meta_value(), 'meta_compare' => 'IN' ); $dfw_agenda_query = new WP_Query($dfw_agenda_args); $dfw_agenda_total = $dfw_agenda_query->post_count; while ( $dfw_agenda_query->have_posts() ) : $dfw_agenda_query->the_post(); $dfw_agenda_date = explode('/', get_post_meta($post->ID, 'dfw_agenda_date', true)); $dfw_agenda_year = $dfw_agenda_date[2]; $dfw_agenda_month = $dfw_agenda_date[1] - 1; $dfw_agenda_day = $dfw_agenda_date[0]; $dfw_agenda_hour = get_post_meta($post->ID, 'dfw_agenda_date_h', true); $dfw_agenda_min = get_post_meta($post->ID, 'dfw_agenda_date_m', true); ?> { title: '<?php the_title(); ?>', start: new Date(<?php echo $dfw_agenda_year . ', ' . $dfw_agenda_month . ', ' . $dfw_agenda_day . ', ' . $dfw_agenda_hour . ', ' . $dfw_agenda_min; ?>), allDay: false, url: '<?php the_permalink(); ?>' }<?php // Removes the last comma to work in internet explorer if($dfw_agenda_query->current_post != $dfw_agenda_total -1) : ?>,<?php endif; ?> <?php endwhile; ?> ] }); }); </script> <div id="dfw-calendar"></div> </div> </article> <?php get_footer(); ?><file_sep><?php // Add WP-calendar-of-events require_once (get_template_directory() . '/agenda/init.php'); ?><file_sep><?php // Add metabox function dfw_admin_agenda_metabox() { add_meta_box( 'dfw-agenda-metabox', 'Detalhes do evento', 'dfw_admin_agenda_metabox_content', 'agenda', 'advanced' ); } add_action('admin_init', 'dfw_admin_agenda_metabox'); // Set numbers function dfw_agenda_set_zeros($number, $n) { return str_pad((int) $number, $n, '0', STR_PAD_LEFT); } // Add contant for metabox function dfw_admin_agenda_metabox_content() { global $post; ?> <script src="<?php bloginfo('template_url');?>/agenda/js/agenda-admin-metabox.js" type="text/javascript"></script> <div id="dfw-agenda-box-wrap"> <h4><?php _e('Atrações:'); ?></h4> <table class="dfw-agenda-metabox"> <tr> <th> <label for="dfw_agenda_bandas"><?php _e('Banda(s):'); ?></label> </th> <td> <textarea name="dfw_agenda_bandas" id="dfw_agenda_bandas" cols="50" rows="5"><?php echo get_post_meta($post->ID, 'dfw_agenda_bandas', true); ?></textarea> </td> </tr> </table> <h4><?php _e('Local e Data'); ?></h4> <table class="dfw-agenda-metabox"> <tr> <th> <label for="dfw_agenda_local"><?php _e('Local:'); ?></label> </th> <td> <input value="<?php echo get_post_meta($post->ID, 'dfw_agenda_local', true); ?>" name="dfw_agenda_local" id="dfw_agenda_local" type="text" class="regular-text" placeholder="<?php _e('Nome da casa de eventos'); ?>" /> </td> </tr> <tr> <th> <label for="dfw_agenda_date"><?php _e('Data e hora:'); ?></label> </th> <td> <input value="<?php echo get_post_meta($post->ID, 'dfw_agenda_date', true); ?>" name="dfw_agenda_date" id="dfw_agenda_date" type="text" class="regular-text" /> <?php _e('às'); ?> <select name="dfw_agenda_date_h" class="dfw-agenda-date-select"> <?php for($d = 0; $d <= 23; $d++) : $dfw_agenda_hour = dfw_agenda_set_zeros($d, 2); if (get_post_meta($post->ID, 'dfw_agenda_date_h', true) == $dfw_agenda_hour) : $current = ' selected="selected"'; else : $current = ''; endif; echo '<option'. $current .'>'. $dfw_agenda_hour .'</option>'; endfor; ?> </select> : <select name="dfw_agenda_date_m" class="dfw-agenda-date-select"> <?php for($d = 0; $d <= 59; $d++) : $dfw_agenda_min = dfw_agenda_set_zeros($d, 2); if (get_post_meta($post->ID, 'dfw_agenda_date_m', true) == $dfw_agenda_min) : $current = ' selected="selected"'; else : $current = ''; endif; echo '<option'. $current .'>'. $dfw_agenda_min .'</option>'; endfor; ?> </select> </td> </tr> <tr> <th> <label for="dfw_agenda_end"><?php _e('Endereço:'); ?></label> </th> <td> <input value="<?php echo get_post_meta($post->ID, 'dfw_agenda_end', true); ?>" name="dfw_agenda_end" id="dfw_agenda_end" type="text" class="regular-text" placeholder="<?php _e('Rua e número (separados por vírgula)'); ?>" /> </td> </tr> <tr> <th> <label for="dfw_agenda_nei"><?php _e('Bairro:'); ?></label> </th> <td> <input value="<?php echo get_post_meta($post->ID, 'dfw_agenda_nei', true); ?>" name="dfw_agenda_nei" id="dfw_agenda_nei" type="text" class="regular-text" /> </td> </tr> <tr> <th> <label for="dfw_agenda_city"><?php _e('Cidade:'); ?></label> </th> <td> <input value="<?php echo get_post_meta($post->ID, 'dfw_agenda_city', true); ?>" name="dfw_agenda_city" id="dfw_agenda_city" type="text" class="regular-text" /> </td> </tr> <tr> <th> <label for="dfw_agenda_state"><?php _e('Estado:'); ?></label> </th> <td> <select name="dfw_agenda_state" id="dfw_agenda_state" class="dfw-agenda-date-select"> <?php $dfw_agenda_states = array('AC', 'AL', 'AP', 'AM', 'BA', 'CE', 'DF', 'ES', 'GO', 'MA', 'MT', 'MS', 'MG', 'PA', 'PB', 'PR', 'PE', 'PI', 'RJ', 'RN', 'RS', 'RO', 'RR', 'SC', 'SP', 'SE', 'TO'); $dfw_agenda_current_state = get_post_meta($post->ID, 'dfw_agenda_state', true); foreach ($dfw_agenda_states as $state) { ?> <option <?php if ($dfw_agenda_current_state == $state) { echo 'selected="selected"'; } ?>><?php echo $state; ?></option><?php } ?> </select> </td> </tr> </table> <h4>Produtora</h4> <table class="dfw-agenda-metabox"> <tr> <th> <label for="dfw_agenda_prod"><?php _e('Nome:'); ?></label> </th> <td> <input value="<?php echo get_post_meta($post->ID, 'dfw_agenda_prod', true); ?>" name="dfw_agenda_prod" id="dfw_agenda_prod" type="text" class="regular-text" /> </td> </tr> <tr> <th> <label for="dfw_agenda_prod_s"><?php _e('Website:'); ?></label> </th> <td> <input value="<?php echo get_post_meta($post->ID, 'dfw_agenda_prod_s', true); ?>" name="dfw_agenda_prod_s" id="dfw_agenda_prod_s" type="text" class="regular-text" placeholder="<?php _e('http://'); ?>" /> <span class="description"><?php _e('Campo opcional'); ?></span> </td> </tr> <tr> <th> <label for="dfw_agenda_prod_e"><?php _e('E-mail:'); ?></label> </th> <td> <input value="<?php echo get_post_meta($post->ID, 'dfw_agenda_prod_e', true); ?>" name="dfw_agenda_prod_e" id="dfw_agenda_prod_e" type="text" class="regular-text" /> <span class="description"><?php _e('Campo opcional'); ?></span> </td> </tr> <tr> <th> <label for="dfw_agenda_prod_t"><?php _e('Telefone:'); ?></label> </th> <td> <input value="<?php echo get_post_meta($post->ID, 'dfw_agenda_prod_t', true); ?>" name="dfw_agenda_prod_t" id="dfw_agenda_prod_t" type="text" class="regular-text" placeholder="<?php _e('(xx) xxxx-xxxx'); ?>" /> <span class="description"><?php _e('Campo opcional'); ?></span> </td> </tr> </table> <h4>Ingressos</h4> <table class="dfw-agenda-metabox"> <tr> <th> <label for="dfw_agenda_tickets"><?php _e('Valores:'); ?></label> </th> <td> <textarea name="dfw_agenda_tickets" id="dfw_agenda_tickets" cols="50" rows="5"><?php echo get_post_meta($post->ID, 'dfw_agenda_tickets', true); ?></textarea> </td> </tr> <tr> <th> <label for="dfw_agenda_sale"><?php _e('Pontos de venda:'); ?></label> </th> <td> <textarea name="dfw_agenda_sale" id="dfw_agenda_sale" cols="50" rows="5" placeholder="Endereços de websites com http://"><?php echo get_post_meta($post->ID, 'dfw_agenda_sale', true); ?></textarea> </td> </tr> </table> <h4>Fonte</h4> <table class="dfw-agenda-metabox"> <tr> <th> <label for="dfw_agenda_source"><?php _e('Nome:'); ?></label> </th> <td> <input value="<?php echo get_post_meta($post->ID, 'dfw_agenda_source', true); ?>" name="dfw_agenda_source" id="dfw_agenda_source" type="text" class="regular-text" /> </td> </tr> <tr> <th> <label for="dfw_agenda_source_s"><?php _e('Website:'); ?></label> </th> <td> <input value="<?php echo get_post_meta($post->ID, 'dfw_agenda_source_s', true); ?>" name="dfw_agenda_source_s" id="dfw_agenda_source_s" type="text" class="regular-text" placeholder="<?php _e('http://'); ?>" /> </td> </tr> </table> </div> <?php } // Save metabox function dfw_admin_agenda_save_metabox($post_id) { if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id; if (!current_user_can('edit_post', $post_id)) return $post_id; if (get_post_type($post_id) == 'agenda' && $_POST) { $agenda_fields = array( 'dfw_agenda_bandas', 'dfw_agenda_date', 'dfw_agenda_date_h', 'dfw_agenda_date_m', 'dfw_agenda_local', 'dfw_agenda_end', 'dfw_agenda_nei', 'dfw_agenda_city', 'dfw_agenda_state', 'dfw_agenda_prod', 'dfw_agenda_prod_s', 'dfw_agenda_prod_e', 'dfw_agenda_prod_t', 'dfw_agenda_tickets', 'dfw_agenda_sale', 'dfw_agenda_source', 'dfw_agenda_source_s', ); foreach ($agenda_fields as $field) : $value_old = get_post_meta($post_id, $field, true); $value_new = esc_attr($_POST[$field]); if (!$value_new) { if ($value_old) delete_post_meta($post_id, $field, $value_old); } else { update_post_meta($post_id, $field, $value_new); } endforeach; } return $post_id; } add_action('save_post', 'dfw_admin_agenda_save_metabox'); ?><file_sep><?php /* * Calendar Interface * Create by Dreams Factory Web * http://www.dreamsfactoryweb.com * * version: 1.0 */ $dfw_agenda_dir = get_template_directory() . '/agenda/'; $dfw_scripts_dir = get_bloginfo('template_url') . '/agenda/'; // Agenda Custom Post Type require_once ($dfw_agenda_dir . 'admin/agenda-cpt.php'); // Agenda Metabox require_once ($dfw_agenda_dir . 'admin/agenda-metabox.php'); // Add theme support for post thumbnails add_theme_support('post-thumbnails'); // Load scripts in back-end function dfw_agenda_front_scripts() { if (get_post_type() == 'agenda' && !is_single()) { global $dfw_scripts_dir; wp_enqueue_script('jquery-ui-core'); wp_register_style('fullcalendar-styles', $dfw_scripts_dir . 'css/fullcalendar.css'); wp_enqueue_style('fullcalendar-styles'); wp_register_script('fullcalendar-scripts', $dfw_scripts_dir . 'js/fullcalendar.min.js'); wp_enqueue_script('fullcalendar-scripts'); } } add_action('wp_enqueue_scripts', 'dfw_agenda_front_scripts'); // Load scripts in front-end function dfw_agenda_front_scripts() { global $dfw_scripts_dir; wp_enqueue_script('jquery-ui-core'); wp_register_style('fullcalendar-styles', $dfw_scripts_dir . 'css/fullcalendar.css'); wp_enqueue_style('fullcalendar-styles'); wp_register_script('fullcalendar-scripts', $dfw_scripts_dir . 'js/fullcalendar.min.js'); wp_enqueue_script('fullcalendar-scripts'); } add_action('wp_enqueue_scripts', 'dfw_agenda_front_scripts'); // Array of valid days function dfw_agenda_meta_value() { // Verify transient $cache = get_transient('dfw_agenda_meta_value'); if ($cache != false) return $cache; // Get the current date $dfw_get_year = date('Y'); $dfw_get_month = date('m'); $dfw_get_next_month = dfw_agenda_set_zeros($dfw_get_month + 1, 2); $dfw_get_next_next_month = dfw_agenda_set_zeros($dfw_get_month + 2, 2); $dfw_get_day = date('d'); $dfw_current_month = ''; // Creates a string with the remaining days of the month for ($dfw_day = $dfw_get_day; $dfw_day <= 31; $dfw_day++) : $dfw_current_month .= dfw_agenda_set_zeros($dfw_day, 2) . '/' . $dfw_get_month . '/' . $dfw_get_year . ','; endfor; // Creates a string with the day of the month following for ($dfw_day = 1; $dfw_day <= 31; $dfw_day++) : $dfw_current_month .= dfw_agenda_set_zeros($dfw_day, 2) . '/' . $dfw_get_next_month . '/' . $dfw_get_year . ','; endfor; // Creates a string with the days of one month following for ($dfw_day = 1; $dfw_day <= 31; $dfw_day++) : $dfw_current_month .= dfw_agenda_set_zeros($dfw_day, 2) . '/' . $dfw_get_next_next_month . '/' . $dfw_get_year . ','; endfor; // Remove last character from string $dfw_date_final_string = substr($dfw_current_month, 0 , -1); // Creates an array $dfw_agenda_meta_value = explode(',', $dfw_date_final_string); // Save Transient $cache = $dfw_agenda_meta_value; set_transient('dfw_agenda_meta_value', $cache, 60*60*24); } // Clear cache to publish ou edit post function dfw_clear_agenda_cache(){ delete_transient('dfw_agenda_meta_value'); } add_action('publish_post', 'dfw_clear_agenda_cache'); ?>
e37a6ea03bb7a12c1cd6b8a4ad732267d1a48fad
[ "PHP" ]
5
PHP
saas786/WP-calendar-of-events
cd53e2ffef248be5e2471816513097cd6fb8df7f
948b1fa581ba4f34860671c7a954945050a8f9bf
refs/heads/master
<file_sep>-- phpMyAdmin SQL Dump -- version 3.3.9 -- http://www.phpmyadmin.net -- -- Serveur: localhost -- Généré le : Mar 30 Mars 2021 à 13:41 -- Version du serveur: 5.5.8 -- Version de PHP: 5.3.5 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Base de données: `bdd_medical` -- -- -------------------------------------------------------- -- -- Structure de la table `dosirer_medical` -- CREATE TABLE IF NOT EXISTS `dosirer_medical` ( `id_dossier` int(11) NOT NULL AUTO_INCREMENT, `id_p` int(11) NOT NULL, `id_m` int(11) NOT NULL, `Antecedant` text CHARACTER SET utf8 COLLATE utf8_bin, `traitement_actuel` text CHARACTER SET utf8 COLLATE utf8_bin, `resultat_anal_biologiques` text CHARACTER SET utf8 COLLATE utf8_bin, `resultat_irm_radio` text CHARACTER SET utf8 COLLATE utf8_bin, PRIMARY KEY (`id_dossier`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -- Contenu de la table `dosirer_medical` -- -- -------------------------------------------------------- -- -- Structure de la table `medecin` -- CREATE TABLE IF NOT EXISTS `medecin` ( `id_med` int(11) NOT NULL AUTO_INCREMENT, `nom_med` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL, `prenom_med` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL, `specialite_med` varchar(200) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL, `email` varchar(100) NOT NULL, `mp` varchar(100) NOT NULL, PRIMARY KEY (`id_med`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -- Contenu de la table `medecin` -- -- -------------------------------------------------------- -- -- Structure de la table `patient` -- CREATE TABLE IF NOT EXISTS `patient` ( `id_p` int(11) NOT NULL AUTO_INCREMENT, `nom_p` varchar(100) NOT NULL, `prenom_p` varchar(100) NOT NULL, `date_naiss_p` int(25) NOT NULL, `adresse_p` varchar(100) NOT NULL, `tel_p` varchar(25) NOT NULL, `email_p` varchar(100) NOT NULL, `sexe_p` varchar(25) NOT NULL, `n_securite_social` varchar(100) DEFAULT NULL, `ville_p` varchar(100) NOT NULL, `pays_p` varchar(100) NOT NULL, PRIMARY KEY (`id_p`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -- Contenu de la table `patient` -- -- -------------------------------------------------------- -- -- Structure de la table `plage_horaire` -- CREATE TABLE IF NOT EXISTS `plage_horaire` ( `id_h` int(11) NOT NULL AUTO_INCREMENT, `id_m` int(11) NOT NULL, `jour_semaine` varchar(100) NOT NULL, `heure_debut` time NOT NULL, `heur_fin` time NOT NULL, PRIMARY KEY (`id_h`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -- Contenu de la table `plage_horaire` -- -- -------------------------------------------------------- -- -- Structure de la table `rdv` -- CREATE TABLE IF NOT EXISTS `rdv` ( `id_rdv` int(11) NOT NULL AUTO_INCREMENT, `id_p` int(11) NOT NULL, `id_m` int(11) NOT NULL, `date_heure_rdv` datetime NOT NULL, PRIMARY KEY (`id_rdv`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -- Contenu de la table `rdv` -- -- -------------------------------------------------------- -- -- Structure de la table `secretaire` -- CREATE TABLE IF NOT EXISTS `secretaire` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nom` varchar(100) NOT NULL, `prenom` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `mp` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -- Contenu de la table `secretaire` -- -- -------------------------------------------------------- -- -- Structure de la table `visite` -- CREATE TABLE IF NOT EXISTS `visite` ( `id_visite` int(11) NOT NULL AUTO_INCREMENT, `id_p` int(11) NOT NULL, `id_m` int(11) NOT NULL, `date_visite` date NOT NULL, `diagnostic_patient` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id_visite`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -- Contenu de la table `visite` --
b944df0f7d130218a41ea34b7983bc023449981f
[ "SQL" ]
1
SQL
ilyesam/monprojetweb
4a391f097e53c106498356f8553d544a578bf783
66c264715800f946258f02375afbe1601b4dec93
refs/heads/master
<file_sep>library(data.table) library(dplyr) library(lubridate) library(ggplot2) options(digits = 4) options(scipen = 999) data <- fread("./../Data/Sales Prediction/training.csv", stringsAsFactors = F) glimpse(data) data <- data %>% filter(quantity > 0 & sales_amount > 0) %>% ##this could be explored furter. EXPLAIN! mutate(purchase_date = as.Date(purchase_date, "%Y-%m-%d")) %>% arrange(contact_id, purchase_date) %>% select(contact_id, order_id, purchase_date, product_id, quantity, sales_amount) data %>% summarize(row_count = n(), unique_customers = n_distinct(contact_id), transaction_count = n_distinct(order_id), unique_products = n_distinct(product_id), avg_quantity = mean(quantity), median_quantity = median(quantity), avg_sales_amount = mean(sales_amount), median_sales_amount = median(sales_amount) ) ##TODO: avg&median / customer (not line item)! --> two-step aggr. per_contact_avgs <- data %>% group_by(contact_id) %>% summarize(total_line_items = n(), transaction_count = n_distinct(order_id), unique_products = n_distinct(product_id), avg_quantity = mean(quantity), median_quantity = median(quantity), avg_sales_amount = mean(sales_amount), median_sales_amount = median(sales_amount), total_sales_amount = sum(sales_amount)) per_contact_avgs %>% arrange(desc(transaction_count)) %>% head() ##visualize per_contact_avgs %>% ggplot() + geom_histogram(aes(x= transaction_count)) + ##log so at least we can read something... facet_wrap(~transaction_count > 25, scales = "free") #total_line_items * avg_sales_amount --> total sales. show? ##visualize contact_id groups and their contribution to sales --> "calibration" check ##TODO_validate results. groups should be decreasing. ratio? total_rows <- nrow(data) data %>% group_by(contact_id) %>% summarize(total_sales_amount = sum(sales_amount)) %>% ungroup() %>% arrange(desc(total_sales_amount)) %>% mutate(rowno = row_number()) %>% mutate(category = cut(rowno, seq(-1, total_rows, total_rows/20), include.lowest = T)) %>% group_by(category) %>% summarize(sum_total_sales = sum(total_sales_amount)) %>% mutate(cumsum_total_sales = cumsum(sum_total_sales)) %>% ggplot(aes(x=category, y=cumsum_total_sales)) + geom_point() + geom_line(group=1) ##TODO: monthly volumes ##visualize ordered_year_month <- data %>% mutate(purchase_year = year(purchase_date)) %>% mutate(purchase_month = month(purchase_date)) %>% distinct(purchase_year, purchase_month) %>% mutate(purchase_year_month = paste(as.character(purchase_year), as.character(purchase_month), sep = "-")) %>% arrange(purchase_year, purchase_month) %>% select(purchase_year_month) data %>% mutate(purchase_year = year(purchase_date)) %>% mutate(purchase_month = month(purchase_date)) %>% mutate(purchase_year_month = paste(as.character(purchase_year), as.character(purchase_month), sep = "-")) %>% mutate(purchase_year_month = factor(purchase_year_month, levels = ordered_year_month[["purchase_year_month"]])) %>% group_by(purchase_year_month) %>% summarize(sales = sum(sales_amount)) %>% ggplot(aes(x= purchase_year_month, y = sales)) + geom_point() + geom_line(group=1) head(data) ?cumsum data %>% mutate(purchase_date_minus_2wks = purchase_date - 14) %>% group_by(contact_id, purchase_date) %>% mutate(cum_sales = cumsum(sales_amount)) %>% head(15) fun_prev_sales <- function(df, iID, iDate, iWindow) { df %>% filter(contact_id == iID) %>% filter(purchase_date >= iDate - iWindow & purchase_date < iDate) %>% summarize(sum(sales_amount)) } fun_prev_sales(data, 884, as.Date("2013-05-14", "%Y-%m-%d"), 100) <file_sep># SALES_PRED Repository for practicing sales prediction <file_sep>--- title: "Sales Prediction Exercise" date: '2018-03-04' output: html_notebook: df_print: paged toc: true number_sections: true theme: united html_document: df_print: paged toc: true number_sections: true theme: united --- ```{r setup, message=FALSE, include=FALSE} library(data.table) library(dplyr) library(purrr) library(lubridate) library(ggplot2) library(gridExtra) library(scales) library(reshape) library(caret) library(glmnet) library(knitr) knitr::opts_chunk$set(warning = FALSE) knitr::opts_chunk$set(message = FALSE) options(digits = 4) options(scipen = 999) theme_set(theme_minimal()) # globally set ggplot theme set.seed(93) RMSE <- function(x, true_x) sqrt(mean((x - true_x)^2)) ``` # Purpose definition The goal of this exercise is to predict sales for the coming year for different customers (groups of customers). I'll use standard prediction techniques and practices to create predictive models, while explaining the decision I've made along the code as well. The output will be available in an .Rmd and .html files. My documentation approach is the following: the .html output will show only limited amount of code, only snippets that are helpful for understanding the logic applied (others are "hidden" by the 'echo = FALSE' prefix for code chunks). For the full code base, please refer to the .Rmd file. The presentation of the analysis is built of the following parts: 1. Data review & cleaning 2. Exploratory data analysis 3. Featuring engineering 4. Model & model selection 5. Performance evaluation An important feature of data analysis is that it is an iterative process - we are likely to go back to earlier steps once we learn something new about the data to expand what we did. This iterative process is by definition not very linear - presenting things as they evolved would be a very messy read for anyone. Hence, this document is created to capture the final state of the analysis - many of these smaller iterations are inherently lost unfortunately. Please keep this in mind when reading. # Data review & cleaning After reading in the data, let's take a glimpse at the data structure we'll be working with: ```{r, echo = FALSE} data <- fread("./../Data/Sales Prediction/training.csv", stringsAsFactors = F) glimpse(data) head(data) ``` One thing to notice is that we have a field containing dates, however R treats it as a character column by default. We'll correct that in the next step, but before that let's check if there is any observation that will require some fixing as well: ```{r, echo=FALSE} fun_count_na <- function(dt) { ##counts and reports the missing observations for each column in a data.table object missing_values <- as.data.table(t(dt[, lapply(.SD, function(x) sum(is.na(x))), .SDcols = names(dt)]), keep.rownames = TRUE) setnames(missing_values, c("variable", "NA Count")) return(missing_values[order(-`NA Count`)]) } ``` ```{r, echo=FALSE} fun_count_na(data) ``` No NAs, that's good news. Before deciding whether the dataset is complete or not, let's make sure all the sales & quantity values make sense, by checking how many 0-s we encounter. First, for quantities: ```{r} data %>% filter(quantity == 0) %>% summarize(count = n(), sum_sales_amount = sum(sales_amount)) ``` This looks very limited. Without further context on the data, I'll just assume they are recording errors, and exlcude them for the dataset. ```{r} data %>% filter(quantity != 0) %>% filter(sales_amount == 0) %>% summarize(count = n(), sum_quantity = sum(quantity)) ``` We are encountering many (6947 in total) observations for which sales_amount is 0. Interestingly, sometimes even the record quantity is larger than 1 for these. Although they are marginal compared to the number of all observations (500K+), a decision needs to be still made how to handle them, as they are likely misleading for any model in their current format. ```{r, include = FALSE} data %>% filter(product_id == 1533517) %>% head() ``` There might be a reason behind having 0 values (one I can think of is they are being part of some kind of promotion), and this reason could actually be indicative of future sales (e.g. the promotion is for frequent shoppers etc.). In this case, features should be created out of these items to help enhance the model's prediction. On the other hand, they might just be simple data issues. Deleted items still showing up as line items, incorrect prices (hence sales_amount), or anything similar. Right now we can simply and assume they actually represent wrong data - so by taking the easy path, I simply exclude them from further modeling efforts. Applying the fixes before we continue: ```{r} data <- data %>% filter(sales_amount > 0) %>% mutate(purchase_date = as.Date(purchase_date, "%Y-%m-%d")) %>% arrange(contact_id, purchase_date) %>% select(contact_id, order_id, purchase_date, product_id, quantity, sales_amount) ``` # Data exploration As standard practice, I'll continue by visually exploring what's in the data, that might be useful for sales prediction. My starting hypothesis is that one of the most important features to understand is whether we are working returning customers - which materializes as having more than one purchase_date per contact_id (the other is the seasonality effect - more on that later). The below table gives us a brief look into customers who are generating the most number of transactions: ```{r, echo = FALSE} per_contact_avgs <- data %>% group_by(contact_id) %>% summarize(total_line_items = n(), transaction_count = n_distinct(order_id), unique_products = n_distinct(product_id), avg_quantity = mean(quantity), median_quantity = median(quantity), avg_sales_amount = mean(sales_amount), median_sales_amount = median(sales_amount), total_sales_amount = sum(sales_amount)) per_contact_avgs %>% arrange(desc(transaction_count)) %>% head(10) ``` Below is a visualization of the distribution of transactions among customers, broken into two groups, one having more than 25 transactions, and one having less. ```{r, echo = FALSE, fig.width=8, fig.height=3, fig.align='center'} per_contact_avgs %>% mutate(transaction_category = ifelse(transaction_count < 25, "Less than 25 transactions", "25+ transactions")) %>% mutate(transaction_category = factor(transaction_category, levels = c("Less than 25 transactions", "25+ transactions"))) %>% ggplot() + geom_histogram(aes(x= transaction_count, fill = transaction_category)) + facet_wrap(~transaction_category, scales = "free") + scale_y_continuous(name="# of contact_id-s", labels = comma) + scale_x_continuous(name="Count of total transactions", labels = comma) + labs(title = "Grouping contact_id-s based on number of transactions") ``` What do we learn from this? 1. First, most customers only buy once. This is important for our modeling, as we won't know anything about them (priori to their first purchase) when we try to forecast their sales. Hence, all we'll be able to rely on is some generalizations made based on when they make their purchase. 2. Any way we slice the customers, transaction counts will be heavily skewed to the left - even more than for lognormal distributions. 3. A very important thing that we _don't_ learn is how much sales these different groups generate. Maybe not suprisingly, total sales per contract_id do closely resemble a lognormal distribution: ```{r, echo=FALSE, fig.width=10, fig.height=6, fig.align='center'} p1 <- per_contact_avgs %>% mutate(transaction_category = ifelse(transaction_count < 2, "One-time customer", "Returning customer")) %>% mutate(transaction_category = factor(transaction_category, levels = c("One-time customer", "Returning customer"))) %>% ggplot() + geom_histogram(aes(x= total_sales_amount, fill = transaction_category)) + scale_x_continuous(trans='log10', labels = comma) + facet_wrap(~transaction_category, scales = "free") temp <- per_contact_avgs %>% mutate(transaction_category = ifelse(transaction_count < 2, "One-time customer", "Returning customer")) %>% mutate(transaction_category = factor(transaction_category, levels = c("One-time customer", "Returning customer"))) temp1 <- temp %>% filter(transaction_category == "One-time customer") temp2 <- temp %>% filter(transaction_category == "Returning customer") p2 <- ggplot() + geom_density(data = temp1, aes(x= avg_sales_amount, fill = transaction_category), alpha = 0.4) + geom_density(data = temp2, aes(x= avg_sales_amount, fill = transaction_category), alpha = 0.25) + scale_x_continuous(trans='log10', labels = comma) grid.arrange(p1, p2, ncol = 1) ``` Returning customers do spend more in total - not much news, but it's good to confirm with data. More interesting is the second plot, which show the distribution of _average spending_ by customer-type split. Returning customers spend a bit more on average, but both distributions are skewed to the right - and larger transactions happen relatively more often to one-timers! The second important factor to understand is how seasonality (basically time of purchase) is related to sales amounts. For modeling, we will build solutions that predict the the 2013 total (generally, the next year's total) from 2012 data - so it's good to know if there is any interesting dynamics going on for the time dimension of sales. ```{r, echo = FALSE} ordered_year_month <- data %>% mutate(purchase_year = year(purchase_date)) %>% mutate(purchase_month = month(purchase_date)) %>% distinct(purchase_year, purchase_month) %>% mutate(purchase_year_month = paste(as.character(purchase_year), as.character(purchase_month), sep = "-")) %>% arrange(purchase_year, purchase_month) %>% select(purchase_year_month) data <- data %>% mutate(purchase_year = year(purchase_date)) %>% mutate(purchase_month = month(purchase_date)) %>% mutate(purchase_year_month = paste(as.character(purchase_year), as.character(purchase_month), sep = "-")) %>% mutate(purchase_year_month = factor(purchase_year_month, levels = ordered_year_month[["purchase_year_month"]])) ``` ```{r, echo = FALSE} fun_plot_trend <- function(df1, x_var, y_var, x_breaks, yLabel, chartColor) { p <- ggplot(data = df1, aes_string(x= x_var)) + geom_point(aes_string(y = y_var), color = chartColor, size = 2.5) + geom_line(aes_string(y = y_var), color = chartColor, size = 1.2, group=1) + scale_x_discrete(breaks = x_breaks) + scale_y_continuous(labels = comma) + labs(x = "Month", y = yLabel) return(p) } ``` ```{r, echo = FALSE, fig.width=10, fig.align='center', fig.height=9} month_breaks <- ordered_year_month$purchase_year_month[seq(0, 24, 3)] p1 <- data %>% group_by(purchase_year_month) %>% summarize(sales = sum(sales_amount)) %>% fun_plot_trend(x_var = "purchase_year_month", y_var = "sales", x_breaks = month_breaks, yLabel = "Total Sales", chartColor = "darkblue") p2 <- data %>% group_by(purchase_year_month) %>% summarize(transaction_count = n_distinct(order_id)) %>% fun_plot_trend(x_var = "purchase_year_month", y_var = "transaction_count", x_breaks = month_breaks, yLabel = "Total Transaction #", chartColor = "orange") p3 <- data %>% group_by(purchase_year_month, order_id) %>% summarize(sales_amount = sum(sales_amount)) %>% group_by(purchase_year_month) %>% summarize(avg_sales_amount = mean(sales_amount)) %>% fun_plot_trend(x_var = "purchase_year_month", y_var = "avg_sales_amount", x_breaks = month_breaks, yLabel = "Avg. Sales per Order", chartColor = "purple") grid.arrange(p1, p2, p3, ncol = 1) ``` Total sales per month is visibly mostly driven by transaction count, which shows a lot of variation over time ( _reminder: here we talk about "total totals", not per customer numbers_). On the other hand, avg. sales per order clearly showed some upwards trend, specially in the second half of 2013. This could mean either customers are buying more pricey items, or they are buying the same stuff as before, but per item costs have gone up. For a more detailed modeling, this is something worth exploring, however I am not going to go into further depths here. # Feature engineering In this section, we'll be getting the data in shape to use for prediction. In this exercise, the goal is to predict a customers spending for a new year, based on historical spending patterns. We have two years in our dataset, 2012 & 2013 - given this, the setup will be rather simple - using everything we can from 2012, we want to predict a total sales_amount number for 2013 for a given customer. When working with time data, and trying to make predictions, it's very important to avoid any "future leaks" - we only want to predict based on information that was available _a priori_ compared to when we are making the prediction. Here, we basically already achieve this by data from 2012 as predictors for 2013 sales, so this is not something we need to worry about going forward. ```{r, echo = FALSE} data <- data %>% mutate(year = year(purchase_date)) ``` So, first steps first: let's calculate the per customer total spending for 2013. ```{r} sales_2013 <- data %>% filter(year == 2013) %>% group_by(contact_id) %>% summarize(total_sales_2013 = sum(sales_amount, na.rm = TRUE)) ``` A look at how the data looks arranged by top spenders on top: ```{r, echo = FALSE} sales_2013 %>% arrange(desc(total_sales_2013), contact_id) %>% head(5) ``` For 2012 we can start by building a couple of features that are rather "obvious" - total sales, transaction count, etc.: ```{r} data_2012 <- data %>% filter(year == 2012) features_2012 <- data_2012 %>% group_by(contact_id) %>% summarize(total_sales_2012 = sum(sales_amount, na.rm = T), total_line_items_2012 = n(), total_purchases_2012 = n_distinct(order_id), total_quantity_2012 = sum(quantity, na.rm = T), biggest_purchase_item = max(sales_amount, na.rm = T), smallest_purchase_item = min(sales_amount, na.rm = T) ) %>% mutate(existing_2012_contact_id = "Y") ``` Again, look at how the data looks arranged by top spenders on top: ```{r} features_2012 %>% arrange(desc(total_sales_2012), contact_id) %>% head(5) ``` The results are already promising - some customers are actually getting repeated in the top5 (e.g. contact_id 35244243 or 49141897), which is just a minor signal that there is likely to be a relationship between the two years' spending patterns. I am going to explore this and a lot more futher after we are finished building all our features for prediction. More features on yearly data: ```{r} features_2_2012 <- data_2012 %>% group_by(contact_id, order_id) %>% summarize(sales_amount = sum(sales_amount), most_expensive_line = max(sales_amount), least_expensive_line = min(sales_amount), count_lines = n()) %>% group_by(contact_id) %>% summarize(avg_sales_by_order_2012 = mean(sales_amount), max_sales_by_order_2012 = max(sales_amount), min_sales_by_order_2012 = min(sales_amount), avg_most_expensive_line_by_order_2012 = mean(most_expensive_line), avg_least_expensive_line_by_order_2012 = mean(least_expensive_line), avg_line_item_count_by_order_2012 = mean(count_lines), purchase_count = n()) ``` A lot of features were created already - however, all of these used the data for the whole year. We've seen that seasonality is important - let's build features that take this into account in some way: ```{r} features_3_2012 <- data_2012 %>% group_by(contact_id, purchase_month) %>% summarize(sales_amount = sum(sales_amount)) %>% group_by(contact_id) %>% tidyr::spread(key = purchase_month, value = sales_amount, fill = 0, sep= "_") new_feature_names <- paste(gsub("purchase_month", "sales_in_month", names(features_3_2012)), "2012", sep = "_")[2:13] setnames(features_3_2012, old = names(features_3_2012)[2:13], new_feature_names) features_4_2012 <- data_2012 %>% group_by(contact_id, purchase_month) %>% summarize(order_count = n_distinct(order_id)) %>% group_by(contact_id) %>% tidyr::spread(key = purchase_month, value = order_count, fill = 0, sep= "_") new_feature_names <- paste(gsub("purchase_month", "orders_in_month", names(features_4_2012)), "2012", sep = "_")[2:13] setnames(features_4_2012, old = names(features_4_2012)[2:13], new_feature_names) ``` Putting together what we have: ```{r} df_for_prediction <- sales_2013 %>% left_join(features_2012, by = "contact_id") %>% left_join(features_2_2012, by = "contact_id") %>% left_join(features_3_2012, by = "contact_id") %>% left_join(features_4_2012, by = "contact_id") ``` Taking a look: ```{r} head(df_for_prediction) ``` Not suprisingly, the features have many NAs: ```{r, echo = FALSE} fun_count_na(data.table(df_for_prediction)) ``` What does this mean? Remember, many of the customers are one-off purchasers, for whom no historical data will be available. Here (based on the assumption that the starting dataset was a complete), we know that all the NAs are actually true 0s, hence we can just substitue the NAs with 0s. ```{r} df_for_prediction <- df_for_prediction %>% mutate(existing_2012_contact_id = ifelse(!is.na(existing_2012_contact_id), "Yes", "No")) df_for_prediction <- map(df_for_prediction, function(x) ifelse(is.na(x), 0, x)) %>% ##given vector x, if a value is NA it will be replaced by 0 as.data.table() ## Notes: this approach needs to be applied with caution! we don't want to replace non-number NAs with 0 for example. ## In this case it will be fine though - we already understand where NAs happen in the data head(df_for_prediction) ``` Making predictions on the zeros is one way to handle this issue - another one would be two build separate models for returning customers (a more complex one), and new customers (something very simple). We'll see in the modeling phase which one makes more sense in this case. ## Visual exploration of the "new" features Without much effort, we can visualize all of our predictors vs. our target. Not suprisingly all will have positive relationship, more or less linear ones. However, we shouldn't read to much into these graphs, given most values clutter on the lower end of the scale - this is just a "lazy" check to make sure all makes sense. ```{r, echo=FALSE, fig.width=15, fig.height = 39, fig.align='center'} plotlist <- list() i = 1 for(var in names(df_for_prediction)[c(-1, -2, -9)]) { plotlist[[i]] <- df_for_prediction %>% ggplot(aes_string(x= var, y= "total_sales_2013")) + geom_point(alpha = 0.1) + geom_smooth() + scale_y_continuous(labels = comma) + scale_x_continuous(labels = comma) i = i + 1 } grid.arrange(grobs = plotlist, ncol = 3) ``` # Modeling & model selection For this part I'll leverage the functionality given by <NAME>'s caret package, which gives easy access to many predictive methods, with possibility to tune the most important parameters. Briefly, this step is of three parts: I'll train & tune models with cross-validation. Once this is done, we can move onto selecting the best model - I'll use a separate held-out set for this, to avoid measuring performance on the tuning set. Selection criteria will be simply RMSE, which I'll try to optimize not just in general, but for separte sets of customer types as well. ## Separating training and evaluation datasets Let's separate the different datasets we will use for the different steps. Caret helps us with this one as well, hence we don't need to hustle with randomization. ( _Note: At this point we would need to be cautious with time-series data and partitioning. However, the way the dataset was engineered, this is no longer a concern._) ```{r} training_ratio <- 0.6 set.seed(93) #for reproducibility train_indices <- createDataPartition(y = df_for_prediction[["total_sales_2013"]], times = 1, p = training_ratio, list = FALSE) data_train <- df_for_prediction[train_indices, ] data_test <- df_for_prediction[-train_indices, ] split_ratio <- 3/4 set.seed(93) #for reproducibility perf_indices <- createDataPartition(y = data_test[["total_sales_2013"]], times = 1, p = split_ratio, list = FALSE) data_test <- data_test[perf_indices, ] data_perf <- data_test[-perf_indices, ] ``` We'll be using 60% of the all observations for training&tunining, 30% for model selection, and a third set of 10% for the final evaulation of the best model's performance. ## Training & parameter tuning When building models, I think using benchmarks is a good practice. Generally, I would break benchmarks into two categories: 1. Base models, which can be used to evaulate the added value by more complex ones 2. "The best possible model", usually something very complex for prediction. This can be later stripped of the extra features, and see if a simpler version (which might be easier to interpret) is able to provide similar performance metrics We'll build one from the 1st category - using only one predictor, total sales from 2012. This model will be a simple linear model (we've seen it in the previous visuals that the relationship is close to linear). As discussed, for all models I'm using 10-fold CV to help avoid overfitting: ```{r} train_control <- trainControl(method = "cv", number = 10) ``` Earlier I've mentioned that the larger part of the customers are one-off purchasers - this makes prediction for them harder, as we don't have anything to use for profiling that's specific for them. I was trying two approaches: 1. "no history" is represented by 0s in the predictors 2. training models only for the returning customers - for all others, we'll just use the average spending in 2012 per customer as predictors for 2013 As it turned out, the second approach gave slightly better results, so when discussing the performance of different models, that's what I'm going to focus on. We can even ask the question whether it makes sense to bother for predicting for totally new customers? In real life scenarios, where there is $ impact, I would likely approach them with a very different approach, but in general, we can't just disregard the majority of our customers. _Note: the solution of using the avg. sales per customer from the previous year is very unsophisticated - we could tune this further easily. Simple ideas come to mind: account for trend YoY in sales, as well as take average only for one-off customers in 2012. In this case, however, I'm only using the basic approach, and focus on returning customer more._ ```{r} data_train_full <- copy(data_train) data_train_just_returning <- data_train %>% filter(existing_2012_contact_id == "Yes") %>% select(everything(), -existing_2012_contact_id) avg_sales_2012 <- mean(df_for_prediction$total_sales_2012) ``` ### Benchmark model - simple glm Training the model(s): ```{r} #base model set.seed(93) glm_fit_full <- train(total_sales_2013 ~ total_sales_2012, method = "lm", data = data_train_full, trControl = train_control) set.seed(93) glm_fit_just_returning <- train(total_sales_2013 ~ total_sales_2012, method = "lm", data = data_train_just_returning, trControl = train_control) ``` For all models, I'll evalute performance later - so let's just go onto our 2nd model. ```{r, echo = FALSE} fun_plot_model_eval <- function(model= NULL, fit_full, fit_just_returning, testdata, avgSales_2012) { #creates "calibration" plots & calculates RMSE for predictions #calculate predictions full_predictions <- predict.train(fit_full, newdata = testdata) just_returning_predictions <- predict.train(fit_just_returning, newdata = testdata) %>% bind_cols(predicted_sales_w_corr = ., existing_2012_contact_id = testdata$existing_2012_contact_id, actual_sales = testdata$total_sales_2013) %>% mutate(predicted_sales_w_corr = ifelse(existing_2012_contact_id == "Yes", predicted_sales_w_corr, avg_sales_2012)) #bind datasets for charting & RMSE calc actual_vs_pred_full <- bind_cols(predicted = full_predictions, just_returning_predictions) %>% mutate(sample = "All") actual_vs_pred_just_returning <- actual_vs_pred_full %>% filter(existing_2012_contact_id == "Yes") %>% mutate(sample = "Returning customers") actual_vs_pred_just_new <- actual_vs_pred_full %>% filter(existing_2012_contact_id == "No") %>% mutate(sample = "New customers") actual_vs_pred <- bind_rows(actual_vs_pred_full, actual_vs_pred_just_returning, actual_vs_pred_just_new) #RMSE calc. rmse_corr_full <- RMSE(data_test$total_sales_2013, actual_vs_pred_full$predicted_sales_w_corr) rmse_corr_just_returning <- RMSE(data_test[existing_2012_contact_id == "Yes"]$total_sales_2013, actual_vs_pred_just_returning$predicted_sales_w_corr) #prepare texts for chart s_title <- ifelse(is.null(model), "", paste("Calibration plot for Model:", model, sep = " ")) s_subtitle <- paste("Full model RMSE: ", format(round(rmse_corr_full, digits = 3), nsmall=2), ". Only for returning customers: ", format(round(rmse_corr_just_returning, digits = 3), nsmall=2), sep = "") s_caption = "Note: Non-linear scale used for both axes" #create chart actual_vs_pred %>% mutate(category = cut(actual_sales, c(0, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, Inf), include.lowest = TRUE)) %>% group_by(sample, category) %>% summarize(mean_actual = mean(actual_sales), mean_predicted = mean(predicted), mean_predicted_w_corr = mean(predicted_sales_w_corr), num_obs = n()) %>% ggplot(aes(x= mean_actual, y = mean_predicted_w_corr, size= num_obs)) + geom_point(aes(color = sample)) + geom_abline(intercept = 0, slope = 1, linetype = "dashed") + scale_y_continuous(name = "Avg. predicted sales", labels = comma, trans="log10", breaks = c(0, 500, 1000, 5000, 10000)) + scale_x_continuous(name = "Avg. actual sales", labels = comma, trans="log10", breaks = c(0, 500, 1000, 5000, 10000)) + labs(title = s_title, subtitle = s_subtitle, caption = s_caption) + theme(legend.position="none") + facet_grid(~sample) } ``` ```{r, echo = FALSE} p_model1 <- fun_plot_model_eval("GLM Benchmark", glm_fit_full, glm_fit_just_returning, data_test, avg_sales_2012) ``` ### Model 2 - glmnet with LASSO & ridge - parameter tuned The second model we are going to train is glmnet, applying LASSO & Ridge regularization. This is a nice way to train a linear model, without worrying much about overfitting or variable selection - L1/L2 penalities will do that automatically. ```{r} predictor_names <- names(data_train)[c(-1:-16)] tune_grid <- expand.grid("alpha" = c(0, 1), "lambda" = seq(from = 0.00, to = 1, by = 0.025)) set.seed(93) glmnet_fit_full <- train(total_sales_2013 ~ . -contact_id, method = "glmnet", data = data_train, trControl = train_control, tuneGrid = tune_grid, preProcess = c("center", "scale")) set.seed(93) glmnet_fit_just_returning <- train(total_sales_2013 ~ . -contact_id, method = "glmnet", data = data_train_just_returning, trControl = train_control, tuneGrid = tune_grid, preProcess = c("center", "scale")) ``` ```{r, echo = FALSE} p_model2 <- fun_plot_model_eval("GLMNet", glmnet_fit_full, glmnet_fit_just_returning, data_test, avg_sales_2012) ``` ### Model 3 - single decision tree Moving into a bit different territory - decision trees. They are regularly used for classification problems, however they can be helpful for regression as well. The advantage of trees is that they are good at addressing non-linear patterns in the data - something we can only do in linear models by feature engingeering (e.g. adding polynomial terms). Single trees have some disadvantages as well, which I'll discuss in the next part. ```{r} set.seed(93) rpart_fit_full <- train(total_sales_2013 ~ . -contact_id, data = data_train, method = "rpart", tuneLength = 20, trControl = train_control) set.seed(93) rpart_fit_just_returning <- train(total_sales_2013 ~ . -contact_id, data = data_train_just_returning, method = "rpart", tuneLength = 20, trControl = train_control) ``` ```{r, echo = FALSE} p_model3 <- fun_plot_model_eval("Single decision tree (rpart)", rpart_fit_full, rpart_fit_just_returning, data_test, avg_sales_2012) ``` ### Model 4 - Bagging (/ Random Forest) So what is the (theoretical) problem with single trees? Well, they are implemented as "greedy" algorithms, which are prone to get stuck in local optimum. My original implementation used Random Forest, which addresses this in two steps: 1. By bootstrapping the dataset, and fitting many trees on the new samples. This makes the results more robust 2. By always only using a subset of the predictors at each split. Simple bootstrapping might still produce very correlated trees, this helps with that Fitting RF takes hours in the caret implementation unforunately, and as it turned out the results are not that good. So I switched back to simple treebag, which I could reran more easily as needed. ```{r} set.seed(93) rf_fit_full <- train(total_sales_2013 ~ . -contact_id, data = data_train, method = "treebag", tuneLength = 20, ntree = 250, trControl = train_control) set.seed(93) rf_fit_just_returning <- train(total_sales_2013 ~ . -contact_id, data = data_train_just_returning, method = "treebag", tuneLength = 20, ntree = 250, trControl = train_control) ``` ```{r, echo = FALSE} p_model4 <- fun_plot_model_eval("Bagging - 250 trees", rf_fit_full, rf_fit_just_returning, data_test, avg_sales_2012) ``` ## Model selection Let's start by a summary visualization of the results, which can be seen below. RMSEs and plots are based on how the models performed on the held-out test sets, not the original training data. ```{r, echo = FALSE, fig.align='center', fig.width=15, fig.height=16} grid.arrange(p_model1, p_model2, p_model3, p_model4, ncol = 1) ``` So.. first things first: how can we evaulate the overall performance of our models? The best RMSE achieved is ~830 - that looks very large! But let's remember for a moment that our data exhibits very large variaton as well: ```{r} data_train_just_returning %>% summarize(avg = mean(total_sales_2013), std_dev = sd(total_sales_2013)) ``` This still doesn't make me overly happy with the performance, but at least we know that it might not be that bad. Another reason for the not-so-great performance can be read from the plots: the models are exhibiting strong bias for different customer groups! - For low-spenders, we overpredict on average - For mid-spenders, we tend to underpredict on average - While the biggest spenders are OK more or less My original suspection was that this is due to the heavily skewed distribution of the sales data. However, after trying multiple correction (log transformations, or filtering top 1%) the models still exhibited similar behavior. The above explanation still makes sense to me - RMSE will penalize larger mispredictions, which are more likely to happen for the tail sales numbers. Let's assume for now that there is nothing we could do about the results, and we have to believe one of our models is truly the best. Which one should we choose? Generally, the results are similar, but the GLMNet fit stands out a bit. It's a good question to ask ourselves whether that makes sense or not. At first, I expected the original RF to perform best - however, we can see that tree-based methods lag behind. One explanation can be that the actual functional form that we are trying to estimate is linear - in this case, tree methods, however good they are at capturing nonlinearities, will be in disadvantage. And if we take a look at the variable important scores extract from our models, we'll see that the most imporant variables seem to be actually linear in total_sales_2013 when we visualized them earlier: ```{r, echo = FALSE, fig.align='center', fig.width=9, fig.height=7} t1 <- data.table(varImp(rf_fit_just_returning, scale = T)$importance, keep.rownames = TRUE) %>% setnames(c("variable", "Importance Score")) %>% mutate(model = "Treebag") t2 <- data.table(varImp(glmnet_fit_just_returning, scale = T)$importance, keep.rownames = TRUE) %>% setnames(c("variable", "Importance Score")) %>% mutate(model = "GLMNet") t1 %>% rbind(t2) %>% mutate(variable = reorder(variable, `Importance Score`)) %>% ggplot(aes(x=variable, y= `Importance Score`)) + geom_line(color = "lightblue", size = 1.1) + geom_point(aes(color = model), size = 2.5) + coord_flip() ``` With this explanation (+based on best RMSE), I'm comfortable taking GLMNet as our best model. # Model performance evaluation and final words ## Performance evaluation Let do one final step of evalation, with the second held-out set we kept. This was needed, as the first one was used to select our best model, hence it might biased towards it as well. ```{r, echo = FALSE, fig.width=15, fig.height=6} fun_plot_model_eval("GLMNet", glmnet_fit_full, glmnet_fit_just_returning, data_perf, avg_sales_2012) ``` Okay... so our RMSE metrics look even worse than before. Is that a concern regarding in terms of the previous "good" performance being just a result of chance? I don't think so. This last sample is smaller - hence, a few big mispredictions can drive up RMSE. The plots show that the fit is similar to what we had before, hence I'm going to accept that this model is the best I could do now. Let's consider a couple of possible improvements: 1. Enhanced scope - by more conscious definition of our target, we could filter to narrow the data, or build multiple models for different groups of customers 2. More features - either we can create further ones from the dataset (e.g. try if 0 costs actually represent promotions), or see if we can get more features from external sources 3. Selecting a better model form, which might fit the data better 4. Depending on the final goal of the analysis, we might decide to create our own loss function. By defaulting to RMSE for model selection, we used one which is symmetric and non-linear -- both of these attributes could be tailored to the exact need. ## External validity? With all prediction exercises, we need to ask ourselves whether our results would be applicable outside of the current dataset. In this case, there are some concerns regarding that - specially as we only used two years of data, so we can't really predict how good we can perform over time. Also, as speciality of the data, majority customers were new - and as discussed, in lack of historical patterns, we are very limited in what we can do.
e3fc175cd64304b2fa5825c0cc078a70fc71bb16
[ "Markdown", "R", "RMarkdown" ]
3
R
tomiaJO/SALES_PRED
c2ee5505cd326e883227c8fc7b4d1985c6cb3ff1
809c13c800c4d23355263929db861a6763635590
refs/heads/master
<repo_name>stemicha/MVA_shiny_app<file_sep>/ui.R library(colourpicker) library(shinydashboard) library(plotly) library(DT) library(shinyWidgets) library(bit64) dashboardPage( dashboardHeader(title = "PCA | HCPC | Clustering of data",titleWidth = 400), dashboardSidebar( sidebarMenu( #action button for run or Demo actionButton("inputButton", "DEMO or RUN",width = "90%",icon=icon("youtube-play"),style="color: #fff; background-color: #D84315; border-color: #BF360C"), #select_meta_data_coloring uiOutput("meta.sele"), #File main input fileInput('file1', 'MAIN DATA: Choose CSV or TXT', accept=c('text/csv', 'text/comma-separated-values,text/plain', '.csv')), #File meta input fileInput('file2', 'META DATA: Choose CSV or TXT', accept=c('text/csv', 'text/comma-separated-values,text/plain', '.csv')), awesomeRadio('sep', 'table separator', c(Tab='\t', Comma=',' ), selected='\t'), #download examples menuItem("download example", tabName = "download example", icon = icon("table"), #download examples downloadButton(outputId= "file1.data.frame",label = "Download example data frame",class="butt2"), br(), #download examples downloadButton(outputId= "file2.data.frame",label = "Download example meta data",class="butt2"), br(), # making the font italics this time tags$head(tags$style(".butt2{background-color:black;} .butt2{color: white;} .butt2{font-style: italic;}")) ), #data transformations menuItem("data transformation", tabName = "data transformation", icon = icon("bar-chart"), materialSwitch(inputId = "logtrans", label = "Do log2 transformation of data?", status = "danger",value = FALSE,width = 400), materialSwitch(inputId = "scaling", label = "Do scaling of data?", status = "danger",value = TRUE,width = 400), materialSwitch(inputId = "missval", label = "missing value imputation of data? (TRUE = replace missing values with HM [half-minimal value])", status = "danger",value = TRUE,width = 400) ), #clustering adjustments menuItem("clustering", tabName = "clustering adjustments", icon = icon("cubes"), #selection sliderInput("num.cluster", "number of cluster (dendrogram plot):" , min = 2, max = 30, value = 3,step = 1), selectInput(inputId = "metrics", label = "metrics for clustering:", choices = list("euclidean","manhattan"),selected = "euclidean"), selectInput(inputId = "linkage", label = "linkage for clustering:", choices = list("single","complete","ward","average"),selected = "average") ), #general adjustments menuItem("general adjustments", tabName = "general adjustments", icon = icon("wrench"), sliderInput("theme.cex", "basic theme text size:", 18, 60, value = 22, step=1), sliderInput("num.ele", "number of top elements to contribution:", 1, 50, value = 10, step=1) ), menuItem("downloads", tabName = "downloads", icon = icon("cloud-download"), downloadButton('plots2D_PCA', '2D PCA plots',class="butt2"), br(), downloadButton('plots2D_PCA_legend', '2D PCA legend',class="butt2"), br(), downloadButton('plot_PCA_scree', 'Scree plot',class="butt2"), br(), downloadButton('plot_PCA_contrib', 'contribution plots',class="butt2"), br(), downloadButton('plot_PCA_contrib_biplot', 'contribution biplot plots',class="butt2"), br(), downloadButton('plot_dendro', 'dendrogram cluster analysis',class="butt2"), br(), downloadButton('correlationplot', 'correlation plots',class="butt2"), br(), downloadButton('boxplo', 'Boxplots',class="butt2"), br(), downloadButton('pca.interpret.dim1', 'characteristic for 1st. Dim.',class="butt2"), br(), downloadButton('pca.interpret.dim2', 'characteristic for 2nd. Dim.',class="butt2"), br(), downloadButton('pca.interpret.dim3', 'characteristic for 3rd. Dim.',class="butt2"), # making the font italics this time tags$head(tags$style(".butt2{background-color:black;} .butt2{color: white;} .butt2{font-style: italic;}")) ), #versioning tags$hr(), em("version 1.4.6 | <NAME>") ) ), dashboardBody( #hide error messsages in shiny tags$style(type="text/css", ".shiny-output-error { visibility: hidden; }", ".shiny-output-error:before { visibility: hidden; }" ), # Also add some custom CSS to make the title background area the same # color as the rest of the header. tags$head(tags$style(HTML(' /* logo */ .skin-blue .main-header .logo { background-color: #080A0D; } /* logo when hovered */ .skin-blue .main-header .logo:hover { background-color: #080A0D; } /* navbar (rest of the header) */ .skin-blue .main-header .navbar { background-color: #080A0D; } /* main sidebar */ .skin-blue .main-sidebar { background-color: #080A0D; } /* active selected tab in the sidebarmenu */ .skin-blue .main-sidebar .sidebar .sidebar-menu .active a{ background-color: #080A0D; } /* other links in the sidebarmenu */ .skin-blue .main-sidebar .sidebar .sidebar-menu a{ background-color: #080A0D; color: #FFFFFF; } /* other links in the sidebarmenu when hovered */ .skin-blue .main-sidebar .sidebar .sidebar-menu a:hover{ background-color: #616262; } /* toggle button when hovered */ .skin-blue .main-header .navbar .sidebar-toggle:hover{ background-color: #080A0D; } '))), fluidRow( tabBox(width = 9, title = "", # The id lets us use input$main on the server to find the current tab id = "main", #tabPanel("testx", textOutput("testx")), #tabPanel("table", tableOutput("table.out")), # pdf(NULL) important before plotly out put otherwise Rplot.pdf error occur tabPanel("PCA 3D plots", pdf(NULL),plotlyOutput("facto.plot.3d",height = 600)), tabPanel("PCA 2D plots", dropdownButton( #add menu directly to plot (shinyWidgets) tags$h3("2D PCA plot adjustments:"), checkboxInput("shownam", "show labels ?", value = FALSE), checkboxInput("ellipses", "add ellipses ?", value = FALSE), checkboxInput("show.mean.points", "show center points ?", value = FALSE), selectInput("ellipses.method","ellipses calculation method",c("norm","convex","t","euclid"),selected = "norm"), numericInput("ellipses.level","size of the concentration ellipse in normal probability:",value=0.95), numericInput("ellipses.alpha","transparency of ellipses:",value=0.1), sliderInput("plot.point.size","size of the points:",min = 1,max = 10,value=3,step = 0.5), circle = TRUE, status = "danger", icon = icon("wrench"), width = "300px", tooltip = tooltipOptions(title = "Click to open plot adjustments !") ), plotOutput("facto.plot.2d",height = 800) #,plotOutput("facto.plot.2d.legend") ), tabPanel("HCPC 3D plot", plotOutput("facto.plot.hcpc.3d",height = 800)), tabPanel("HCPC 2D plot", plotOutput("facto.plot.hcpc.2d",height = 800)), tabPanel("HCPC tree plot", plotOutput("facto.plot.hcpc.tree")), tabPanel("HCPC bar plot", plotOutput("facto.plot.hcpc.bar")), tabPanel("Scree plots", plotOutput("facto.scree",height = "800px")), tabPanel("contribution plots of data input in PCA", plotOutput("facto.contr.id"),plotOutput("facto.contr.sample")), tabPanel("contribution samples matrix plot",plotOutput("corrplot.var",width = 800,height = 1200)), tabPanel("contribution biplot of PCA", plotOutput("facto.contr.biplot",height = "800px")), tabPanel("dimension description", fluidRow( box(DT::dataTableOutput("table.pca.interpret.dim1"),title = "1st. Dimension",width = 4,solidHeader = TRUE,status = "primary"), box(DT::dataTableOutput("table.pca.interpret.dim2"),title = "2nd. Dimension",width = 4,solidHeader = TRUE,status = "success"), box(DT::dataTableOutput("table.pca.interpret.dim3"),title = "3rd. Dimension",width = 4,solidHeader = TRUE,status = "danger") )), tabPanel("boxplot of data input in PCA", plotOutput("boxplot.data")), tabPanel("correlation plot of data input in PCA", dropdownButton( #add menu directly to plot (shinyWidgets) tags$h3("correlation plot adjustments:"), colourpicker::colourInput("col2", "Select upper colour:", "orangered3",palette = "square", returnName = TRUE,showColour = c("both")), colourpicker::colourInput("colneutral", "Select neutral colour:", "white",palette = "square", returnName = TRUE,showColour = c("both")), colourpicker::colourInput("col1", "Select lower colour:", "dodgerblue3",palette = "square", returnName = TRUE,showColour = c("both")), sliderInput("leg.lim", "corrplot color limits:" , min = -1, max = 1, value = c(0.7,1),step = 0.1), numericInput("sig.level", "sig. level:" , value = 0.01), materialSwitch(inputId = "corr.reorder", label = "Do reordering based on clustering?", status = "danger",value = TRUE,width = 400), sliderInput("corr.size", "size text factor :" , min = 5, max = 70, value = 7,step = 1), circle = TRUE, status = "danger", icon = icon("wrench"), width = "300px", tooltip = tooltipOptions(title = "Click to open plot adjustments !") ), plotOutput("corr.plot",width = 800,height = 800) ), tabPanel("dendrogram over samples", plotOutput("den.out",height = 1000))#, #tabPanel("test table", tableOutput("table.test")) ), tabBox(width = 3, title = tagList(shiny::icon("question"), "help"),side = "right",selected = "color selction", tabPanel("general", h3("PCA and HCPC function (FactoMineR package in R)"), h5("scaled = correlation matrix // unscaled = covariation matrix"), h5("Hierarchical Clustering on Principle Components (HCPC)"), h5("Principle Components Analysis (PCA)") , valueBoxOutput("individual.count",width="100%"), valueBoxOutput("raw.data.count",width="100%"), valueBoxOutput("pca.data.count",width="100%"), valueBoxOutput("removed.variables",width="100%") ), tabPanel("PCA", strong("used here:"),p("When genes/proteins are variables, the analysis creates a set of “principal gene components” that indicate the features of genes that best explain the experimental responses they produce."), tags$hr(), p("When experiments are the variables, the analysis creates a set of “principal experiment components” that indicate the features of the experimental conditions that best explain the gene behaviors they elicit."), h5("<NAME>. & <NAME>. Principal components analysis to summarize microarray experiments: application to sporulation time series. Pacific Symposium on … (2000)."), tags$hr(), tags$div(class='success',HTML( "The amount of variation retained by each PC is called <strong>eigenvalues</strong>. The first PC corresponds to the direction with the maximum amount of variation in the data set.")), strong("cos2:"), p("The squared loadings for variables are called cos2 ( = cor * cor = coord * coord)."), HTML("<div class='success'> <ul> <li>The cos2 values are used to estimate the quality of the representation</li> <li>The closer a variable is to the circle of correlations, the better its representation on the factor map (and the more important it is to interpret these components)</li> <li>Variables that are closed to the center of the plot are less important for the first components.</li> </ul> </div>"), strong("contributions:"), p("The contributions of variables in accounting for the variability in a given principal component are (in percentage) : (variable.cos2 * 100) / (total cos2 of the component)"), p("The larger the value of the contribution, the more the variable contributes to the component."), HTML("<p><span class='question'>What means the red line on the graph?</span></p> <div class='warning'> <ul> <li><p>If the contribution of the variables were uniform, the expected value would be 1/length(variables) = 1/10 = 10%.</p></li> <li>The red dashed line on the graph above indicates the expected average contribution. For a given component, a variable with a contribution larger than this cutoff could be considered as important in contributing to the component.</li> </ul> </div>") ), tabPanel("clustering", #explaination cluserting strong("metrics"), h5("euclidean"), h6("Euclidean distances are root sum-of-squares of differences."), h5("manhattan"), h6("Manhattan distances are the sum of absolute differences."), #linkage tags$hr(), strong("linkage") , h5("Single"), h6("With single linkage method (also called nearest neighbor method), the distance between two clusters is the minimum distance between an observation in one cluster and an observation in the other cluster. The single linkage method is a good choice when clusters are obviously separated. When observations lie close together, the single linkage method tends to identify long chain-like clusters that can have a relatively large distance separating observations at either end of the chain."), h5("Average"), h6("With the average linkage method, the distance between two clusters is the mean distance between an observation in one cluster and an observation in the other cluster. Whereas the single or complete linkage methods group clusters are based on single pair distances, the average linkage method uses a more central measure of location."), #h5("Centroid"), #h6("With the centroid linkage method, the distance between two clusters is the distance between the cluster centroids or means. Like the average linkage method, this method is one more averaging technique."), h5("Complete"), h6("With the complete linkage method (also called furthest neighbor method), the distance between two clusters is the maximum distance between an observation in one cluster and an observation in the other cluster. This method ensures that all observations in a cluster are within a maximum distance and tends to produce clusters with similar diameters. The results can be sensitive to outliers."), #h5("Median"), #h6("With the median linkage method, the distance between two clusters is the median distance between an observation in one cluster and an observation in the other cluster. This is a different averaging technique, but uses the median instead of the mean, thus downweighting the effect of outliers."), #h5("McQuitty"), #h6("With McQuitty's linkage method, when two clusters are be joined, the distance of the new cluster to any other cluster is calculated as the average of the distances of the soon to be joined clusters to that other cluster. For example, if clusters 1 and 3 are to be joined into a new cluster, say 1*, then the distance from 1* to cluster 4 is the average of the distances from 1 to 4 and 3 to 4. Here, distance depends on a combination of clusters instead of individual observations in the clusters."), h5("Ward"), h6("With Ward's linkage method, the distance between two clusters is the sum of squared deviations from points to centroids. The goal of Ward's linkage method is to minimize the within-cluster sum of squares. It tends to produce clusters with similar numbers of observations, but it is sensitive to outliers. In Ward's linkage method, it is possible for the distance between two clusters to be larger than dmax, the maximum value in the original distance matrix. If this occurs, the similarity will be negative.") ), #tabPanel("sessionInfo", # uiOutput("sessioninfo")), tabPanel("method", uiOutput("helper.text.method")), tabPanel("color selction", uiOutput("colorselector")) ) #tabbox close )#close fluidrow )#close dashboard body )#close dashboard page #### to do !!! # drastic performance optimization ! split reactive element!!! #version: 1.4.6 # add selectable colors helptext if elements in meta data are above 15 elements #version: 1.4.5 # add selectable colors # use factoMineR plot function for HCPC (bug was fixed an therefore the sefl edited function is no longer needed) #version: 1.4.4 # fixed issue if to low number of dimension was generated in PCA for contribution from "contri<-get_pca_ind(pca.facto)$contrib[,1:8]" to "contri<-get_pca_ind(pca.facto)$contrib[,1:5]" #version: 1.4.3 # use mean.points to show and hide centers # add correlation plot to ind contrib #add value boxes for data overview #version: 1.4.2 # use check.names=F for import to avoid "X" infront of numbers in colnames # add re-ordering selection for correlation plot #version: 1.4.1 # fix 64bit number issue # boxplot issue remianing! #version: 1.4 # PCA plot from FactoExtra package # add ellipsis option to 2D plot # solve issue if numbers are used for sample description #version: 1.3 # add new shiny dashboard look and feel #version: 1.2 # do shiny dashboard adpation # add dimdesc + table (correlation and test) # This function is designed to point out the variables and the categories that are the most characteristic according to each dimension obtained by a Factor Analysis. #version: 1.1 # implement feedback and resolve some bugs and naming # resolve input action button bug; now using eventReactive instead of isolate #version: 1 # release of the app # add colour picker # add theme size slidebar # transform UI to dashboard # add HCPC # add dendrogram # add PCA plotly # add PCA non-overlapping labels <file_sep>/helper_functions/session_info_extract_pretty.R includeRmd <- function(path){ # https://groups.google.com/d/topic/shiny-discuss/ObgFdmusyJM/discussion if (!require(knitr)) stop("knitr package is not installed") if (!require(markdown)) stop("Markdown package is not installed") shiny:::dependsOnFile(path) contents = paste(readLines(path, warn = FALSE), collapse = '\n') html <- knitr::knit2html(text = contents, fragment.only = TRUE) Encoding(html) <- 'UTF-8' return(HTML(html)) }<file_sep>/server.R library(shiny) library(shinyBS) library(shinyjs) library(colourpicker) library(dplyr) library(ggplot2) library(gridExtra) library(metricsgraphics) library(RColorBrewer) library(scales) library(ggrepel) library(data.table) library(FactoMineR) library(factoextra) library(plotly) library(ggcorrplot) library(dendextend) library(DT) library(knitr) library(markdown) library(bit64) #load helper functions source(file.path("helper_functions/ggcorrplot_edited.R")) source(file.path("helper_functions/multiplot.R")) source(file.path("helper_functions/ggplot_extract_legend.R")) #source(file.path("helper_functions/hcpc_plot_edited.R")) source(file.path("helper_functions/session_info_extract_pretty.R")) options(shiny.usecairo=TRUE,shiny.maxRequestSize=200*1024^2) shinyServer(function(input, output, session) { example<-fread(file.path("data/#protein quantification_mean_peptide_intensities_Rho_cytoplasmic_qval_0-001.txt"),sep = "\t",header=T,data.table = F,na.strings = "NA") example[,-1]<-apply(example[,-1],2,function(x) log2(as.numeric(as.character(x)))) example.meta<-fread(file.path("data/#protein quantification_mean_peptide_intensities_Rho_cytoplasmic_qval_0-001_META-data.txt"),sep = "\t",header=T,data.table = F) data <- eventReactive(input$inputButton,{ if(is.null(input$file1)){ dataframe <- example } else { dataframe <- fread( input$file1$datapath, sep=input$sep, header = T,data.table = F,na.strings = "NA",check.names = F) } return(dataframe) }) data.meta <- eventReactive(input$inputButton,{ if(is.null(input$file2)){ dataframe <- example.meta } else { dataframe <- fread( input$file2$datapath, sep=input$sep, header = T,data.table = F,na.strings = "NA",check.names = F) } return(dataframe) }) meta.names<-reactive({ meta.in<-data.frame(data.meta()) meta.select<-input$meta.sele ele<-unique(as.character(meta.in[,meta.select])) if(length(ele)<15){ ele<-c(ele,rep("not in use",15-length(ele))) } return(ele) }) meta.names.ele<-reactive({ meta.in<-data.frame(data.meta()) meta.select<-input$meta.sele ele<-unique(as.character(meta.in[,meta.select])) return(length(ele)) }) output$colorselector <- renderUI({ if(meta.names.ele()>15){ helpText("more than 15 elements in selected meta data. A color gradient will be used.") }else{ fluidRow(column(6, colourpicker::colourInput(inputId = "color1",label=meta.names()[1],value="#0057e7",showColour="background"), colourpicker::colourInput(inputId = "color2",label=meta.names()[2],value="#d62d20",showColour="background"), colourpicker::colourInput(inputId = "color3",label=meta.names()[3],value="#008744",showColour="background"), colourpicker::colourInput(inputId = "color4",label=meta.names()[4],value="#ffa700",showColour="background"), colourpicker::colourInput(inputId = "color5",label=meta.names()[5],value="#03A9F4",showColour="background"), colourpicker::colourInput(inputId = "color6",label=meta.names()[6],value="#E91E63",showColour="background"), colourpicker::colourInput(inputId = "color7",label=meta.names()[7],value="#009688",showColour="background") ), column(6, colourpicker::colourInput(inputId = "color8",label=meta.names()[8],value="#4CAF50",showColour="background"), colourpicker::colourInput(inputId = "color9",label=meta.names()[9],value="#B71C1C",showColour="background"), colourpicker::colourInput(inputId = "color10",label=meta.names()[10],value="#FF5722",showColour="background"), colourpicker::colourInput(inputId = "color11",label=meta.names()[11],value="#3F51B5",showColour="background"), colourpicker::colourInput(inputId = "color12",label=meta.names()[12],value="#795548",showColour="background"), colourpicker::colourInput(inputId = "color13",label=meta.names()[13],value="#607D8B",showColour="background"), colourpicker::colourInput(inputId = "color14",label=meta.names()[14],value="#673AB7",showColour="background"), colourpicker::colourInput(inputId = "color15",label=meta.names()[15],value="#FFC107",showColour="background") ) ) } }) #manual colors #general.colors<-function()c("#0057e7","#d62d20","#008744","#ffa700","#03A9F4","#E91E63","#009688","#4CAF50","#B71C1C","#FF5722","#3F51B5","#795548","#607D8B","#673AB7","#FFC107") general.colors<-reactive({c(input$color1,input$color2,input$color3,input$color4,input$color5,input$color6,input$color7,input$color8,input$color9,input$color10,input$color11,input$color12,input$color13,input$color14,input$color15)}) #gradient colors general.colors.gradient<-colorRampPalette(c("black","#0057e7","#d62d20","#008744","#ffa700","grey")) # barplot(rep(1,length(general.colors.gradient)),col=general.colors.gradient) # barplot(rep(1,length(general.colors)),col=general.colors,names.arg = seq(1:length(general.colors))) #data<-function()fread("data file DCM_STC_resids_test2.txt",sep = "\t",header = T) #data.meta<-function()fread("metadata STC and DCM_test2.txt",sep = "\t",header = T) ## DO PCA reactive element ########################### pca <- reactive({ withProgress(message = 'Process:', value = 0, { # Increment the progress bar, and update the detail text. incProgress(1/8, detail = paste("prepare data...")) table.in <- data.frame(data()) raw.dim<-dim(table.in) meta.in <- data.frame(data.meta()) #table.in<-example #meta.in<-example.meta colnames(meta.in)[1]<-"sample" # overwrite first column header to be more universal meta.in[,1]<-as.character(meta.in[,1]) #as factor important when numbers are used row.nam<-table.in[,1] table.in<-table.in[,-1] table.in<-as.data.frame(sapply(table.in, as.numeric))# transform all to numeric variables rownames(table.in)<-row.nam #input<-list(meta.sele="sex") #meta selection + colorimng meta.select<-input$meta.sele meta.select.number.of.elements<-length(unique(as.factor(as.character(meta.in[,meta.select])))) if(meta.select.number.of.elements>15){ used.col<-general.colors.gradient(meta.select.number.of.elements) }else{ used.col<-general.colors()[1:meta.select.number.of.elements] } ## perform minimum imputation if missing values if(input$missval) {table.in[is.na(table.in)]<-min(table.in[table.in!=0],na.rm=T)/2}else{table.in<-na.omit(table.in);row.nam <- rownames(table.in)} #only 100% valid values or missing value imputation lowest int #table.in[is.na(table.in)]<-min(table.in,na.rm=T) #log2 transform if(input$logtrans) {table.in<-apply(table.in,2,log2)} #log transformation rownames(table.in)<-row.nam #scaling table.transform <-if(input$scaling) scale(table.in,center = T,scale = T) else scale(table.in,scale = F,center = T) p.mat <- cor_pmat(table.in) # Increment the progress bar, and update the detail text. incProgress(2/8, detail = paste("correlation plot ...")) #correlation plot corr <- round(cor(table.in,method = "spearman"), 2) # using hierarchical clustering correlation.plot<-ggcorrplot(corr, colors = c(input$col1, input$colneutral, input$col2), legend.title = "correlation",leg.lim=input$leg.lim,lab_size = input$theme.cex/input$corr.size, sig.level = input$sig.level,hc.order = input$corr.reorder,hc.method = input$linkage,method = "square",type = "full",lab = TRUE, p.mat = p.mat, insig = "blank")+ theme_classic(base_size = input$theme.cex)+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5,hjust = 1))+ labs(title="correlation plot",subtitle=paste("spearman corr. & reord. (linkage:",input$linkage,")"),y="",x="") # Increment the progress bar, and update the detail text. incProgress(3/8, detail = paste("dendrogram plot ...")) ## dendrogramm: dend <- as.dendrogram(hclust(dist(t(table.in),method = input$metrics), input$linkage)) den.out.plot<-dend%>% set("hang_leaves")%>% set("labels_colors",k=input$num.cluster)%>% set("labels_cex",c(1))%>% set("branches_lwd",c(4))%>% set("branches_k_color",k=input$num.cluster) %>% as.dendrogram # Increment the progress bar, and update the detail text. incProgress(4/8, detail = paste("box plot ...")) #boxplot over data box.data<-try(data.table::melt(table.transform),silent = T) colnames(box.data)[2]<-"sample" ## unify names box.data[,2]<-as.factor(box.data[,2]) box.data<-try(dplyr::right_join(box.data,meta.in,by="sample"),silent = T) box.data$sample<-as.factor(box.data$sample) box.data$sample<-factor(box.data$sample,levels = unique(box.data$sample),ordered = TRUE) #reorder data to sample boxplot.of.data <- ggplot(box.data,aes(x = sample,y = value,fill = factor(get(meta.select))))+ geom_boxplot()+ ylim(c(min(box.data$value,na.rm=T),max(box.data$value,na.rm=T)))+ #min max scaling of plot labs(title="Boxplot",subtitle="data without missing values",y="values",x="samples",fill="group")+ theme_classic(base_size = input$theme.cex)+ theme(axis.text.x = element_text(angle = 90, hjust = 1))+ scale_fill_manual(values = c(used.col)) # Increment the progress bar, and update the detail text. incProgress(5/8, detail = paste("PCA ...")) #PCA generation # numeric variables in columns // individuals rows # protein/genes in columns // samples/experiemnts in rows #transforming? #pca.facto <-if(input$transpose) PCA(t(table.in), graph = FALSE,ncp = 10,scale.unit = input$scaling) else PCA(table.in, graph = FALSE,ncp = 10,scale.unit = input$scaling) pca.dim<-dim(table.in) pca.facto <-PCA(t(table.in), graph = FALSE,ncp = 10,scale.unit = input$scaling) pca.interpret<-dimdesc(pca.facto,axes = 1:3,proba = 0.05) #pca.facto.scree.var,pca.facto.plot incProgress(7/8, detail = paste("generating plots ...")) pca.facto.scree.var<-#screeplot # eigenvalue fviz_eig(pca.facto, choice = c("variance"),addlabels=TRUE, hjust = -0.3,ncp = 10) + labs(title="Scree plot", subtitle="explained variances")+ ylim(c(0,100))+ theme_bw(base_size = input$theme.cex) #vizualize controbutions facto.contr.id.1<-fviz_contrib(pca.facto, choice ="ind", axes = 1,top = input$num.ele)+ labs(title="Ind. contribution (1st Dim.)", subtitle="",x="")+theme_bw(base_size = input$theme.cex)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) facto.contr.id.2<-fviz_contrib(pca.facto, choice ="ind", axes = 2,top = input$num.ele)+ labs(title="Ind. contribution (2nd Dim.)", subtitle="",x="")+theme_bw(base_size = input$theme.cex)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) facto.contr.sample.1<-fviz_contrib(pca.facto, choice="var", axes = 1,top = input$num.ele)+labs(title="Var. contribution (1st Dim.)", subtitle="",x="")+theme_bw(base_size = input$theme.cex)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) facto.contr.sample.2<-fviz_contrib(pca.facto, choice="var", axes = 2, top = input$num.ele)+labs(title="Var. contribution (2nd Dim.)", subtitle="",x="")+theme_bw(base_size = input$theme.cex)+theme(axis.text.x = element_text(angle = 90, hjust = 1)) #contribution plot facto.contr.ID.biplot<-fviz_pca_var(pca.facto, select.var = list(contrib = input$num.ele),col.var = "contrib",col.circle = "black")+ labs(title=paste("TOP", input$num.ele), subtitle="contributions to PCA")+ theme_bw(base_size = input$theme.cex) #generate 3D plotly version of PCA plot FactomineR :: Eigenvalues = coordinates plotly3d.facto<-as.data.frame(pca.facto$ind$coord) plotly3d.facto.plot <- plot_ly(plotly3d.facto, x = ~Dim.1, y = ~Dim.2, z = ~Dim.3, color = ~as.factor(as.character(meta.in[,meta.select])), colors = c(used.col)) %>% add_markers() %>% add_text(text = meta.in$sample, textposition = "top right",visible = "legendonly") %>% layout(title = "PCA (individuals coordinates)", scene = list(xaxis = list(title = paste("1st PC (", round(pca.facto$eig[1,2]), "%)", sep="")), yaxis = list(title = paste("2nd PC (", round(pca.facto$eig[2,2]), "%)", sep="")), zaxis = list(title = paste("3rd PC (", round(pca.facto$eig[3,2]), "%)", sep="")))) #plot PCA eigenvalues // 1vs2 pca.facto.plot<-fviz_pca_ind(pca.facto,axes = c(1, 2),mean.point=input$show.mean.points,pointsize=input$plot.point.size,pointshape=19, label="none",ellipse.type = input$ellipses.method,ellipse.alpha=input$ellipses.alpha,addEllipses = input$ellipses,ellipse.level=input$ellipses.level,habillage = as.factor(as.character(meta.in[,meta.select])))+ scale_color_manual(values = c(used.col))+ theme_classic(base_size = input$theme.cex)+ labs(title="PCA: PC 1vs2",subtitle="individuals coordinates",color="group")+ guides(color=F,fill=F,shape = F) if(input$shownam) pca.facto.plot<-pca.facto.plot +geom_text_repel(aes(label=rownames(pca.facto$ind$coord)), label = rownames(pca.facto$ind$coord)) #plot PCA eigenvalues // 1vs3 pca.facto.plot1<-fviz_pca_ind(pca.facto,axes = c(1, 3),mean.point=input$show.mean.points,pointsize=input$plot.point.size,pointshape=19, label="none",ellipse.type = input$ellipses.method,ellipse.alpha=input$ellipses.alpha,addEllipses = input$ellipses,ellipse.level=input$ellipses.level,habillage = as.factor(as.character(meta.in[,meta.select])))+ scale_color_manual(values = c(used.col))+ theme_classic(base_size = input$theme.cex)+ labs(title="PCA: PC 1vs3",subtitle="individuals coordinates",color="group")+ guides(color=F,fill=F,shape = F) if(input$shownam) pca.facto.plot1<-pca.facto.plot1 +geom_text_repel(aes(label=rownames(pca.facto$ind$coord)), label = rownames(pca.facto$ind$coord)) #plot PCA eigenvalues // 2vs3 pca.facto.plot2<-fviz_pca_ind(pca.facto,axes = c(2, 3),mean.point=input$show.mean.points,pointsize=input$plot.point.size,pointshape=19, label="none",ellipse.type = input$ellipses.method,ellipse.alpha=input$ellipses.alpha,addEllipses = input$ellipses,ellipse.level=input$ellipses.level,habillage = as.factor(as.character(meta.in[,meta.select])))+ scale_color_manual(values = c(used.col))+ theme_classic(base_size = input$theme.cex)+ labs(title="PCA: PC 2vs3",subtitle="individuals coordinates",color="group")+ guides(color=F,fill=F,shape = F) pca.facto.plot2.leg<-fviz_pca_ind(pca.facto,axes = c(2, 3),pointsize=input$plot.point.size,pointshape=19, label="none",ellipse.type = input$ellipses.method,ellipse.alpha=input$ellipses.alpha,addEllipses = input$ellipses,ellipse.level=input$ellipses.level,habillage = as.factor(as.character(meta.in[,meta.select])))+ scale_color_manual(values = c(used.col))+ theme_classic(base_size = input$theme.cex)+ labs(title="PCA: PC 1vs2",subtitle="individuals coordinates",color="group") if(input$shownam) pca.facto.plot2<-pca.facto.plot2 +geom_text_repel(aes(label=rownames(pca.facto$ind$coord)), label = rownames(pca.facto$ind$coord)) #extract legend legend <- g_legend(pca.facto.plot2.leg) contri<-get_pca_ind(pca.facto)$contrib[,1:5] #contri<-contri[order(rowMeans(contri),decreasing=T),] corrplot.contrib.ind<-ggcorrplot(t(contri),method="circle", colors = rev(c("orangered", "steelblue", "grey")), legend.title = "contribution",leg.lim=c(min(contri),max(contri)))+ theme_classic(base_size = input$theme.cex)+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5,hjust = 1))+ labs(title="contribution plot of individuals",y="",x="") # Increment the progress bar, and update the detail text. incProgress(8/8, detail = paste("output generation ...")) # return all object as a list list( plotly3d.facto.plot = plotly3d.facto.plot, pca.facto.plot = pca.facto.plot, pca.facto = pca.facto, pca.interpret = pca.interpret, pca.facto.plot1 = pca.facto.plot1, pca.facto.plot2 = pca.facto.plot2, legend = legend, pca.facto.scree.var = pca.facto.scree.var, boxplot.of.data = boxplot.of.data, correlation.plot = correlation.plot, facto.contr.id.1 = facto.contr.id.1, facto.contr.id.2 = facto.contr.id.2, facto.contr.sample.1 = facto.contr.sample.1, facto.contr.sample.2 = facto.contr.sample.2, facto.contr.ID.biplot = facto.contr.ID.biplot, den.out.plot = den.out.plot, corrplot.contrib.ind = corrplot.contrib.ind, meta.seletion.elements.min = min(table(meta.in[,meta.select]),na.rm=T), raw.dim = raw.dim, pca.dim = pca.dim ) }) }) #meta reactive meta<-reactive({meta.in <- data.frame(data.meta()) return(colnames(meta.in))}) #selection ui input for coloring output$meta.sele <- renderUI({ selectInput(inputId = "meta.sele", label = "Choose category for coloring:", choices = as.list(meta()[-1]),selected = "media.phase") }) #HCPC analysis hcpc<-reactive({ withProgress(message = 'Process HCPC:', value = 0, { incProgress(1/1, detail = paste("HCPC calculation...")) # Compute HCPC with automatic cutting of clusters pca.facto.hcpc <- HCPC(pca()$pca.facto, graph = FALSE,nb.clust=-1,metric = input$metrics,method = input$linkage) return(pca.facto.hcpc) }) }) #Plot output output$facto.plot.3d<-renderPlotly({pca()$plotly3d.facto.plot}) output$facto.contr.biplot<-renderPlot({pca()$facto.contr.ID.biplot}) output$facto.plot.2d<-renderPlot({grid.arrange(pca()$pca.facto.plot,pca()$pca.facto.plot1,pca()$pca.facto.plot2 ,pca()$legend,ncol=2)}) output$facto.plot.2d.legend<-renderPlot({grid.draw(pca()$legend)}) output$facto.scree<-renderPlot({pca()$pca.facto.scree.var}) output$boxplot.data<-renderPlot({pca()$boxplot.of.data}) output$den.out<-renderPlot({par(mar=c(15,5,5,5)) plot(pca()$den.out.plot,main = paste("clustering (hclust - ",input$metrics,"/",input$linkage,"/ N = ",input$num.cluster,")"),cex.main=2)}) output$corr.plot<-renderPlot({pca()$correlation.plot}) output$corrplot.var<-renderPlot({pca()$corrplot.contrib.ind}) output$facto.contr.id<-renderPlot({multiplot(pca()$facto.contr.id.1,pca()$facto.contr.id.2,cols=2)}) output$facto.contr.sample<-renderPlot({multiplot(pca()$facto.contr.sample.1,pca()$facto.contr.sample.2,cols=2)}) #value boxes output$raw.data.count<-renderValueBox({ valueBox( pca()$raw.dim[1],color="light-blue", "raw N of variables", icon=icon("table") ) }) output$pca.data.count<-renderValueBox({ valueBox( pca()$pca.dim[1],color = "black", "N of variables used for PCA", icon=icon("area-chart") ) }) output$removed.variables<-renderValueBox({ valueBox( pca()$raw.dim[1]-pca()$pca.dim[1],color = "orange", "removed variables due to missing values", icon=icon("trash-o") ) }) output$individual.count<-renderValueBox({ valueBox( pca()$raw.dim[2],color = "light-blue", "N of individuals", icon=icon("table") ) }) ###### render tables ####### output$table.pca.interpret.dim1 <- renderDataTable({ dat <- data.frame(pca()$pca.interpret$Dim.1) colnames(dat)<-c("correlation","p-value") dat[,1]<-round(dat[,1],digits = 3) dat[,2]<-format.pval(dat[,2]) datatable(dat) }) output$table.pca.interpret.dim2 <- renderDataTable({ dat <- data.frame(pca()$pca.interpret$Dim.2) colnames(dat)<-c("correlation","p-value") dat[,1]<-round(dat[,1],digits = 3) dat[,2]<-format.pval(dat[,2]) datatable(dat) }) output$table.pca.interpret.dim3 <- renderDataTable({ dat <- data.frame(pca()$pca.interpret$Dim.3) colnames(dat)<-c("correlation","p-value") dat[,1]<-round(dat[,1],digits = 3) dat[,2]<-format.pval(dat[,2]) datatable(dat) }) ###### HCPC ####### # HCPC + tree + 2d + tree + barplot output$facto.plot.hcpc.3d<-renderPlot({ plot(hcpc(), choice = "3D.map",title="factor map of individuals colored by cluster + tree",clust.col=general.colors) }) output$facto.plot.hcpc.2d<-renderPlot({ plot(hcpc(), choice = "map",title="factor map of individuals colored by cluster",clust.col=general.colors) }) output$facto.plot.hcpc.tree<-renderPlot({ plot(hcpc(), choice = "tree",title="tree plot",clust.col=general.colors) }) output$facto.plot.hcpc.bar<-renderPlot({ plot(hcpc(), choice = "bar",title="bar plot of of inertia gains",clust.col=general.colors) }) ###### generate outputs for download ####### output$pca.interpret.dim1<-downloadHandler( filename = function() { paste(gsub(".txt","", input$file1),"_variables_most_characteristic_for_1st-Dim.txt",sep='') }, content = function(file) { dat <- data.frame(pca()$pca.interpret$Dim.1); dat <- cbind(rownames(dat),dat); colnames(dat)[1]<-"variables"; write.table(dat, file, row.names=FALSE, quote=FALSE,sep="\t") } ) output$pca.interpret.dim2<-downloadHandler( filename = function() { paste(gsub(".txt","", input$file1),"_variables_most_characteristic_for_2nd-Dim.txt",sep='') }, content = function(file) { dat <- data.frame(pca()$pca.interpret$Dim.2); dat <- cbind(rownames(dat),dat); colnames(dat)[1]<-"variables"; write.table(dat, file, row.names=FALSE, quote=FALSE,sep="\t") } ) output$pca.interpret.dim3<-downloadHandler( filename = function() { paste(gsub(".txt","", input$file1),"_variables_most_characteristic_for_3rd-Dim.txt",sep='') }, content = function(file) { dat <- data.frame(pca()$pca.interpret$Dim.3); dat <- cbind(rownames(dat),dat); colnames(dat)[1]<-"variables"; write.table(dat, file, row.names=FALSE, quote=FALSE,sep="\t") } ) output$file1.data.frame<-downloadHandler( filename = function() { paste("example_data_frame.txt", sep='') }, content = function(file) { dat <- data.frame(example); write.table(dat, file, row.names=FALSE, quote=FALSE,sep="\t") } ) output$file2.data.frame<-downloadHandler( filename = function() { paste("example_meta_data.txt", sep='') }, content = function(file) { dat <- data.frame(example.meta); write.table(dat, file, row.names=FALSE, quote=FALSE,sep="\t") } ) output$plots2D_PCA <- downloadHandler( filename = function() { paste(gsub(".txt","", input$file1),"_2D_plots_PCA_analysis.pdf",sep='') }, content = function(file) { pdf(file,width = 20,height = 20) grid.arrange(pca()$pca.facto.plot,pca()$pca.facto.plot1,pca()$pca.facto.plot2 ,pca()$legend,ncol=2) dev.off() } ) output$plots2D_PCA_legend <- downloadHandler( filename = function() { paste(gsub(".txt","", input$file1),"_2D_plots_legend_PCA_analysis.pdf",sep='') }, content = function(file) { pdf(file) grid.draw(pca()$legend) dev.off() } ) output$plot_PCA_scree <- downloadHandler( filename = function() { paste(gsub(".txt","", input$file1),"_Scree_plot_PCA_analysis.pdf",sep='') }, content = function(file) { pdf(file) print( pca()$pca.facto.scree.var ) dev.off() } ) output$plot_PCA_contrib <- downloadHandler( filename = function() { paste(gsub(".txt","", input$file1),"_contributions_barplot_PCA_analysis.pdf",sep='') }, content = function(file) { pdf(file,width = 20,height = 7) print( multiplot(pca()$facto.contr.id.1,pca()$facto.contr.id.2,cols=2) ) print( multiplot(pca()$facto.contr.sample.1,pca()$facto.contr.sample.2,cols=2) ) dev.off() } ) output$plot_PCA_contrib_biplot <- downloadHandler( filename = function() { paste(gsub(".txt","", input$file1),"_contributions_biplot_PCA_analysis.pdf",sep='') }, content = function(file) { pdf(file,width = 10,height = 10) print( pca()$facto.contr.ID.biplot ) dev.off() } ) output$plot_dendro <- downloadHandler( filename = function() { paste(gsub(".txt","", input$file1),input$metrtics,"_",input$linkage,"_clusterN_",input$num.cluster,"_dendrogram_cluster_analysis.pdf",sep='') }, content = function(file) { pdf(file,width = 20,height = 13) par(mar=c(15,5,5,5)) print(plot(pca()$den.out.plot,main = paste("clustering (hclust - ",input$metrics,"/",input$linkage,"/ N = ",input$num.cluster,")"),cex.main=2) ) dev.off() } ) output$correlationplot <- downloadHandler( filename = function() { paste(gsub(".txt","", input$file1),"_correlation_plot_analysis.pdf",sep='') }, content = function(file) { pdf(file,width = 20,height = 20) print( pca()$correlation.plot ) dev.off() } ) output$boxplo <- downloadHandler( filename = function() { paste(gsub(".txt","", input$file1),"_boxplot_analysis.pdf",sep='') }, content = function(file) { pdf(file,width = 15,height = 6) print( pca()$boxplot.of.data ) dev.off() } ) #plotly out put very low res #output$downloadplotly <- downloadHandler( # filename = function() { paste(gsub(".txt","", input$file1),"_3D-plot_PCA_analysis.png",sep='') }, # content = function(file) { # plotly_IMAGE(pca()$plotly3d.facto.plot, format = "png",width = 1000,height = 1000,, out_file = file) # } # ) #session info output output$sessioninfo <- renderUI({ if(!is.null(input$packages)) sapply(input$packages, function(x) eval(parse(text=paste0("library(",x,")")))) includeRmd("SessionInfo.Rmd") }) output$helper.text.method<-renderUI({ paste(c( paste("The principle component analysis was performed in R (",R.Version()$version.string,") using the factomineR package (version:",packageVersion("FactoMineR"),").",sep=""), if(input$missval==T){paste("Missing values were replaced by 0.")}else{paste("Missing values were removed.")}, if(input$scaling==F){paste("The data centering was done by subtracting the column means (omitting NAs) of the data from their corresponding columns.") }else{ paste("The data centering was done by subtracting the column means (omitting NAs) of the data from their corresponding columns. To unify variances scaling of data was done by dividing the (centered) columns of the data by their standard deviations.")}, if(input$ellipses==T){paste("Ellipses around the individuals were drawn by using", input$ellipses.level,"size of the concentration ellipse in normal probability.")}, paste("The Hierarchical Clustering on Principle Components (HCPC) is performing an agglomerative hierarchical clustering on results from a factor analysis like PCA."), paste("(metric: ",input$metrics,"; linkage: ",input$linkage,")",sep=""), paste("The suggest cutting of the tree into cluster was done by building the sum of the within-cluster inertia that are calculated for each partition and was used for the calculation of the suggested partition, which is the one with the higher relative loss of inertia (i(clusters n+1)/i(cluster n)) (automatic cluster cutting inside the HCPC function; option: nb.clust = -1).") ),collapse = " ") }) }) <file_sep>/helper_functions/hcpc_plot_edited.R hcpc.plot<-function (x, axes = c(1, 2), choice = "3D.map", rect = TRUE, draw.tree = TRUE, ind.names = TRUE, t.level = "all", title = NULL, new.plot = FALSE, max.plot = 15, tree.barplot = TRUE, centers.plot = FALSE,clust.col=NULL,names.cex=1,pos.lab=1,points.cex=10,legend=TRUE, ...) { f.draw.tree = function(X, merge, height, dimens, t.level, ind.names, axes, xlim = NULL, vec = NULL, scale.y = NULL, xlab = NULL, ylab = NULL, y.ticklabs = NULL, ...) { ax1 = axes[1] ax2 = axes[2] names.ind = row.names(X) X$clust = as.numeric(X$clust) nb.clust = max(X$clust) if (class(t.level) == "character") { if (t.level == "centers") t.level = nb.clust if (t.level == "all") t.level = nrow(merge) + 1 } leg = NULL if (dimens == 2) { main = NULL } if (dimens == 3) { if ((new.plot) & !nzchar(Sys.getenv("RSTUDIO_USER_IDENTITY"))) dev.new() if (vec) { X[, ax1] = res$data.clust[, 1] x = X[, ax1] X[, ax2] = seq(min(x)/1000, max(x)/1000, length.out = length(x)) } else { if (ncol(X) == 2) { X = X[, c(1, 1, 2)] x = X[, 1] X[, 2] = seq(min(x)/1000, max(x)/1000, length.out = length(x)) } else x = X[, ax1] } y = X[, ax2] z = rep(0, nrow(X)) X$clust = as.factor(as.numeric(X$clust)) cluster.color<-X$clust cluster.color<-unlist(sapply(cluster.color,function(x) clust.col[as.numeric(x)])) levs = levels(X$clust) cluster.color.levs<-levs cluster.color.levs<-unlist(sapply(cluster.color.levs,function(x) clust.col[as.numeric(x)])) if (!vec) { if (is.null(xlab)) xlab = paste("Dim ", ax1, " (", round(res$call$t$res$eig[ax1, 2], digits = 2), "%)", sep = "") if (is.null(ylab)) ylab = paste("Dim ", ax2, " (", round(res$call$t$res$eig[ax2, 2], digits = 2), "%)", sep = "") } else { y.ticklabs = rep(" ", 2) ylab = " " xlab = " " } scale.y = ((max(y) - min(y))/(max(x) - min(x))) s = scatterplot3d::scatterplot3d(x, y, z, zlim = c(0, max(height)), xlab = xlab, ylab = ylab, zlab = "height", cex.axis=1, box = FALSE, color = if(length(clust.col)==0){X$clust}else{cluster.color}, pch = 20, scale.y = scale.y, y.ticklabs = y.ticklabs, ...) for (i in 1:nb.clust) leg = c(leg, paste("cluster", levs[i], " ", sep = " ")) if(legend==T){ legend("topleft", leg, text.col = if(length(clust.col)==0){as.numeric(levels(X$clust))}else{cluster.color.levs}, cex = 0.8)} if (ind.names) { for (i in 1:nrow(X)) text(s$xyz.convert(x[i], y[i], 0), cex = names.cex, names.ind[i], col = as.vector(if(length(clust.col)==0){X$clust}else{cluster.color})[i], pos = pos.lab) } } aa = matrix(ncol = 4, nrow = nrow(merge)) for (i in 1:nrow(merge)) { if (merge[i, 1] < 0) { x1 = X[-merge[i, 1], ax1] y1 = X[-merge[i, 1], ax2] h1 = 0 w1 = 1 } else { x1 = aa[merge[i, 1], 1] y1 = aa[merge[i, 1], 2] w1 = aa[merge[i, 1], 4] h1 = aa[merge[i, 1], 3] } if (merge[i, 2] < 0) { x2 = X[-merge[i, 2], ax1] y2 = X[-merge[i, 2], ax2] h2 = 0 w2 = 1 } else { x2 = aa[merge[i, 2], 1] y2 = aa[merge[i, 2], 2] w2 = aa[merge[i, 2], 4] h2 = aa[merge[i, 2], 3] } aa[i, 1] = (w1 * x1 + w2 * x2)/(w1 + w2) aa[i, 2] = (w1 * y1 + w2 * y2)/(w1 + w2) if (i <= nrow(merge) - t.level + 1) height[i] = 0 aa[i, 3] = height[i] aa[i, 4] = w1 + w2 if (i > (nrow(merge) - t.level + 1)) { if (dimens == 3) s$points3d(rbind(c(x1, y1, h1), c(x1, y1, height[i]), c(x2, y2, height[i]), c(x2, y2, h2)), lty = 1, type = "o", pch = "") if (dimens == 2) lines(c(x1, x2), c(y1, y2), lwd = (height[i]/max(height)) * 3) } } if (dimens == 3) { list.centers = by(X[, -ncol(X), drop = FALSE], X$clust, colMeans) centers = matrix(unlist(list.centers), ncol = ncol(X) - 1, byrow = TRUE) for (l in 1:nb.clust) { if (centers.plot) { s$points3d(centers[l, ax1], centers[l, ax2], 0, col = levs[l], type = "o", pch = ".", cex = points.cex) text(s$xyz.convert(centers[l, ax1], centers[l, ax2], 0), cex = names.cex, leg[l], col = cluster.color.levs[l], pos = 1) } } } } res = x X = res$call$X max = res$call$max min = res$call$min max.plot = max(res$call$max, 15) nb.clust = length(levels(X$clust)) levs = levels(X$clust) if (choice == "tree") { if ((new.plot) & !nzchar(Sys.getenv("RSTUDIO_USER_IDENTITY"))) dev.new() if (is.null(title)) title = "Hierarchical clustering" if (tree.barplot) { def.par <- par(no.readonly = TRUE) par(mar = c(0.5, 2, 0.75, 0)) lay = matrix(ncol = 5, nrow = 5, c(2, 4, 4, 4, 4, 2, 4, 4, 4, 4, 2, 4, 4, 4, 4, 2, 4, 4, 4, 4, 1, 3, 3, 3, 3)) layout(lay, respect = TRUE) vec = res$call$t$inert.gain[1:max.plot] barplot(height = vec, col = c(rep("black", nb.clust - 1), rep("grey", max(max, 15) - nb.clust + 1)), space = 0.9) plot(x = 1, xlab = "", ylab = "", main = "", col = "white", axes = FALSE) text(1, 1, title, cex = 2) plot(x = 1, xlab = "", ylab = "", main = "", col = "white", axes = FALSE) legend("top", "inertia gain ", box.lty = NULL, cex = 1) } plot(res$call$t$tree, hang = -1, xlab = "", sub = "", ...) if (rect) { y = (res$call$t$tree$height[length(res$call$t$tree$height) - nb.clust + 2] + res$call$t$tree$height[length(res$call$t$tree$height) - nb.clust + 1])/2 ordColo <- unique(res$call$X$clust[res$call$t$tree$order]) if(length(clust.col)==0){ordColo <- unique(res$call$X$clust[res$call$t$tree$order])}else{ordColo <-unlist(sapply(unique(res$call$X$clust[res$call$t$tree$order]),function(x) clust.col[as.numeric(x)]))} rect = rect.hclust(res$call$t$tree, h = y, border = ordColo) } } if (choice == "3D.map") { if (is.null(title)) title = "Hierarchical clustering on the factor map" f.draw.tree(t.level = t.level, X, merge = res$call$t$tree$merge, height = res$call$t$tree$height, dimens = 3, ind.names = ind.names, axes = axes, vec = res$call$vec, ...) title(title) } if (choice == "bar") { if ((new.plot) & !nzchar(Sys.getenv("RSTUDIO_USER_IDENTITY"))) dev.new() vec = res$call$t$inert.gain[1:max.plot] names.arg = NULL if (is.null(title)) title = "Inter-cluster inertia gains" for (i in 1:(max.plot)) names.arg = c(names.arg, paste(i, "-", i + 1, sep = "")) barplot(vec, names.arg = names.arg, col = c(rep(1, nb.clust - 1), rep(18, length(vec) - nb.clust + 1)), main = title, xlab = "level of cutting", ylab = "Inertia") } if (choice == "map") { if (!res$call$vec) { if (is.null(title)) title = "Factor map" Y = X[, -ncol(X)] leg.map = NULL for (p in 1:nrow(X)) leg.map[p] = paste("cluster", X$clust[p], " ", sep = " ") Y = cbind.data.frame(Y, as.factor(leg.map)) res2 = PCA(Y, quali.sup = ncol(Y), scale.unit = FALSE, row.w = res$call$t$res$call$row.w, ncp = Inf, graph = FALSE) res2$eig <- res$call$t$res$eig if (ind.names) plot.PCA(res2, title = title, habillage = ncol(Y), cex = 0.8, axes = axes, new.plot = new.plot, palette = palette(clust.col), ...) else plot.PCA(res2, title = title, habillage = ncol(Y), cex = 0.8, axes = axes, label = "none", new.plot = new.plot, palette = palette(clust.col), ...) if (draw.tree) f.draw.tree(X, merge = res$call$t$tree$merge, height = res$call$t$tree$height, dimens = 2, t.level = t.level, axes = axes, ...) } } if (choice == "tree" & tree.barplot) par(def.par) invisible() } <file_sep>/README.md MVA (multivariant analysis) shiny app ===================================== This is an shiny app for doing a multivariant analysis of your data. The app is mainly based on the FactoMineR package (<a href="http://factominer.free.fr" class="uri">http://factominer.free.fr</a>) - PCA (Principle component analysis) - HCPC (hierachical clustering on principle component) - Clustering R packages used and should be installed ======================================= - shiny - shinyBS - shinyjs - colourpicker - dplyr - ggplot2 - gridExtra - metricsgraphics - RColorBrewer - scales - ggrepel - data.table - FactoMineR - factoextra - plotly - ggcorrplot - dendextend - DT - knitr - markdown - bit64 Screenshot/movie of the app =========================== ![](www/MVA_demo.gif) Feel free to try the app. <file_sep>/helper_functions/ggcorrplot_edited.R #' Visualization of a correlation matrix using ggplot2 #' @import ggplot2 #' @description \itemize{ \item ggcorrplot(): A graphical display of a #' correlation matrix using ggplot2. \item cor_pmat(): Compute a correlation #' matrix p-values. } #' @param corr the correlation matrix to visualize #' @param method character, the visualization method of correlation matrix to be #' used. Allowed values are "square" (default), "circle". #' @param type character, "full" (default), "lower" or "upper" display. #' @param ggtheme function, ggplot2 theme name. Default value is theme_minimal. #' Allowed values are the official ggplot2 themes including theme_gray, #' theme_bw, theme_minimal, theme_classic, theme_void, .... #' @param title character, title of the graph. #' @param show.legend logical, if TRUE the legend is displayed. #' @param legend.title a character string for the legend title. lower #' triangular, upper triangular or full matrix. #' @param show.diag logical, whether display the correlation coefficients on the #' principal diagonal. #' @param colors a vector of 3 colors for low, mid and high correlation values. #' @param outline.color the outline color of square or circle. Default value is #' "gray". #' @param hc.order logical value. If TRUE, correlation matrix will be hc.ordered #' using hclust function. #' @param hc.method the agglomeration method to be used in hclust (see ?hclust). #' @param lab logical value. If TRUE, add correlation coefficient on the plot. #' @param lab_col,lab_size size and color to be used for the correlation #' coefficient labels. used when lab = TRUE. #' @param p.mat matrix of p-value. If NULL, arguments sig.level, insig, pch, #' pch.col, pch.cex is invalid. #' @param sig.level significant level, if the p-value in p-mat is bigger than #' sig.level, then the corresponding correlation coefficient is regarded as #' insignificant. #' @param insig character, specialized insignificant correlation coefficients, #' "pch" (default), "blank". If "blank", wipe away the corresponding glyphs; #' if "pch", add characters (see pch for details) on corresponding glyphs. #' @param pch add character on the glyphs of insignificant correlation #' coefficients (only valid when insig is "pch"). Default value is 4. #' @param pch.col,pch.cex the color and the cex (size) of pch (only valid when #' insig is "pch"). #' @param tl.cex,tl.col,tl.srt the size, the color and the string rotation of #' text label (variable names). #' @return #' \itemize{ #' \item ggcorrplot(): Returns a ggplot2 #' \item cor_pmat(): Returns a matrix containing the p-values of correlations #' } #' @examples #' # Compute a correlation matrix #' data(mtcars) #' corr <- round(cor(mtcars), 1) #' corr #' #' # Compute a matrix of correlation p-values #' p.mat <- cor_pmat(mtcars) #' p.mat #' #' # Visualize the correlation matrix #' # -------------------------------- #' # method = "square" or "circle" #' ggcorrplot(corr) #' ggcorrplot(corr, method = "circle") #' #' # Reordering the correlation matrix #' # -------------------------------- #' # using hierarchical clustering #' ggcorrplot(corr, hc.order = TRUE, outline.col = "white") #' #' # Types of correlogram layout #' # -------------------------------- #' # Get the lower triangle #' ggcorrplot(corr, hc.order = TRUE, type = "lower", #' outline.col = "white") #' # Get the upeper triangle #' ggcorrplot(corr, hc.order = TRUE, type = "upper", #' outline.col = "white") #' #' # Change colors and theme #' # -------------------------------- #' # Argument colors #' ggcorrplot(corr, hc.order = TRUE, type = "lower", #' outline.col = "white", #' ggtheme = ggplot2::theme_gray, #' colors = c("#6D9EC1", "white", "#E46726")) #' #' # Add correlation coefficients #' # -------------------------------- #' # argument lab = TRUE #' ggcorrplot(corr, hc.order = TRUE, type = "lower", #' lab = TRUE) #' #' # Add correlation significance level #' # -------------------------------- #' # Argument p.mat #' # Barring the no significant coefficient #' ggcorrplot(corr, hc.order = TRUE, #' type = "lower", p.mat = p.mat) #' # Leave blank on no significant coefficient #' ggcorrplot(corr, p.mat = p.mat, hc.order = TRUE, #' type = "lower", insig = "blank") #' #' @name ggcorrplot #' @rdname ggcorrplot #' @export ggcorrplot <- function (corr, method = c("square", "circle"), type = c("full", "lower", "upper"),leg.lim=c(-1,1), ggtheme = ggplot2::theme_minimal, title = "", show.legend = TRUE, legend.title = "Corr", show.diag = FALSE, colors = c("blue", "white", "red"), outline.color = "gray", hc.order = FALSE, hc.method = "complete", lab = FALSE, lab_col = "black", lab_size = 4, p.mat = NULL, sig.level = 0.05, insig = c("pch", "blank"), pch = 4, pch.col = "black", pch.cex = 5, tl.cex = 12, tl.col = "black", tl.srt = 45) { type <- match.arg(type) method <- match.arg(method) insig <- match.arg(insig) if (!is.matrix(corr) & !is.data.frame(corr)) stop("Need a matrix or data frame!") corr <- as.matrix(corr) if (hc.order) { ord <- .hc_cormat_order(corr) corr <- corr[ord, ord] if (!is.null(p.mat)) p.mat <- p.mat[ord, ord] } # Get lower or upper triangle if (type == "lower") { corr <- .get_lower_tri(corr, show.diag) p.mat <- .get_lower_tri(p.mat, show.diag) } else if (type == "upper") { corr <- .get_upper_tri(corr, show.diag) p.mat <- .get_upper_tri(p.mat, show.diag) } # Melt corr and pmat corr <- reshape2::melt(corr, na.rm = TRUE) colnames(corr) <- c("Var1", "Var2", "value") corr$pvalue <- rep(NA, nrow(corr)) corr$signif <- rep(NA, nrow(corr)) if (!is.null(p.mat)) { p.mat <- reshape2::melt(p.mat, na.rm = TRUE) corr$coef <- corr$value corr$pvalue <- p.mat$value corr$signif <- as.numeric(p.mat$value <= sig.level) p.mat <- subset(p.mat, p.mat$value > sig.level) if (insig == "blank") corr$value <- corr$value * corr$signif } corr$abs_corr <- abs(corr$value) * 10 # Heatmap p <- ggplot2::ggplot(corr, ggplot2::aes_string("Var1", "Var2", fill = "value")) if (method == "square") p <- p + ggplot2::geom_tile(color = outline.color) else if (method == "circle") { p <- p + ggplot2::geom_point(color = outline.color, shape = 21, ggplot2::aes_string(size = "abs_corr")) + ggplot2::scale_size(range = c(4, 10)) + ggplot2::guides(size = FALSE) } p <- p + ggplot2::scale_fill_gradient2( low = colors[1], high = colors[3], mid = colors[2], midpoint = mean(leg.lim), limit = leg.lim, space = "Lab", name = legend.title ) + ggtheme() + ggplot2::theme( axis.text.x = ggplot2::element_text( angle = tl.srt, vjust = 1, size = tl.cex, hjust = 1 ), axis.text.y = ggplot2::element_text(size = tl.cex) ) + ggplot2::coord_fixed() label <- round(corr[, "value"], 2) if (lab) p <- p + ggplot2::geom_text( ggplot2::aes_string("Var1", "Var2"), label = label, color = lab_col, size = lab_size ) if (!is.null(p.mat) & insig == "pch") { p <- p + ggplot2::geom_point( data = p.mat, ggplot2::aes_string("Var1", "Var2"), shape = pch, size = pch.cex, color = pch.col ) } # Add titles if (title != "") p <- p + ggplot2::ggtitle(title) if (!show.legend) p <- p + ggplot2::theme(legend.position = "none") p <- p + .no_panel() p } #' Compute the matrix of correlation p-values #' #' @param x numeric matrix or data frame #' @param ... other arguments to be passed to the function cor.test. #' @rdname ggcorrplot #' @export cor_pmat <- function(x, ...) { mat <- as.matrix(x) n <- ncol(mat) p.mat <- matrix(NA, n, n) diag(p.mat) <- 0 for (i in 1:(n - 1)) { for (j in (i + 1):n) { tmp <- stats::cor.test(mat[, i], mat[, j], ...) p.mat[i, j] <- p.mat[j, i] <- tmp$p.value } } colnames(p.mat) <- rownames(p.mat) <- colnames(mat) p.mat } #+++++++++++++++++++++++ # Helper Functions #+++++++++++++++++++++++ # Get lower triangle of the correlation matrix .get_lower_tri <- function(cormat, show.diag = FALSE) { if (is.null(cormat)) return(cormat) cormat[upper.tri(cormat)] <- NA if (!show.diag) diag(cormat) <- NA return(cormat) } # Get upper triangle of the correlation matrix .get_upper_tri <- function(cormat, show.diag = FALSE) { if (is.null(cormat)) return(cormat) cormat[lower.tri(cormat)] <- NA if (!show.diag) diag(cormat) <- NA return(cormat) } # hc.order correlation matrix .hc_cormat_order <- function(cormat, hc.method = "complete") { dd <- stats::as.dist((1 - cormat) / 2) hc <- stats::hclust(dd, method = hc.method) hc$order } .no_panel <- function() { ggplot2::theme( axis.title.x = ggplot2::element_blank(), axis.title.y = ggplot2::element_blank() ) }
696a97ad2c6ef65b84f760519721633964d77d74
[ "Markdown", "R" ]
6
R
stemicha/MVA_shiny_app
40a78ae3754368f632889d100ad356dbb667c108
472c4d4f5c756a3c39405fbd01bb976bd772b0bf
refs/heads/master
<file_sep>#include"../header/CreatingTimeableLibrary.h" #include<stdlib.h> extern char *s_getCurrentTime(); extern char *s_pretreatLocalDir(); char sMotherFile[100]; int const iMax=20; int const iTrick=19; void *v_creatFile(char *sCreateLocation,char *sFileName); void v_addTasks(char *sFileName,FILE *FFile); int i_addTaskArray(strTimeableTask *sTTTA,int iTL); void v_arrangeTasks(strTimeableTask *sTTTasksArray,int iEleNum); void v_creatTimeable(){ char sCurrentTime[100], sLocationFile[100], sFileName[4]; strcpy(sCurrentTime,""); strcpy(sLocationFile,""); strcpy(sFileName,""); /*------------------------------------------------------------------------------------------------------------------------------------------*/ strcpy(sLocationFile,s_pretreatLocalDir()); for( strcpy(sCurrentTime,s_getCurrentTime()); strcmp(sCurrentTime,"")!=0; strcpy(sCurrentTime,&sCurrentTime[3]) ){ strncpy(sFileName,sCurrentTime,3); v_creatFile(sLocationFile,&sFileName[0]); } /*------------------------------------------------------------------------------------------------------------------------------------------*/ system("@cls||clear"); printf("CREATED Timeable FOR TODAY"); getch(); return; } void *v_creatFile(char *sCreateLocation,char *sFileName){ FILE *FFile; char sResult[100]; strcpy(sResult,""); sFileName[3]='\0'; /*----------------------------------------------------------------------------------------------------------------------------*/ strcpy(sResult,sCreateLocation); strcat(sResult,"/"); if( sFileName[0]!='D' ) strncat(sResult,sFileName,3); else strcat(sResult,"D"); if( !opendir(sResult) ) mkdir(sResult); strcpy(sCreateLocation,sResult); strncat(sResult,"/",1); strncat(sResult,sFileName,3); strncat(sResult,".txt",4); if( !fopen(sResult,"r") ){ FFile=fopen(sResult,"w"); v_addTasks(sFileName, FFile); fclose(FFile); } strcpy(sMotherFile,sResult); /*------------------------------------------------------------------------------------------------------------------------------*/ return; } void v_addTasks(char *sFileName,FILE *FFile){ strTimeableTask sTTTasks[iMax], sTTSaveTask; int i, iCout, iTaskAmount; float fTimePoint; char s_Number[3]; FILE *FMotherFile=fopen(sMotherFile,"r"); //------------------------------------------------------------------------------------------------// if(sFileName[0]!='D'){ switch(sFileName[0]){ case 'Q': iTaskAmount=3; break; case 'W': iTaskAmount=6; break; default: iTaskAmount=4; break; } if(sFileName[0]=='Y'){ printf("Enter %i Jobs that you need to do in %s:\n",iTaskAmount,sFileName); iCout=i_addTaskArray(sTTTasks,iTaskAmount); for(i=0;i<iCout;i++) fwrite(&sTTTasks[i], sizeof(sTTTasks[i]), 1, FFile); } else{ FMotherFile=fopen(sMotherFile,"r"); for(i=0;i<sFileName[2]-'0';i++) fread(&sTTSaveTask,sizeof(sTTSaveTask),1,FMotherFile); fclose(FMotherFile); printf("Enter %i Jobs that links with %s in %s:\n",iTaskAmount,sTTSaveTask.sNameTask,sFileName); iCout=i_addTaskArray(sTTTasks,iTaskAmount); for(i=0;i<iCout;i++) fwrite(&sTTTasks[i], sizeof(sTTTasks[i]), 1, FFile); } }else{ FMotherFile=fopen(sMotherFile,"r"); for(fread(&sTTSaveTask,sizeof(sTTSaveTask),1,FMotherFile);1;fread(&sTTSaveTask,sizeof(sTTSaveTask),1,FMotherFile)){ sprintf(&s_Number[0],"%i",(int)sTTSaveTask.sTTTimeScope.fEnd); if( strlen(&s_Number[0])==1 ){ s_Number[1]=s_Number[0]; s_Number[0]='0'; } if( strncmp(&sFileName[1],&s_Number[0],2)==0 ) break; } fclose(FMotherFile); printf("Enter Tasks that links with %s in %s:\n",sTTSaveTask.sNameTask,sFileName); printf("Enter Tasks that you have to do in %s:\n",sFileName); iCout=i_addTaskArray(sTTTasks,iMax); printf("Enter Tasks that you need to do in %s:\n",sFileName); iCout=i_addTaskArray(sTTTasks,iTrick); for(i=0;i<iCout;i++) fwrite(&sTTTasks[i], sizeof(sTTTasks[i]), 1, FFile); } //-------------------------------------------------------------------------------// return; } int i_addTaskArray(strTimeableTask *sTTTA,int iTL){ int iReturnValue=0, iRemain=0, i, j; float fTimeScope=0; /*-----------------------------------------------------------------------------------------------------------------------------------------*/ if(iTL!=iTrick) for(i=0;i<iTL;i++){ printf("Let's enter Task that You are going to Do:\n"); fflush(stdin); if( strcmp(gets(sTTTA[i].sNameTask),"")==0 ) break; iReturnValue++; if(iTL==iMax){ printf("Enter Start time point: "); fflush(stdin); scanf("%f",&sTTTA[i].sTTTimeScope.fBegin); } else sTTTA[i].sTTTimeScope.fBegin=0; printf("Enter End time point: "); fflush(stdin); scanf("%f",&sTTTA[i].sTTTimeScope.fEnd); v_arrangeTasks(sTTTA,iReturnValue); } else{ iReturnValue=0; for(i=0;strcmp(sTTTA[i].sNameTask,"")!=0;i++) iReturnValue++; for(i=iReturnValue;i<iMax;i++){ if(i_addTaskArray(&sTTTA[i],1)==0) break; fTimeScope=sTTTA[i].sTTTimeScope.fEnd-sTTTA[i].sTTTimeScope.fBegin; for(j=1;j<iReturnValue;j++) if( fTimeScope<=(sTTTA[j].sTTTimeScope.fBegin-sTTTA[j-1].sTTTimeScope.fEnd) ){ sTTTA[i].sTTTimeScope.fBegin=sTTTA[j-1].sTTTimeScope.fEnd; sTTTA[i].sTTTimeScope.fEnd=sTTTA[i].sTTTimeScope.fBegin+fTimeScope; iReturnValue++; v_arrangeTasks(sTTTA,iReturnValue); break; } if( j==iReturnValue ){ iRemain++; i--; sTTTA[iMax-iRemain]=sTTTA[i+1]; } } printf("Tasks aren't Done:\n"); for(i=0;i<iRemain;i++) printf("\t%s\n",sTTTA[iMax-i-1].sNameTask); getch(); } /*-----------------------------------------------------------------------------------------------------------------------------------------*/ return iReturnValue; } void v_arrangeTasks(strTimeableTask *sTTTasksArray,int iEleNum){ int i,j; strTimeableTask sTTSave; /*------------------------------------------------------------------------------------------------------------------------------------------*/ for(i=0;i<iEleNum;i++) for(j=i;j<iEleNum;j++) if(sTTTasksArray[i].sTTTimeScope.fEnd>sTTTasksArray[j].sTTTimeScope.fEnd){ sTTSave=sTTTasksArray[i]; sTTTasksArray[i]=sTTTasksArray[j]; sTTTasksArray[j]=sTTSave; } /*--------------------------------------------------------------------------------------------------------------------------------------------*/ return; } <file_sep>#include"../header/CreatingTimeableLibrary.h" extern v_observeTimeable(int i_Controller); int i_showMainMenu(){ system("@cls||clear"); printf("1. Creating Timeable\n"); printf("2. Observing Timeable\n"); printf("0. Exit\n"); return (getch() - '0'); } <file_sep>#include"../header/CreatingTimeableLibrary.h" extern char *s_pretreatLocalDir(); char *s_getRequestFile(); char *s_showControllerMenu(DIR *Dp_Folder); void v_showTimeable(char *sRF); void v_observeTimeable() { char s_RF[100], s_SaveDay[15]; /*------------------------------------------------------------------------------------------------------------------------------------------*/ system("@cls||clear"); strcpy(s_RF,s_getRequestFile()); v_showTimeable(s_RF); /*------------------------------------------------------------------------------------------------------------------------------------------*/ getch(); return; } char *s_getRequestFile(){ DIR *Dp_Folder; char s_SaveString[10]; static char cp_Path[100]; /*------------------------------------------------------------------------------------------------------------------------------------------*/ for(strcpy(cp_Path,s_pretreatLocalDir());1;){ printf("%s\n",cp_Path); Dp_Folder=opendir(cp_Path); if( Dp_Folder==NULL ) break; strncat(&cp_Path[0],"/",1); strcpy(&s_SaveString[0],s_showControllerMenu(Dp_Folder)); if( s_SaveString[3]!='.' ) if(s_SaveString[0]!='D') strncat(cp_Path,s_SaveString,3); else strncat(cp_Path,s_SaveString,1); else strncat(cp_Path,s_SaveString,7); } /*------------------------------------------------------------------------------------------------------------------------------------------*/ return &cp_Path[0]; } char *s_showControllerMenu(DIR *Dp_Folder){ int i_Controller=0; struct dirent *sDp_Ent; char s_Dir[10][10]; /*-----------------------------------------------------------------------------------------------------------------------------------------*/ system("@cls||clear"); for(sDp_Ent=readdir(Dp_Folder);sDp_Ent!=NULL;sDp_Ent=readdir(Dp_Folder)){ if( sDp_Ent->d_name[0]!='.' ){ i_Controller=i_Controller+1; printf("%i. %s\n",i_Controller,sDp_Ent->d_name); strncpy(&s_Dir[i_Controller-1][0],sDp_Ent->d_name,(int)strlen(sDp_Ent->d_name)); } } printf("Enter Number that you Want to Observe: "); i_Controller=getch() - '0'; /*-----------------------------------------------------------------------------------------------------------------------------------------*/ return &s_Dir[i_Controller-1][0]; } void v_showTimeable(char *cRF){ strTimeableTask sTTTask; FILE *FRequestFile=fopen(cRF,"r"); system("@cls||clear"); if(FRequestFile==NULL){ printf("Timeable of Day isn't created. Let's creat!"); return; } /*------------------------------------------------------------------------------------------------------------------------------------------*/ printf("%s\t\t%s\t\t%s\n","Name of Task","Begin Time Point","End Time Point"); for(fread(&sTTTask,sizeof(sTTTask),1,FRequestFile);!feof(FRequestFile);fread(&sTTTask,sizeof(sTTTask),1,FRequestFile)) printf("%s\t\t%.2f\t\t%.2f\n",sTTTask.sNameTask,sTTTask.sTTTimeScope.fBegin,sTTTask.sTTTimeScope.fEnd); /*------------------------------------------------------------------------------------------------------------------------------------------*/ fclose(FRequestFile); return; } <file_sep># Timeable - project with C language - comprise of creatTimeable and observeTimeable main functions - comprise of SupportFunctions are getCurrentTime and pretreatLocalDir - project funtions are linked by extern variables and functions # creatTimeable - creatTimeable for Day, Week, Month, Quater and Year - return TimeableFile - compose of addTasks # addTasks - assign number of Tasks that you need to do - write Tasks on File - comprise addTaskArray # addTaskArray - creatTimeable in SpeacialStructure - comprise of arrangeTasks # arrangeTaskArray - arrange CreatedTaskArray # observeTimeable - show Timeable that you requested - compose of getRequestFile and showTimeable # getRequestFile - show folders and files that you can access - return Path of File is sRF - comprise of showControllerMenu # showConrollerMenu - display SelectionScreen - get Char from Keyboard - return File or Folder Name # showTimeable - get sRF - showTimeable # getCurrentTime - getRealTime - return SpecialString include information of RealTime # pretreatLocalDir - creatDataFolder include Files of Timeable - return DataFolderPath <file_sep>#include"header/CreatingTimeableLibrary.h" char *s_getCurrentTime(); char *s_pretreatLocalDir(); extern int i_showMainMenu(); extern void v_creatTimeable(); extern void v_observeTimeable(); int main(){ char cController=s_getCurrentTime()[11]; int iController; if(cController=='5') printf("Sorry, App don't run in this day!"); else for(iController=i_showMainMenu();(iController>0)&&(iController<5);iController=i_showMainMenu()) switch(iController){ case 1: v_creatTimeable(); break; case 2: v_observeTimeable(1); break; default: break; } return 0; } char *s_getCurrentTime(){ time_t rawtime; static char cSaveDate[100]; char cSource[25], cDestination[25]; { strcpy(cSaveDate,""); time (&rawtime); strcpy(cSource,ctime(&rawtime)); //"Fri Dec 22 15:26:14 2017" cSource[24]='\0'; strcpy(cDestination,""); } { strcat(cSaveDate,"Y"); strcpy(cDestination,&cSource[strlen(cSource)-2]); strcat(cSaveDate,cDestination); } { strcat(cSaveDate,"Q"); strncpy(cDestination,&cSource[4],3); cDestination[3]='\0'; if( strcmp(cDestination,"Jan")==0 || strcmp(cDestination,"Feb")==0 || strcmp(cDestination,"Mar")==0 ) strcat(cSaveDate,"01"); else if( strcmp(cDestination,"Apr")==0 || strcmp(cDestination,"May")==0 || strcmp(cDestination,"Jun")==0 ) strcat(cSaveDate,"02"); else if( strcmp(cDestination,"Jul")==0 || strcmp(cDestination,"Aug")==0 || strcmp(cDestination,"Sep")==0 ) strcat(cSaveDate,"03"); else if( strcmp(cDestination,"Oct")==0 || strcmp(cDestination,"Nov")==0 || strcmp(cDestination,"Dec")==0 ) strcat(cSaveDate,"04"); } { strcat(cSaveDate,"M"); if(strcmp(cDestination,"Jan")==0) strcpy(cDestination,"01"); if(strcmp(cDestination,"Feb")==0) strcpy(cDestination,"02"); if(strcmp(cDestination,"Mar")==0) strcpy(cDestination,"03"); if(strcmp(cDestination,"Apr")==0) strcpy(cDestination,"04"); if(strcmp(cDestination,"May")==0) strcpy(cDestination,"05"); if(strcmp(cDestination,"Jun")==0) strcpy(cDestination,"06"); if(strcmp(cDestination,"Jul")==0) strcpy(cDestination,"07"); if(strcmp(cDestination,"Aug")==0) strcpy(cDestination,"08"); if(strcmp(cDestination,"Sep")==0) strcpy(cDestination,"09"); if(strcmp(cDestination,"Oct")==0) strcpy(cDestination,"10"); if(strcmp(cDestination,"Nov")==0) strcpy(cDestination,"11"); if(strcmp(cDestination,"Dec")==0) strcpy(cDestination,"12"); strcat(cSaveDate,cDestination); } { int i; strcat(cSaveDate,"W"); strncpy(cDestination,&cSource[strlen(cSource)-16],2); i=atoi(cDestination); switch(i/7){ case 0: strcat(cSaveDate,"01"); break; case 1: if(i%7==0) strcat(cSaveDate,"01"); else strcat(cSaveDate,"02"); break; case 2: if(i%7==0) strcat(cSaveDate,"02"); else strcat(cSaveDate,"03"); break; case 3: if(i%7==0) strcat(cSaveDate,"03"); else strcat(cSaveDate,"04"); break; case 4: if(i%7==0) strcat(cSaveDate,"04"); else strcat(cSaveDate,"05"); break; default: break; } } { strcat(cSaveDate,"D"); strcat(cSaveDate,cDestination); } return &cSaveDate[0]; } char *s_pretreatLocalDir(){ int i; static char sLocalDir[100]; /*-----------------------------------------------------------------------------------------------------------------------------------------*/ getcwd(sLocalDir, sizeof(sLocalDir)); for(i=0;i<strlen(sLocalDir);i++) if(sLocalDir[i]=='\\') sLocalDir[i]='/'; strncat(&sLocalDir[0],"/Data",5); if( opendir(&sLocalDir[0])==NULL ) mkdir(sLocalDir); /*-----------------------------------------------------------------------------------------------------------------------------------------*/ return sLocalDir; } <file_sep>#ifndef CreatingTimeableLibrary_H_ #define CreatingTimeableLibrary_H_ #include<stdio.h> #include<time.h> #include<string.h> #include<stdlib.h> #include<dirent.h> #include<conio.h> typedef struct{ float fBegin; float fEnd; }strTimeTimeable; typedef struct{ char sNameTask[100]; float fTimeScope; } strTask; typedef struct{ char sNameTask[100]; strTimeTimeable sTTTimeScope; } strTimeableTask; #endif // CreatingTimeableLibrary_H_
9e229811c4871eb08cb09332d2cbd5f49a754645
[ "Markdown", "C" ]
6
C
DustStuart159/Timeable
57050fa2cd2c2ba72e1043e4b577a87f4d783e3f
897bbcde5357609afe2189a7a9c00ec27aeaa60d
refs/heads/main
<file_sep>import { Injectable } from '@angular/core'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import { FormGroup, Validators } from '@angular/forms'; import { FormBuilder } from '@angular/forms'; @Injectable({ providedIn: 'root' }) export class UserService { contactForm; readonly baseURL='https://localhost:5001/api'; constructor(public formBuilder: FormBuilder,public http:HttpClient) { this.contactForm = this.formBuilder.group({ UserName : ['',Validators.required], Email : ['',Validators.email], FullName : ['',Validators.required], Passwords:this.formBuilder.group({ //find a soln. for this //if more than one validators,use inside an array Password : ['',[Validators.required,Validators.minLength(5)]], ConfirmPassword : ['',Validators.required] },{validator:this.comparePasswords} ) }); } comparePasswords(fb: FormGroup) { let confirmPswrdCtrl = fb.get('ConfirmPassword'); //passwordMismatch //confirmPswrdCtrl.errors={passwordMismatch:true} if (confirmPswrdCtrl?.errors == null || 'passwordMismatch' in confirmPswrdCtrl?.errors) { if (fb.get('Password')?.value != confirmPswrdCtrl?.value) confirmPswrdCtrl?.setErrors({ passwordMismatch: true }); else confirmPswrdCtrl?.setErrors(null); } } // circular dependency error --> https://angular.io/errors/NG0200 //Reactive form Design using formgroup and form control with validators //https://www.tektutorialshub.com/angular/angular-formbuilder-in-reactive-forms/ register() { var body= { UserName : this.contactForm.value.UserName, Email : this.contactForm.value.Email, FullName : this.contactForm.value.FullName, Password : <PASSWORD>.value.<PASSWORD> }; return this.http.post(this.baseURL+'/ApplicationUser/Register',body); } login(formData:any) { return this.http.post(this.baseURL+'/ApplicationUser/Login',formData); } getUserProfile() { var tokenHeader=new HttpHeaders({'Authorization':'Bearer '+localStorage.getItem('token')}); return this.http.get(this.baseURL+'/UserProfile' ,{headers:tokenHeader} ); } get UserName() { return this.contactForm.get('UserName'); } get Email() { return this.contactForm.get('Email'); } get FullName() { return this.contactForm.get('FullName'); } get Password() { return this.contactForm.get('Passwords.Password'); } get ConfirmPassword() { return this.contactForm.get('Passwords.ConfirmPassword'); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { UserService } from 'src/app/shared/user.service'; import { ToastrService } from 'ngx-toastr'; @Component({ selector: 'app-registration', templateUrl: './registration.component.html', styleUrls: ['./registration.component.css'] }) export class RegistrationComponent implements OnInit { constructor(public service:UserService,public toastr: ToastrService) {} onSubmit() { this.service.register() .subscribe( //we can define the form output here /* res => { this.service.contactForm.reset(); //Toastr is a JavaScript library which is used to create a notification popup. this.toastr.success('Submitted Successfully','User Registeration'); //pm.=?msg,title }, err => { console.log(err); } */ (res: any) => { if (res.Succeeded) { this.service.contactForm.reset(); this.toastr.success('New user created!', 'Registration successful.'); } else { res.Errors.forEach((element: { code: any; description: string | undefined; }) => { switch (element.code) { case 'DuplicateUserName': this.toastr.error('Username is already taken','Registration failed.'); break; default: //this.toastr.error(element.description,'Registration failed.'); this.toastr.error('Username is already taken','Registration failed.'); break; } }); } }, err => { console.log(err); } ); } ngOnInit(): void { } } /* For successful registration: ex: { "UserName": "selva", "FullName": "Selvakumar", "Email": "<EMAIL>", "Password":"<PASSWORD>" } { "Succeeded": true, "Errors": [] } For unsuccesful registration:(if user uses an username which is already present) { "Succeeded": false, "Errors": [ { "Code": "DuplicateUserName", "Description": "User name 'skselva21' is already taken." } ] } */
d8b2097f4c4a609a9b07cc155e2b3b3e03ee10c8
[ "TypeScript" ]
2
TypeScript
Selvakumar2000/AuthenticaltionApp---Client
2a75f3d5ae0c1417888c873c7fd8cf8ef4858f8f
59d2acace5c4a8e954147bc390868d2efe863d85
refs/heads/master
<repo_name>hikaru4/mabao<file_sep>/mabao.js var hackerList, options = { valueNames: [ 'classname', 'district', 'weekday', 'time', 'age', 'description', 'id', ], item: '<li class="item list-item">' + '<div class="classname"></div>' + '<div class="container">' + '<div class="location">' + '<div class="city">台南市</div>' + '<div class="district"></div>' + '</div>' + '<div class="datetime">' + '<div class="weekday"></div>' + '<div class="time"></div>' + '</div>' + '<div class="age"></div>' + '</div>' + '<div class="description"></div>' + '<div class="id"></div>' + '</li>' }; let url = 'mabao_list.json'; fetch(url) .then(res => res.json()) .then((out) => { // 濾掉空的課程 values = out.filter(function(item){ return item.classname !== ''; }) hackerList = new List('hacker-list', options, values); }) .catch(err => console.error(err)); $(document).on('click', '.list-item', function(e) { var id = e.currentTarget.lastElementChild.textContent, item = hackerList.get("id", id)[0]._values; for (var k in item){ if (item.hasOwnProperty(k)) { elem = document.getElementById('info-' + k) if (elem){ elem.innerHTML = item[k]; } } } document.getElementById('mask').style.display = 'block'; document.getElementById('item-info').style.display = 'block'; }); $(document).on('click', '#mask', function(e) { document.getElementById('mask').style.display = 'none'; document.getElementById('item-info').style.display = 'none'; });
a4a640b5a908002d677427274e732d1c59371465
[ "JavaScript" ]
1
JavaScript
hikaru4/mabao
235a0484ac443248effca87f278c0e607eeb4f1f
996fd2010a1126c3a014ffdf14d20afdb461fb79
refs/heads/master
<file_sep>function showStatus(msg,delay){ $('.status').hide().html(msg).fadeIn(200).delay(delay).fadeOut(300); } function ajax(config){ this.method = config.method || 'GET'; this.payload = config.payload || null; var xhr = new XMLHttpRequest(); xhr.open(this.method, config.url, true); xhr.upload.addEventListener("progress", function(e){ config.progress(e); }); xhr.addEventListener("load", function(){ config.success(xhr); }); xhr.addEventListener("error", config.error); xhr.send(this.payload); } $(function(){ $(document).on('change', '.uploadPic', function(e){ var ext = this.value.match(/\.([^\.]+)$/)[1].toLowerCase(); var permit = ['jpg','gif','png']; if(permit.indexOf(ext)>-1){ showStatus('Ready to Upload !', 600); } else { showStatus('Your Chosen File Is Not Permitted !! Please pick JPG, GIF or PNG files only !', 4000); $(this).val(''); } }) }) function renderUI (imageList) { for(var i = 0; i < imageList.length; i++) { console.log('... In renderImages function ...'); console.log('tags = ',imageList[i].tags); var str = '<li>'; str += '<div class="overlay">'; str += '<div class="voteCtrl">'; str += '<a href="#" data-photoid="' + imageList[i].id + '" class="like">'; str += '<img src="../images/like.png" alt="Click Here to Like !">'; str += '<h4>' + imageList[i].likes + '</h4>'; str += '</a>'; str += '</div>'; str += '</div>'; str += '<div class="imageHolder">'; str += '<img src="https://s3.amazonaws.com/la-image-tagger-chakrar27/' + imageList[i].filename + '" alt="">'; str += '</div>'; str += '<div class="tags">'; str += '<ul>'; for (var j = 0; j < imageList[i].tags.length; j++) { console.log('tag value =', imageList[i].tags[j]); if (imageList[i].tags[j] !== '') { str += '<li>'; str += '<a href="#" data-tagname="' + imageList[i].tags[j] + '" class="showTag">'; str += '<h4>' + imageList[i].tags[j] + '</h4>'; str += '</a>'; str += '</li>'; } } str += '</ul>'; str += '</div>'; str += '</li>'; $('.gallery ul').append(str); } } <file_sep>var ImageModel = require("../models/recordmodel"); module.exports = function (express, app, formidable, fs, os, gm, knoxClient, couchbase, aws, S3_BUCKET, io) { var router = express.Router(); //console.log("Router Object", router); router.get('/', function (req, res) { console.log("Rendering file upload page"); //console.log("couchbase object = ", couchbase); res.render('upload.html', {host:app.get('host')}); }) var Socket; io.on('connection', function(socket) { Socket = socket; }) var labels; router.post('/upload', function(req, res, next) { function generateFilename(filename){ var ext_regex = /(?:\.([^.]+))?$/; var ext = ext_regex.exec(filename)[1]; var date = new Date().getTime(); var charBank = "abcdefghijklmnopqrstuvwxyz"; var fstring = ''; for(var i = 0; i < 15; i++){ fstring += charBank[parseInt(Math.random()*26)]; } return (fstring += date + '.' + ext); } var tmpFile, nFile, fname; var newForm = formidable.IncomingForm(); newForm.keepExtensions = true; newForm.parse(req, function(err, fields, files) { tmpFile = files.upload.path; fname = generateFilename(files.upload.name); nFile = os.tmpDir() + '/' + fname; res.writeHead(200, {'Content-type':'text/plain'}); res.end(); }) newForm.on('end', function() { fs.rename(tmpFile, nFile, function() { // resize the image and upload to s3 gm(nFile).resize(300).write(nFile, function () { // put in s3 fs.readFile(nFile, function(err, buf) { var req = knoxClient.put(fname, { 'Content-Length': buf.length, 'Content-Type': 'image/jpeg' }) req.on('response', function (res) { // body... if (res.statusCode == 200) { // store in couchbase photogallery bucket console.log("The image is uploaded to s3 successfully !"); // call aws rekognition to detect labels var labelsReko = (function(filename, res) { var rekognition = new aws.Rekognition(); var params = { Image: { S3Object: { Bucket: S3_BUCKET, Name: filename } }, MaxLabels: 5, MinConfidence: 50 }; //console.log("Calling Rekognition with = ", params); rekognition.detectLabels(params, function(err, data) { if (err) { console.log("Error in REKO" + err); } else { // successful response data = JSON.stringify(data); var json = JSON.parse(data); labels = json.Labels; //console.log("data labels", labels); var tags = []; for (var entry in labels) { //console.log("Name: = ", labels[entry].Name); var item = labels[entry].Name; tags.push(item); } var payload = { filename: filename, likes: 0, tags: tags } //console.log("Saving payload", payload); ImageModel.save(payload, function(error, result) { if(error) { return res.status(400).send(error); } //res.send(result); }); // notify front-end that image is saved Socket.emit('status', {'msg':'Image Saved Successfully!', 'delay':3000}); Socket.emit('doUpdate', {}); // Delete file fs.unlink(nFile, function() { //console.log('Local file deleted !'); }) } }) })(fname, res); } }) req.end(buf); }) }); }) }) }) router.get('/getimages', function(req, res, next){ ImageModel.getAll(function(err, result){ res.send(JSON.stringify(result)); }) }) router.get('/like/:id', function(req, res, next){ ImageModel.getByDocumentId(req.params.id, function(err, result){ //console.log('result before incrementing likes = ', result); var jsonFromDB = JSON.stringify(result); var docFromDBArr = JSON.parse(jsonFromDB); var docFromDB = docFromDBArr[0]; console.log("docFromDB ", docFromDB); var likes = docFromDB.likes; console.log("likes before ", likes); // increment the like by 1 likes = likes + 1; console.log("likes after ", likes); docFromDB.likes = likes; console.log("Saving payload with ", JSON.stringify(docFromDB)); ImageModel.save(docFromDB, function(error, result) { if(error) { return res.status(400).send(error); } res.status(200).send({likes:docFromDB.likes}); }) }) }) router.get('/getimages/:tagname', function(req, res, next){ console.log('inside getimages by tagname'); ImageModel.getImagesByTag(req.params.tagname, function(err, result){ console.log('result = ', JSON.stringify(result)); var jsonFromDB = JSON.stringify(result); //var docFromDBArr = JSON.parse(jsonFromDB); //var docFromDB = docFromDBArr[0]; res.send(JSON.stringify(result)); }) }) app.use('/', router); }<file_sep>## ImageTagger This application lets users upload images of their choice and uses amazon AI to detect labels of the image. ### Tech Stack Used - Node js and Express - AWS S3 to store images - The app uses [Amazon Rekognition API](https://aws.amazon.com/rekognition/) to detect tags on an uploaded image ### TODO-s - Add features with more aws rekognition API-s - Integrate Couchbase node sdk to build the tagging feature of photos - Dockerize the app - Deploy on aws ec2 (possibly switch ec2 with lambda later) - Plug into a CI/CD pipeline with Jenkins
c755c8e7f3112019d3f62a4ee762fa5f2e08dde0
[ "JavaScript", "Markdown" ]
3
JavaScript
ratchakr/ImageTagger
cac1b85abf5d93792d4c3b5613002abaa85a3c43
7559a37eeb48640e76e708e32487487d1de7c9ef
refs/heads/main
<repo_name>talaugust/s2-simplify<file_sep>/ui/src/logging.ts import axios from "axios"; import { LogEntryCreatePayload } from "./api/types"; type LogLevel = "error" | "warning" | "info" | "debug"; /** * Logger that logs events to remote server endpoint. * As the singleton for this logger will be initialized when the script is imported, it is * some component of the app is responsible for injecting the username once that * information becomes available by using 'setUsername'. */ class RemoteLogger { setUsername(username: string) { this._username = username; } setContext(context?: any) { this._context = context; } /** * To debounce an event (i.e., only log it every so often), set 'debounce' to a number of * milliseconds to wait before logging an event of that type. Once the wait period expires, * the last event of that type will be logged. * * If 'data' is a function, this function will be called to produce the data to be logged. * This may be useful when using 'debounce' to ensure that data that is expensive to compute * will only be computed when the debounce waiting time has passed. */ async log( level: LogLevel, eventType?: string, data?: any, debounce?: number ) { if (eventType !== undefined && debounce !== undefined && debounce > 0) { /* * If debouncing is requested, only log the data once the interval has passed. * When that interval passes, log only the most recent data for the event. */ if (this._debouncedData[eventType] === undefined) { setTimeout(() => { const d = this._debouncedData[eventType]; this._debouncedData[eventType] = undefined; this._log(level, eventType, d); }, debounce); } this._debouncedData[eventType] = data; return; } this._log(level, eventType, data); } async _log(level: LogLevel, eventType?: string, data?: any) { const logData = this._prepareData(data); console.log(eventType, logData); return axios .post("/api/log", { username: this._username, level, event_type: eventType, data: logData, } as LogEntryCreatePayload) .catch((e) => { if (!this._receivedPostError) { console.error( "Failed to log event with data [", level, eventType, data, "] to remote server. Check that you are connected to the internet. " + "This messge will not be shown again." ); this._receivedPostError = true; } }); } private _prepareData(data: any) { const context = this._context || {}; context.clientTimestamp = new Date().getTime(); let dataWithContext = { _context: context }; if (data) { const d = typeof data === "function" ? data() : data; dataWithContext = { ...dataWithContext, ...d }; } return dataWithContext; } private _username: string | null = null; private _context: any; private _debouncedData: { [eventType: string]: any } = {}; private _receivedPostError: boolean = false; } const remoteLoggerInstance = new RemoteLogger(); export default remoteLoggerInstance; /** * Get remote logger singleton. */ export function getRemoteLogger() { return remoteLoggerInstance; } <file_sep>/ui/src/types/labella.d.ts declare module "labella" { export class Node { constructor(idealPos: number, width: Number, data?: any); idealPos: number; currentPos: number; width: number; data?: any; getLayerIndex(): number; } export class Renderer { constructor(options: RenderOptions); generatePath(node: Node): string; getWaypoints(node: Node): [number, number][]; layout(nodes: Node[]): Node[]; } interface RenderOptions { layerGap?: number; nodeHeight?: number; direction?: "up" | "down" | "left" | "right"; } export class Force { constructor(options?: ForceOptions); nodes(nodes: Node[]): Force; options(options: ForceOptions); compute(): Force; } interface ForceOptions { minPos?: number | null; maxPos?: number | null; lineSpacing?: number; nodeSpacing?: number; algorithm?: "overlap" | "simple" | "none"; density?: number; stubWidth?: number; } } <file_sep>/ui/src/utils/state.ts /** * See the comments about the design choice in storing data in relational stores in 'types/state.ts' */ import { RelationalStore } from "../state"; export function createRelationalStore<T>(): RelationalStore<T> { return { all: [], byId: {} }; } /** * Convert an array into a relational store with the specified key as an ID. */ export function createRelationalStoreFromArray<T>( array: any[], idKey: string ): RelationalStore<T> { const allIds = array .map((item) => item[idKey]) .filter((key) => typeof key === "string"); const itemsById = array .filter((item) => allIds.indexOf(item[idKey]) !== -1) .reduce((byId, item) => { byId[item[idKey]] = item; return byId; }, {}); return { all: allIds, byId: itemsById, }; } /** * Add an item to a relational store. Returns a new relational store with a new 'byId' object * and a new 'all' array. Assumes the item keyed by 'id' is not yet in the store. */ export function add<T>( store: RelationalStore<T>, id: string, item: T ): RelationalStore<T> { return { ...store, byId: { ...store.byId, [id]: item, }, all: [...store.all.concat(id)], }; } /** * Update an item in the relational store. Returns a new relational store with a new 'byId' * object, but the same 'all' array. Assumes the item keyed by 'id' is already in the store. */ export function update<T>( store: RelationalStore<T>, id: string, item: T ): RelationalStore<T> { return { ...store, byId: { ...store.byId, [id]: item, }, }; } /** * Deletes an item from the relational store. Returns a new store with a new 'byId' object, * and a new 'all' array. Assumes the item keyed by 'id' is already in the store. */ export function del<T>( store: RelationalStore<T>, id: string ): RelationalStore<T> { const all = store.all.filter((itemId) => itemId !== id); const byId = { ...store.byId }; delete byId[id]; return { all, byId }; } <file_sep>/ui/src/api/types.ts /** * The design of the data types for responses roughly follow the conventions of JSON:API: * See the specification at https://jsonapi.org/format/. * * In addition, field names are written using underscores, not camelCase. * * These data structures roughly resemble the schemas in the database. A definition of the schemas along * with documentation should reside in 'data-processing/common/models.py' or thereabouts. * * This file was intended to be copied and pasted into other projects that need to know the types * returned from the API. Because of this, all types are exported, so that when this file is copied * into other projects, all of the types are available to the client code. */ export interface Paginated<T> { rows: T[]; offset: number; size: number; total: number; } export interface PaperIdWithEntityCounts { s2_id: string; arxiv_id?: string; version: number; symbol_count: number; citation_count: number; sentence_count: number; term_count: number; equation_count: number; entity_count: number; } /** * Format of returned papers loosely follows that for the S2 API: * https://api.semanticscholar.org/ */ export interface Paper { s2Id: string; abstract: string; authors: Author[]; title: string; url: string; venue: string; year: number | null; influentialCitationCount?: number; citationVelocity?: number; inboundCitations: number; // numCitedBy in S2 API outboundCitations: number; // numCiting in S2 API } export interface PaperWithEntityCounts extends PaperIdWithEntityCounts { abstract?: string; authors?: Author[]; title?: string; url?: string; venue?: string; year?: number | null; influentialCitationCount?: number; citationVelocity?: number; } export interface PaperIdInfo { s2_id: string; arxiv_id?: string; version: number; } export interface PaperWithIdInfo extends PaperIdInfo { abstract?: string; authors?: Author[]; title?: string; url?: string; venue?: string; year?: number | null; influentialCitationCount?: number; citationVelocity?: number; } export interface Author { id: string; name: string; url: string; } export interface EntityGetResponse { data?: Entity[]; } /** * Use type guards (e.g., 'isSymbol') to distinguish between types of entities. */ export type Entity = GenericEntity | Symbol | Term | Citation | Sentence | Experience | PaperQuestion | AnswerSentence | SectionHeader; /** * All entity specifications should extend BaseEntity. To make specific relationship properties * known to TypeScript, define a relationships type (e.g., see 'SymbolRelationships'). Otherwise, * set the relationships property type to '{}'. */ export interface BaseEntity { /** * Entity IDs are guaranteed to be unique, both within and across papers. */ id: string; type: string; attributes: BaseEntityAttributes; relationships: Relationships; } /** * All entities must define at least these attributes. */ export interface BaseEntityAttributes { version?: number; source: string; bounding_boxes: BoundingBox[]; /** * Additional data for this entity in the form of arbitrary strings. For instance, there could be * a tag for a term entity conveying whether it is a 'key term'. As another example, and entity * can be tagged as having irregular bounding boxes, so it should be hidden. * * For stable attributes of entities, they should be added as new named properties on the entity * attributes types, instead of being stored as a tag. This is because it helps type-checking and * code completion be more precise. That said, adding tags to store entity attributes is suitable * when prototyping new features, as it allows the data to be changed in the database without * continually updating these types. */ tags: string[]; } /** * While it is not described with types here, Relationships must be key-value pairs, where the values * are either 'Relationship' or a list of 'Relationship's. */ export interface Relationships {} export interface Relationship { type: string; id: string | null; } export function isRelationship(o: any): o is Relationship { return typeof o.type === "string" && typeof o.id === "string"; } /** * An entity where no information is known about its type, and hence attributes and * relationships specific to that entity type are not available. This type is defined to provide * *some* small amount of type checking for unknown and new types of entities. */ export interface GenericEntity extends BaseEntity { attributes: BaseEntityAttributes & GenericAttributes; relationships: GenericRelationships; } /** * When posting an entity, an 'id' need not be included, nor a version tag. */ export interface EntityCreatePayload { data: EntityCreateData; } export interface EntityCreateData { type: string; attributes: Omit<BaseEntityAttributes, "version" | "tags"> & GenericAttributes; relationships: GenericRelationships; } /** * When patching an entity, the 'type' and 'id' are required. The 'source' attribute is also * required. All modified entities and specified bounding boxes and data will be assigned the * the provided 'source' value. */ export interface EntityUpdatePayload { data: EntityUpdateData; } export interface EntityUpdateData { id: string; type: string; attributes: Pick<GenericAttributes, "source"> & Partial<GenericAttributes>; relationships?: Partial<GenericRelationships>; } /** * In general, attributes can have values of type 'string | number | string[] | null | undefined'. Because * we're doing a type intersection with BaseEntityAttributes above to define the attributes for * a BasicEntity (where some properties are of other types like BoundingBox[]), 'any' is used as * the type of value here, even though the types of GenericAttributes values should be restricted. */ export interface GenericAttributes { [key: string]: any; } export type GenericRelationships = { [key: string]: Relationship | Relationship[]; }; /** * 'Symbol' is an example of how to define a new entity type with custom attributes * and relationships. Note that a full custom entity definition includes: * * an 'attributes' type * * a 'relationships' type * * a type-guard (i.e., an 'is<Entity>' function) */ export interface Symbol extends BaseEntity { type: "symbol"; attributes: SymbolAttributes; relationships: SymbolRelationships; } export interface SymbolAttributes extends BaseEntityAttributes { tex: string | null; type: "identifier" | "function" | "operator"; // TODO: This is null too with the deduped endpoint mathml: string | null; mathml_near_matches: string[]; is_definition: boolean | null; diagram_label: string | null; /** * Nicknames for the symbol extracted from the text, no more than a few words long. */ nicknames: string[]; /** * A description of what a symbol means, in prose (though can contain formulae). May either * describe the concept that the symbol represents (i.e., 'beta is the bias term') or * analytic assertions (i.e., 'beta takes on values between 0 and 1'). */ definitions: string[]; /** * Formulas from the paper that serve as a formal definition of the symbol. */ defining_formulas: string[]; /** * Other passages from the paper that help explain what this symbol means. */ passages: string[]; /** * An extracted TeX snippet that shows the symbol in context. */ snippets: string[]; } export interface SymbolRelationships { equation: Relationship; sentence: Relationship; parent: Relationship; children: Relationship[]; /** * Experimental feature: link to the sentences that contain each type of definition. For each * list of definitions in the symbol attributes (i.e., nicknames, definitions, defining * formulas, etc.), there should be one relationship to a the sentence containing that definition. * Therefore, each of these relationship lists should have the same length as the corresponding * list of definitions in the attributes. */ nickname_sentences: Relationship[]; definition_sentences: Relationship[]; defining_formula_equations: Relationship[]; snippet_sentences: Relationship[]; } /** * Type guards for entities should only have to check the 'type' attribute. */ export function isSymbol(entity: Entity): entity is Symbol { return entity.type === "symbol"; } export interface Term extends BaseEntity { type: "term"; attributes: TermAttributes; relationships: TermRelationships; } export interface TermAttributes extends BaseEntityAttributes { name: string | null; /** * A description of the type of this term (i.e., is it a protologism? A nonce?) */ term_type: string | null; /** * List of prose passages that describe the meaning of the term. */ definitions: string[]; /** * List of passages of TeX. Each item should correspond to the definition at the same index * from 'definitions', assuming the definition was extracted from TeX; otherwise the item * should be set to 'null'. */ definition_texs: string[]; /** * Tag indicating the source of the definition. For example, the tag might indicate that the * definition came from an external glossary, or from a definition extractor. There should be one * source for each definition in 'definitions'. */ sources: string[]; /** * Additional passages that help explain what this term means. */ snippets: string[]; } export interface TermRelationships { sentence: Relationship; definition_sentences: Relationship[]; snippet_sentences: Relationship[]; } export function isTerm(entity: Entity): entity is Term { return entity.type === "term"; } export interface Citation extends BaseEntity { type: "citation"; attributes: CitationAttributes; relationships: {}; } export interface CitationAttributes extends BaseEntityAttributes { paper_id: string | null; } export function isCitation(entity: Entity): entity is Citation { return entity.type === "citation"; } export interface Equation extends BaseEntity { type: "equation"; attributes: EquationAttributes; relationships: {}; } export interface EquationAttributes extends BaseEntityAttributes { tex: string | null; } export function isEquation(entity: Entity): entity is Equation { return entity.type === "equation"; } export interface Sentence extends BaseEntity { type: "sentence"; attributes: SentenceAttributes; relationships: {}; } export interface SentenceAttributes extends BaseEntityAttributes { text: string | null; tex: string | null; tex_start: number | null; tex_end: number | null; } export function isSentence(entity: Entity): entity is Sentence { return entity.type === "sentence"; } /* New types added: Experience & Questions & Sentence Answers & Section Headers */ /* Experiences are overlayed information for specific terms in the document * They include definitions drawn from multiple different sources (urls) */ export interface Experience extends BaseEntity { type: "experience"; attributes: ExperienceAttributes; relationships: {}; } export interface ExperienceAttributes extends BaseEntityAttributes { experience_id: string | null; snippets: string[]; urls: string[]; } export function isExperience(entity: Entity): entity is Experience { return entity.type === "experience"; } /* Questions are overlayed FAQs for a document * Each question can contain multiple places to jump to that answer the question */ export interface PaperQuestion extends BaseEntity { type: "question"; attributes: PaperQuestionAttributes; relationships: PaperQuestionRelationships; } export interface PaperQuestionRelationships { sentence: Relationship; definition_sentences: Relationship[]; snippet_sentences: Relationship[]; } export interface PaperQuestionAttributes extends BaseEntityAttributes { name: string | null; question_text : string; answer_text : string; definitions: string[]; definition_texs: string[]; snippets: string[]; } export function isPaperQuestion(entity: Entity): entity is PaperQuestion { return entity.type === "question"; } /* Sentences answers are answers to paper questions. They work similar to sentences but are highlighted and can be clicked to get a simplified answer */ export interface AnswerSentence extends BaseEntity { type: "answerSentence"; attributes: AnswerSentenceAttributes; relationships: AnswerSentenceRelationships; } export interface AnswerSentenceRelationships { question: Relationship; more_details: Relationship; less_details: Relationship; coaster: Relationship[]; } export interface AnswerSentenceAttributes extends BaseEntityAttributes { text: string | null; simplified_text: string | null; tex: string | null; tex_start: number | null; tex_end: number | null; } export function isAnswerSentence(entity: Entity): entity is AnswerSentence { return entity.type === "answerSentence"; } /* Section headers are simplified explanations of what is going on in a section */ export interface SectionHeader extends BaseEntity { type: "sectionHeader"; attributes: SectionHeaderAttributes; relationships: {}; } export interface SectionHeaderAttributes extends BaseEntityAttributes { summary: string; points: string[]; } export function isSectionHeader(entity: Entity): entity is SectionHeader { return entity.type === "sectionHeader"; } /** * Matches the schema of the data in the 'boundingbox' table in the database. 'left', 'top', * 'width', and 'height' are expressed in ratios to the page width and height, rather than * absolute coordinates. * * For example, a bounding box is expressed as * { * left: .1, * right: .1, * width: .2, * height: .05 * } * * if its absolute position is (50px, 100px), its width is (100px), and its * height is (50px) on a page with dimensions (W = 500px, H = 1000px). * * This representation of coordinates was chosen due to constraints in the design of the data * processing pipeline. More specifically, it's easier to extract ratio coordinates than absolute * coordinates when processing PDFs and PostScript files with Python. */ export interface BoundingBox { source?: string; /** * Page indexes start at 0. */ page: number; left: number; top: number; width: number; height: number; } /** * Data for a logging event. */ export interface LogEntryCreatePayload { username: string | null; level: string; event_type: string | null; data: any; } <file_sep>/ui/src/selectors/term.ts import { Entities } from "../state"; import { isTerm, Term } from "../api/types"; import { orderByPosition } from "./entity"; /** * Get a list of terms that match a set of terms, ordered by position in the document. */ export function matchingTerms(termIds: string[], entities: Entities) { const names = termIds .map((id) => entities.byId[id]) .filter(isTerm) .map((t) => t.attributes.name); const matchingTermIds = entities.all .map((id) => entities.byId[id]) .filter((e) => e !== undefined) .filter(isTerm) .filter((t) => names.indexOf(t.attributes.name) !== -1) .filter((t) => t.attributes.bounding_boxes.length > 0) .map((t) => t.id); return orderByPosition(matchingTermIds, entities); } /** * A summary of term data suitable for logging. This set of properties should * be fast to compute (i.e., mostly of property accesses). */ export function termLogData(term: Term) { return { id: term.id, name: term.attributes.name, numDefinitions: term.attributes.definitions.length, numUsages: term.attributes.snippets.length, pages: term.attributes.bounding_boxes.map((b) => b.page), }; } <file_sep>/ui/src/api/deduped.ts import { BoundingBox, Relationship as LegacyRelationship } from './types'; import { Nullable } from '../types/ui'; /** * Types defined in here are for the entities-deduped endpoint, * and are intentionally less generic. * TODO: Replace existing entity type usages with these */ export interface DedupedEntityResponse { entities: Entity[]; sharedSymbolData: { [dedupedMathml: string]: SharedSymbolData }; } interface EntityBase { id: string; type: string; // type specifically? attributes: AttributesBase; } export type Entity = Citation | Symbol | Term | Equation | Sentence; interface AttributesBase { bounding_boxes: BoundingBox[]; } type Relationship = { id: string } | string; export interface Citation extends EntityBase { type: 'citation'; attributes: CitationAttributes; } interface CitationAttributes extends AttributesBase { paper_id: Nullable<string>; } export interface Symbol extends EntityBase { type: 'symbol'; attributes: SymbolAttributes; relationships: SymbolRelationships; } interface SymbolAttributes extends AttributesBase { tex: Nullable<string>; type: "identifier" | "function" | "operator"; // TODO: This is null too with the deduped endpoint mathml: Nullable<string>; mathml_near_matches: string[]; is_definition: Nullable<boolean>; diagram_label: Nullable<string>; /** * This is the ID to use when getting SharedSymbolData for this entity. */ disambiguated_id: Nullable<string>; /** * Nicknames for the symbol extracted from the text, no more than a few words long. */ nicknames: string[]; /** * Other passages from the paper that help explain what this symbol means. */ passages: string[]; } export interface Term extends EntityBase { type: 'term'; attributes: TermAttributes; relationships: TermRelationships; } interface TermAttributes extends AttributesBase { name: Nullable<string>; /** * A description of the type of this term (i.e., is it a protologism? A nonce?) */ term_type: Nullable<string>; definitions: string[]; definition_texs: string[]; sources: string[]; snippets: string[]; } interface TermRelationships { sentence: Relationship; definition_sentences: Relationship[]; snippet_sentences: Relationship[]; } interface SymbolRelationships { equation: Relationship; sentence: Relationship; parent: Relationship; children: Relationship[]; /** * Experimental feature: link to the sentences that contain each type of definition. For each * list of definitions in the symbol attributes (i.e., nicknames, definitions, defining * formulas, etc.), there should be one relationship to a the sentence containing that definition. * Therefore, each of these relationship lists should have the same length as the corresponding * list of definitions in the attributes. */ nickname_sentences: Relationship[]; } export interface Equation extends EntityBase { type: 'equation'; attributes: EquationAttributes; } interface EquationAttributes extends AttributesBase { tex: Nullable<string>; } export interface Sentence extends EntityBase { type: "sentence"; attributes: SentenceAttributes; } interface SentenceAttributes extends AttributesBase { text: Nullable<string>; tex: Nullable<string>; tex_start: Nullable<number>; tex_end: Nullable<number>; } interface SharedSymbolData { defining_formula_equations: string[]; // entity id defining_formulas: string[]; // tex-bearing formula text definition_sentences: string[]; definition_texs: string[]; definitions: string[]; snippets: string[]; // tex-bearing sentence text snippet_sentences: string[]; // entity id sources: string[]; } /* * Type guards for handling specific types of entities. */ export function isCitation(entity: Entity): entity is Citation { return entity.type === "citation"; } export function isSymbol(entity: Entity): entity is Symbol { return entity.type === "symbol"; } export function isTerm(entity: Entity): entity is Term { return entity.type === "term"; } export function isEquation(entity: Entity): entity is Equation { return entity.type === "equation"; } export function isSentence(entity: Entity): entity is Sentence { return entity.type === "sentence"; } /** * We can express relationships more compactly as a list of IDs, but * exisiting code expects each relationship entry to also define what * entity type it links to, despite relationships always linking * to one type of entity. * @param rel The relationship to process * @param type The entity type to which this relationship links * @returns old-form {id, type} tuple describing the relationship */ export function toLegacyRelationship(rel: Relationship, type: string): LegacyRelationship { if (typeof rel === "string") { return { id: rel, type }; } return { id: rel.id, type }; } <file_sep>/docker-compose.yaml version: '3' services: papersrv: build: ./papersrv volumes: - ./papersrv/paper:/papers/paper ports: - 3002:3002 api: build: ./api volumes: - ./api:/api environment: - PYTHONUNBUFFERED=1 ports: - 8000:8000 ui: build: context: ./ui dockerfile: Dockerfile-dev volumes: - ./ui/src:/ui/src environment: - NODE_ENV=development ports: - 3001:3001 proxy: build: ./proxy ports: - 8080:8080 depends_on: - ui - api - papersrv <file_sep>/proxy/Dockerfile FROM nginx:1.17.0-alpine COPY nginx.conf /etc/nginx/nginx.conf ARG CONF_FILE=local.conf COPY $CONF_FILE /etc/nginx/conf.d/default.conf COPY dist /var/www/skiff/ui/ <file_sep>/ui/src/types/pdfjs-viewer.ts import { PDFDocumentProxy, PDFPageProxy } from "pdfjs-dist/types/display/api"; /** * Declarations for the PDF.js viewer application. These types are not declared as part of * @types/pdfjs-dist, probably because the PDF.js maintainers do not distribute the viewer * application with pdfjs-dist package. * * As we are building on top of Mozilla's viewer application, these typings help us type check * against expectations of the interface to viewer functionality. * * It's possible that these members may become inaccessible in future versions of the pdf.js * package. Take care when updating the 'pdf.js' submodule of this project to check that * all of these typings still accurately describe the interfaces available at runtime when * the application is launched from 'viewer.html'. */ interface PDFPageViewportOptions { viewBox: any; scale: number; rotation: number; offsetX: number; offsetY: number; dontFlip: boolean; } interface PDFPageViewport { width: number; height: number; scale: number; transforms: number[]; clone(options: PDFPageViewportOptions): PDFPageViewport; convertToViewportPoint(x: number, y: number): number[]; // [x, y] convertToViewportRectangle(rect: number[]): number[]; // [x1, y1, x2, y2] convertToPdfPoint(x: number, y: number): number[]; // [x, y] } export interface PDFViewerApplication { initialized: boolean; appConfig: AppConfig; eventBus: EventBus; externalServices: ExternalServices; pdfViewer: PDFViewer; pdfDocument: PDFDocumentProxy; pdfLinkService: PDFLinkService; } export interface AppConfig { toolbar: Toolbar; } export interface Toolbar { viewFind: HTMLDivElement; } export interface EventBus { on: (eventName: string, listener: (...args: any[]) => void) => void; dispatch: (eventName: string, ...args: any[]) => void; } export interface PageRenderedEvent { source: PDFPageView; pageNumber: number; cssTransform: boolean; timestamp: number; } export interface ExternalServices { supportsIntegratedFind: boolean; updateFindControlState: (state: { result: number; matchesCount: MatchInfo; }) => void; updateFindMatchesCount: (matchInfo: MatchInfo) => void; } export interface MatchInfo { current: number; total: number; } /** * States for the pdf.js find controller are defined at: * https://github.com/mozilla/pdf.js/blob/8cfdfb237abc3a20013306eb43dd4cfdb76e4a8e/web/pdf_find_controller.js#L20-L25 */ export enum PdfJsFindControllerState { FOUND = 0, NOT_FOUND = 1, WRAPPED = 2, PENDING = 3, } export interface DocumentLoadedEvent { source: PDFDocumentProxy; } export interface PDFViewer { container: HTMLDivElement; viewer: HTMLDivElement; /** * Scroll the PDF viewer to a location of interest. Example usage: * pdfViewer.scrollPageIntoView({ * pageNumber: PAGE_NUMBER, // page numbers start at 1. * destArray: [ * undefined, * { name: "XYZ" }, * LEFT_X_IN_PDF_COORDINATE_SYSTEM, * TOP_Y_IN_PDF_COORDINATE_SYSTEM, * ], * }); */ scrollPageIntoView: (options: ScrollPageIntoViewOptions) => void; /** * XXX(andrewhead): ideally, this internal function shouldn't be used because we don't know if * pdf.js will maintain it. In practice, it is a very convenient function, as it lets the * caller scroll to a specific element in the viewer without knowing its coordinates. */ _scrollIntoView: (options: ScrollIntoViewOptions) => void; } export interface PDFLinkService { navigateTo: (explicitDest: DestArray) => void; } /** * X and Y coordinates are in the PDF coordinate system, not in the viewport coordinate system. */ interface ScrollPageIntoViewOptions { pageNumber?: number; destArray?: DestArray | null; allowNegativeOffset?: boolean; } /** * First parameter is ignored by 'scrollPageIntoView' and can be 'undefined'. * Second parameter is used to declare the format of the remaining arguments. */ type DestArray = [any | undefined, DestinationType, any?, any?, any?, any?]; interface DestinationType { name: "XYZ" | "Fit" | "FitB" | "FitH" | "FitBH" | "FitV" | "FitBV" | "FitR"; } interface ScrollIntoViewOptions { pageDiv: HTMLElement; pageSpot?: { left: number; top: number }; } export interface PDFPageView { pdfPage: PDFPageProxy; canvas: HTMLCanvasElement; div: HTMLDivElement; scale: number; viewport: PDFPageViewport; } <file_sep>/ui/src/utils/ui.test.ts import { extractArxivId } from './ui'; describe('extractArxivId', () => { it('extracts the ID from an arXiv PDF url', () => { const url = 'https://arxiv.org/pdf/2005.06967v2.pdf'; const output = extractArxivId(url); expect(output).toEqual('2005.06967v2'); }); it('extracts the ID from a math paper arXiv PDF url', () => { const url = 'https://arxiv.org/pdf/math/0008020v2.pdf'; const output = extractArxivId(url); expect(output).toEqual('math/0008020v2'); }); it('ignores nonsense after the .pdf extension as pdf.js does', () => { const url = 'https://arxiv.org/pdf/2005.06967v2.pdf?showAll=true'; const output = extractArxivId(url); expect(output).toEqual('2005.06967v2'); }); it('returns no match if no arxiv URL is given', () => { const url = 'this is not an arxiv url'; const output = extractArxivId(url); expect(output).toEqual(undefined); }); }); <file_sep>/api/requirements.txt certifi==2018.11.29 chardet==3.0.4 Click==7.0 Flask==1.0.2 gevent==1.5.0 greenlet==0.4.15 idna==2.8 itsdangerous==1.1.0 Jinja2==2.11.3 MarkupSafe==1.1.1 python-json-logger==0.1.10 six==1.12.0 urllib3==1.26.5 Werkzeug==0.15.5 <file_sep>/ui/src/utils/feedback.ts import {PaperId} from "../state"; import queryString from "querystring"; export function createFeedbackLink( paperId?: PaperId | undefined, extraContext?: object ) { /* * The URL and field ids below are generated by Google. The identifiers * are opaque to us, which means they could change (say, if we modify * the assocaited form). If this proves to be an issue we'll have to think * through alternative feedback mechanisms. */ const baseUrl = "https://forms.gle/BvGeHYzUA1pHzcAK6"; const params = { "entry.331961046": JSON.stringify( Object.assign({}, extraContext || {}, { paperId }) ), }; return `${baseUrl}?${queryString.stringify(params)}`; } export function openFeedbackWindow(url: string) { window.open(url, "scholar-reader-feedback", "width=640,height=829"); } <file_sep>/ui/src/selectors/entity.ts import { defaultMemoize } from "reselect"; import { BoundingBox, Entity, isSentence, isSymbol, isTerm, isPaperQuestion, Relationship, Sentence, Symbol, Term, PaperQuestion, isAnswerSentence, } from "../api/types"; import { Entities } from "../state"; import { Rectangle } from "../types/ui"; export function selectedEntityType( selectedEntityId: string | null, entities: Entities | null ): string | null { if ( selectedEntityId === null || entities === null || entities.byId[selectedEntityId] === undefined ) { return null; } return entities.byId[selectedEntityId].type; } /** * Return all sentences containing a list of entities. */ export function sentences(entityIds: string[], entities: Entities): Sentence[] { return entityIds .map((id) => entities.byId[id]) .filter((e) => e !== undefined) .filter((e) => isSymbol(e) || isTerm(e)) .map((e) => e as Term | Symbol) .map((s) => s.relationships.sentence.id) .filter((sentId) => sentId !== null) .map((sentId) => entities.byId[sentId as string]) .filter((sent) => sent !== undefined) .filter(isSentence); } /* * Highlight sentences that contain definition information. */ export function definingSentences( entityIds: string[], entities: Entities ): Sentence[] { const sentenceIds = []; /* * Accumulate defining sentences for symbols. */ sentenceIds.push( ...entityIds .map((id) => entities.byId[id]) .filter((e) => e !== undefined) .filter(isSymbol) .map((e) => [ ...e.relationships.definition_sentences.map((r) => r.id), ...e.relationships.nickname_sentences.map((r) => r.id), ...e.relationships.defining_formula_equations.map((r) => r.id), ]) .flat() .filter((id) => id !== null) ); /* * Accumulate defining sentences for terms. */ sentenceIds.push( ...entityIds .map((id) => entities.byId[id]) .filter((e) => e !== undefined) .filter(isTerm) .map((e) => [...e.relationships.definition_sentences.map((r) => r.id)]) .flat() .filter((id) => id !== null) ); /* * Accumulate defining sentences for questions. */ sentenceIds.push( ...entityIds .map((id) => entities.byId[id]) .filter((e) => e !== undefined) .filter(isPaperQuestion) .map((e) => [...e.relationships.definition_sentences.map((r) => r.id)]) .flat() .filter((id) => id !== null) ); sentenceIds.push( ...entityIds .map((id) => entities.byId[id]) .filter((e) => e !== undefined) .filter(isAnswerSentence) .map((e) => e.relationships.question.id) .filter((id) => id !== null) ); return sentenceIds .map((id) => entities.byId[id as string]) .filter((e) => e !== undefined) .filter(isSentence); } /** * If page is not specified, an outer bounding boxes is returned for the all bounding boxes * for the symbol on the same page as the first bounding box. */ export function outerBoundingBox( entity: Entity, page?: number ): Rectangle | null { if (entity.attributes.bounding_boxes.length === 0) { return null; } page = entity.attributes.bounding_boxes[0].page; const boxes = entity.attributes.bounding_boxes.filter((b) => b.page === page); if (boxes.length === 0) { return null; } const left = Math.min(...boxes.map((b) => b.left)); const top = Math.min(...boxes.map((b) => b.top)); const right = Math.max(...boxes.map((b) => b.left + b.width)); const bottom = Math.max(...boxes.map((b) => b.top + b.height)); return { left, top, width: right - left, height: bottom - top, }; } /** * Filter a list of entity IDs to just those in a specified page. */ export function entityIdsInPage( entityIds: string[], entities: Entities | null, page: number ) { if (entities === null) { return []; } return entityIds .map((e) => entities.byId[e]) .filter((e) => e !== undefined) .filter((e) => e.attributes.bounding_boxes.some((b) => b.page === page)) .map((e) => e.id); } function areBoxesVerticallyAligned(box1: BoundingBox, box2: BoundingBox) { const box1Bottom = box1.top + box1.height; const box2Bottom = box2.top + box2.height; return ( (box1.top >= box2.top && box1.top <= box2Bottom) || (box2.top >= box1.top && box2.top <= box1Bottom) ); } /** * Comparator for sorting boxes from highest position in the paper to lowest. * See https://github.com/allenai/scholar-reader/issues/115 for a discussion for how we might * be able to sort symbols by their order in the prose instead of their position. */ export function compareBoxes(box1: BoundingBox, box2: BoundingBox) { if (box1.page !== box2.page) { return box1.page - box2.page; } if (areBoxesVerticallyAligned(box1, box2)) { return box1.left - box2.left; } else { return box1.top - box2.top; } } /** * Compare the position of two entities. Use as a comparator when ordering entities * from top-to-bottom in the document. */ export function comparePosition(e1: Entity, e2: Entity) { if (e1.id === e2.id) { return 0; } if ( e1.attributes.bounding_boxes.length === 0 || e2.attributes.bounding_boxes.length === 0 ) { return 0; } return compareBoxes( e1.attributes.bounding_boxes[0], e2.attributes.bounding_boxes[0] ); } /** * Get the page number for the first page the entity appears on. */ export function firstPage(entity: Entity) { const boxes = entity.attributes.bounding_boxes; if (boxes.length === 0) { return null; } return Math.min(...boxes.map((b) => b.page)); } export function readableFirstPageNumber(entity: Entity) { const pageNumber = firstPage(entity); return pageNumber !== null ? `${pageNumber + 1}` : "?"; } /** * Order a list of entity IDs by which ones appear first in the paper, using the position of * the symbol bounding boxes. Does not take columns into account. This method is memoized * because it's assumed that it will frequently be called with the list of all entities in * the paper, and that this sort will be costly. */ export const orderByPosition = defaultMemoize( (entityIds: string[], entities: Entities) => { const sorted = [...entityIds]; sorted.sort((sId1, sId2) => { const symbol1Boxes = entities.byId[sId1].attributes.bounding_boxes; const symbol1TopBox = symbol1Boxes.sort(compareBoxes)[0]; const symbol2Boxes = entities.byId[sId2].attributes.bounding_boxes; const symbol2TopBox = symbol2Boxes.sort(compareBoxes)[0]; if (symbol1Boxes.length === 0) { return -1; } if (symbol2Boxes.length === 0) { return 1; } return compareBoxes(symbol1TopBox, symbol2TopBox); }); return sorted; } ); /** * Order a list of definitions based on their accompanying contexts. 'definitions' and * 'contexts' should have the same dimensions, where each definition is associated with one context. * 'contexts' are used to sort the order of the definitions. */ export function orderExcerpts( excerpts: string[], contexts: Relationship[], entities: Entities ) { const contextualized = []; for (let i = 0; i < excerpts.length; i++) { const excerpt = excerpts[i]; const context = contexts[i]; if (context === undefined || context.id === null) { continue; } const contextEntity = entities.byId[context.id]; if (contextEntity === undefined) { continue; } const contextPage = firstPage(contextEntity); if (contextPage === null) { continue; } contextualized.push({ excerpt, contextEntity }); } return contextualized.sort((c1, c2) => comparePosition(c1.contextEntity, c2.contextEntity) ); } /** * Get definition that appears right before or after an entity. Don't include * a definition where the entity appears. */ export function adjacentDefinition( entityId: string, entities: Entities, where: "before" | "after" ) { const entity = entities.byId[entityId]; const contexts = definitions([entityId], entities); if ( entity === undefined || !(isTerm(entity) || isPaperQuestion(entity) || isSymbol(entity)) || isAnswerSentence(entity) || contexts.length === 0 ) { return null; } const sentenceId = entity.relationships.sentence.id; return adjacentContext(sentenceId, entities, contexts, where); } /** * Get a list of definitions for a set of entities, ordered by their position in the paper. */ export function definitions( entityIds: string[], entities: Entities, includeNicknames?: boolean ) { const entitiesWithDefinitions = entityIds .map((id) => entities.byId[id]) .filter((e) => e !== undefined) .filter((e) => isTerm(e) || isSymbol(e) || isPaperQuestion(e) || isAnswerSentence(e)) .map((e) => e as Term | Symbol); const definitions = entitiesWithDefinitions .map((e) => { if (isTerm(e) || isPaperQuestion(e) || isAnswerSentence(e)) { return e.attributes.definition_texs; } else { return e.attributes.definitions; } }) .flat(); const contexts = entitiesWithDefinitions .map((s) => s.relationships.definition_sentences) .flat(); return orderExcerpts(definitions, contexts, entities); } export function inDefinition(entityId: string, entities: Entities) { const entity = entities.byId[entityId]; if (entity === undefined || (!isSymbol(entity) && !isTerm(entity))) { return false; } if (isTerm(entity) || isPaperQuestion(entity) || isAnswerSentence(entity)) { return entity.relationships.definition_sentences.some( (r) => r.id !== null && r.id === entity.relationships.sentence.id ); } if (isSymbol(entity)) { return ( entity.relationships.definition_sentences.some( (r) => r.id !== null && r.id === entity.relationships.sentence.id ) || entity.relationships.nickname_sentences.some( (r) => r.id !== null && r.id === entity.relationships.sentence.id ) ); } return false; } export function hasDefinition(entityId: string, entities: Entities) { const entity = entities.byId[entityId]; if (entity === undefined || !(isSymbol(entity) || isTerm(entity))) { return false; } if (isTerm(entity) || isPaperQuestion(entity) || isAnswerSentence(entity)) { return entity.attributes.definition_texs.length > 0; } if (isSymbol(entity)) { return ( entity.attributes.definitions.length > 0 || entity.attributes.nicknames.length > 0 ); } } /** * Get the last context that appears right before an entity. Assumes that 'orderedContexts' * has already been ordered by document position. */ export function adjacentContext( entityId: string | null | undefined, entities: Entities, orderedContexts: { excerpt: string; contextEntity: Entity }[], where: "before" | "after" ) { if (orderedContexts.length === 0) { return null; } /* * If the requested entity doesn't exist, return the first context. */ if (entityId === undefined || entityId === null) { return orderedContexts[0]; } const entity = entities.byId[entityId]; if (entity === undefined || entity === null) { return orderedContexts[0]; } /* * Return the first context that appears before the entity. */ if (where === "before") { const reversed = [...orderedContexts].reverse(); for (const context of reversed) { if (comparePosition(context.contextEntity, entity) < 0) { return context; } } } else { for (const context of orderedContexts) { if (comparePosition(entity, context.contextEntity) < 0) { return context; } } } return null; } /** * Get a list of usages for a set of entities, ordered by their position in the paper. */ export function usages(entityIds: string[], entities: Entities) { const entitiesWithUsages = entityIds .map((id) => entities.byId[id]) .filter((e) => e !== undefined) .filter((e) => isTerm(e) || isSymbol(e) || isPaperQuestion(e) || isAnswerSentence(e)) .map((e) => e as Term | Symbol | PaperQuestion); const snippets = entitiesWithUsages.map((e) => e.attributes.snippets).flat(); const contexts = entitiesWithUsages .map((s) => s.relationships.snippet_sentences) .flat(); return orderExcerpts(snippets, contexts, entities); } /** * Rendering of equation TeX takes place using KaTeX. This leaves the rest of the text formatting * for the prose, like citations, references, citations, italics, bolds, and more as it appeared * in the raw TeX. This function performs some simple (brittle) replacements to attempt to turn the * raw TeX into plaintext. */ export function cleanTex(tex: string) { const noArgMacro = (name: string) => new RegExp(`\\\\${name}(?:{})?`, "g"); const oneArgMacro = (name: string) => new RegExp(`\\\\${name}\\{([^}]*)\\}`, "g"); return tex .replace(/%.*?$/gm, "") .replace(/\\&/gm, "&") .replace(/\{\s*\\bf\s*([^}]*)\}/g, "$1") .replace(oneArgMacro("label"), "") .replace(oneArgMacro("texttt"), "$1") .replace(oneArgMacro("textbf"), "$1") .replace(oneArgMacro("textit|emph"), "$1") .replace(oneArgMacro("footnote"), "") .replace(oneArgMacro("\\w*cite\\w*\\*?"), "[Citation]") .replace(oneArgMacro("(?:eq|c|)ref"), "[Reference]") .replace(oneArgMacro("gls(?:pl)?\\*"), (_, arg) => arg.toUpperCase()) .replace(noArgMacro("bfseries"), ""); } <file_sep>/ui/src/components/common/index.ts export * from './EntityLink'; export * from './EntityPageLink'; export * from './FormattedText'; export * from './LatexPreview'; export * from './RichText'; export * from './Sidenote'; export * from './Tooltip'; export * from './VoteButton'; <file_sep>/api/src/db-connection.ts import * as Knex from "knex"; import { BoundingBox, Entity, EntityCreateData, EntityType, EntityUpdateData, GenericAttributes, GenericRelationships, isSymbol, Paginated, PaperIdInfo, Relationship, SharedSymbolData, sharedSymbolFields, Symbol } from "./types/api"; import * as validation from "./types/validation"; import { DBConfig } from "./conf"; // import * as testEntities from './entities.json'; /** * Create a Knex query builder that can be used to submit queries to the database. */ export function createQueryBuilder(params: DBConfig) { const { host, port, database, user, password } = params; const config: Knex.Config = { client: "pg", connection: { host, port, database, user, password }, pool: { min: 0, max: 10, idleTimeoutMillis: 500 }, }; if (params.schema) { config.searchPath = [params.schema]; } return Knex(config); } /** * An error in loading data for an entity from the API. Based on custom error class declaration from: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error */ export class EntityLoadError extends Error { constructor(id: string, type: string, ...params: any[]) { super(...params); if (Error.captureStackTrace) { Error.captureStackTrace(this, EntityLoadError); } this.name = "ValidationError"; this.message = `Data for entity ${id} of type ${type} is either missing or typed incorrectly`; } } /** * An interface to the database. Performs queries and returns santized, typed objects. */ export class Connection { constructor(params: DBConfig) { this._knex = createQueryBuilder(params); } async close() { await this._knex.destroy(); } async insertLogEntry(logEntry: LogEntryRow) { return await this._knex("logentry").insert(logEntry); } async getAllPapers(offset: number = 0, size: number = 25, entity_type: EntityType = 'citation'): Promise<Paginated<PaperIdInfo>> { type Row = PaperIdInfo & { total_count: string; } const response = await this._knex.raw<{ rows: Row[] }>(` SELECT paper.arxiv_id, paper.s2_id, version.index AS version, COUNT(*) OVER() as total_count FROM paper JOIN ( SELECT MAX(index) AS index, paper_id FROM version GROUP BY paper_id ) AS version ON version.paper_id = paper.s2_id JOIN entity ON entity.paper_id = paper.s2_id AND entity.version = version.index AND entity.type = ? GROUP BY paper.s2_id, paper.arxiv_id, version.index ORDER BY paper.arxiv_id DESC OFFSET ${offset} LIMIT ${size} `, [entity_type]); const rows = response.rows.map(r => ({ arxiv_id: r.arxiv_id, s2_id: r.s2_id, version: r.version, })); const total = parseInt(response.rows[0].total_count); return { rows, offset, size, total }; } async getPaperEntityCount(paperSelector: PaperSelector, entityType: string): Promise<number | null> { const idField = isS2Selector(paperSelector) ? 'p.s2_id' : 'p.arxiv_id'; const idValue = isS2Selector(paperSelector) ? paperSelector.s2_id : `${paperSelector.arxiv_id}%`; const whereClause = `${idField} ${isS2Selector(paperSelector) ? '=' : 'ilike'} ?` const response = await this._knex.raw<{ rows: {count: number, id: string}[] }>(` SELECT count(e.*), ${idField} FROM paper p JOIN entity e on e.paper_id = p.s2_id JOIN ( SELECT paper_id, MAX(index) AS max_version FROM version GROUP BY paper_id ) AS maximum ON maximum.paper_id = e.paper_id WHERE e.version = maximum.max_version AND ${whereClause} AND e.type = ? GROUP BY p.s2_id `, [idValue, entityType]); if (response.rows.length > 0) { return response.rows[0].count; } return null; } async checkPaper(paperSelector: PaperSelector): Promise<boolean> { const rows = await this._knex("paper") .where(paperSelector); return rows.length > 0; } async getLatestPaperDataVersion(paperSelector: PaperSelector): Promise<number | null> { const rows = await this._knex("version") .max("index") .join("paper", { "paper.s2_id": "version.paper_id" }) .where(paperSelector); const version = Number(rows[0].max); return isNaN(version) ? null : version; } async getLatestProcessedArxivVersion(paperSelector: PaperSelector): Promise<number | null> { if (isS2Selector(paperSelector)) { return null; } // Provided arXiv IDs might have a version suffix, but ignore that for this check. const versionDelimiterIndex = paperSelector.arxiv_id.indexOf('v'); const arxivId = versionDelimiterIndex > -1 ? paperSelector.arxiv_id.substring(0, versionDelimiterIndex) : paperSelector.arxiv_id; // TODO(mjlangan): This won't support arXiv IDs prior to 03/2007 as written const response = await this._knex.raw<{ rows: { arxiv_version: number }[] }>(` SELECT CAST((REGEXP_MATCHES(arxiv_id,'^\\d{4}\\.\\d{4,5}v(\\d+)$'))[1] AS integer) AS arxiv_version FROM paper WHERE arxiv_id ilike ? ORDER BY arxiv_version DESC LIMIT 1 `, [`${arxivId}%`]); if (response.rows.length > 0) { return response.rows[0].arxiv_version; } return null; } createBoundingBoxes( boundingBoxRows: Omit<BoundingBoxRow, "id">[] ): BoundingBox[] { return boundingBoxRows.map((bbr) => ({ source: bbr.source, page: bbr.page, left: bbr.left, top: bbr.top, width: bbr.width, height: bbr.height, })); } /** * Extract attributes and relationships for an entity from database rows. These attributes and * relationships may need to be cleaned, as they contain *anything* that was found in the * entity table, which could include junk uploaded by annotators. */ unpackEntityDataRows(rows: Omit<EntityDataRow, "id">[], slim: boolean = false) { const attributes: GenericAttributes = {}; const relationships: GenericRelationships = {}; for (const row of rows) { /** * Read attributes. */ let casted_value; if (row.value === null) { if (!row.of_list) { casted_value = null; } } else if (row.item_type === "integer") { casted_value = parseInt(row.value); } else if (row.item_type === "float") { casted_value = parseFloat(row.value); } else if (row.item_type === "string") { casted_value = row.value; } if (casted_value !== undefined) { if (row.of_list) { if (attributes[row.key] === undefined) { attributes[row.key] = []; } attributes[row.key].push(casted_value); } else { attributes[row.key] = casted_value; } } /** * Read relationships. */ if (row.item_type === "relation-id" && row.relation_type !== null) { // optionally return a more compact representation for relationships const relationship = slim ? { id: row.value } : { type: row.relation_type, id: row.value }; if (row.of_list) { if (relationships[row.key] === undefined) { relationships[row.key] = []; } (relationships[row.key] as Relationship[]).push(relationship); } else { relationships[row.key] = relationship; } } } return { attributes, relationships }; } /** * Convert entity information from the database into an entity object. */ createEntityObjectFromRows( entityRow: EntityRow, boundingBoxRows: Omit<BoundingBoxRow, "id">[], entityDataRows: Omit<EntityDataRow, "id">[], slim?: boolean, ): Entity { const boundingBoxes = this.createBoundingBoxes(boundingBoxRows); const { attributes, relationships } = this.unpackEntityDataRows( entityDataRows, slim ); const entity = { id: String(entityRow.id), type: entityRow.type as EntityType, attributes: { ...attributes, version: entityRow.version, source: entityRow.source, bounding_boxes: boundingBoxes, tags: attributes.tags || [] }, relationships: { ...relationships, }, }; if (isSymbol(entity)) { entity.attributes.disambiguated_id = entity.attributes.mathml; } return entity; } async getEntitiesForPaper(paperSelector: PaperSelector, entityTypes: EntityType[], includeDuplicateSymbolData: boolean, slim: boolean, version?: number) { // added // console.log(testEntities['default']); if (version === undefined) { try { let latestVersion = await this.getLatestPaperDataVersion(paperSelector); if (latestVersion === null) { return []; } version = latestVersion; } catch (e) { console.log("Error fetching latest data version number:", e); } } const entityColumns = slim ? ["entity.paper_id AS paper_id", "id", "type"] : ["entity.paper_id AS paper_id", "id", "version", "type", "source"]; const entityRows: EntityRow[] = await this._knex("entity") .select(entityColumns) .join("paper", { "paper.s2_id": "entity.paper_id" }) .where({ ...paperSelector, version }).andWhere(builder => { if (entityTypes.length > 0) { builder.whereIn('type', entityTypes); } else { builder.where(true); } }); const entityIds = entityRows.map(e => e.id); const boundingBoxColumns = slim ? ["id", "entity_id", "page", "left", "top", "width", "height"] : ["id", "entity_id", "source", "page", "left", "top", "width", "height"]; let boundingBoxRows: BoundingBoxRow[]; try { boundingBoxRows = await this._knex("boundingbox") .select(boundingBoxColumns) .whereIn("entity_id", entityIds); } catch (e) { console.log(e); throw "Error"; } /* * Organize bounding box data by the entity they belong to. */ const boundingBoxRowsByEntity = boundingBoxRows.reduce( (dict, row) => { if (dict[row.entity_id] === undefined) { dict[row.entity_id] = []; } dict[row.entity_id].push(row); return dict; }, {} as { [entity_id: string]: BoundingBoxRow[]; } ); const entityDataColumns = slim ? ["entity.id AS entity_id", "key", "value", "item_type", "of_list", "relation_type"] : ["entity.id AS entity_id", "entitydata.source AS source", "key", "value", "item_type", "of_list", "relation_type"]; const entityDataRows: EntityDataRow[] = await this._knex("entitydata") .select(entityDataColumns) .join("entity", { "entitydata.entity_id": "entity.id" }) /* * Order by entity ID to ensure that items from lists are retrieved in * the order they were written to the database. */ .orderBy("entitydata.id", "asc") .whereIn("entity.id", entityIds) .whereNot( (builder) => { if (!includeDuplicateSymbolData) { builder .where("entity.type", "symbol") .whereIn("entitydata.key", sharedSymbolFields) } } ) /* * Organize entity data entries by the entity they belong to. */ const entityDataRowsByEntity = entityDataRows.reduce( (dict, row) => { if (dict[row.entity_id] === undefined) { dict[row.entity_id] = []; } dict[row.entity_id].push(row); return dict; }, {} as { [entity_id: string]: EntityDataRow[]; } ); /** * Create entities from entity data. */ const entities: Entity[] = entityRows .map((entityRow) => { const boundingBoxRowsForEntity = boundingBoxRowsByEntity[entityRow.id] || []; const entityDataRowsForEntity = entityDataRowsByEntity[entityRow.id] || []; return this.createEntityObjectFromRows( entityRow, boundingBoxRowsForEntity, entityDataRowsForEntity, slim ); }) /* * Validation with Joi does two things: * 1. It adds default values to fields for an entity. * 2. It lists errors when an entity is still missing reuqired properties. */ .map((e) => validation.loadedEntity.validate(e, { stripUnknown: true })) .filter((validationResult) => { if (validationResult.error !== undefined) { console.error( "Invalid entity will not be returned. Error:", validationResult.error ); return false; } return true; }) .map((validationResult) => validationResult.value as Entity); return entities; } /** * Default implementation in `getEntitiesForPaper` naively retrieves all entities, * which includes quadratic data duplication across multiple instances of the same symbol. * This variant method is meant as a placeholder bridge until the underlying DB schema and * extraction write layer is changed to be non-duplicative. * Leaving the underlying data unchanged in the DB, we selectively exclude the entity data * types known to be redundant. These are retrieved later and added into lookup tables. */ async getDedupedEntitiesForPaper(paperSelector: PaperSelector, entityTypes: EntityType[], version?: number) { const entities = await this.getEntitiesForPaper(paperSelector, entityTypes, false, true, version); // Short-circuit fancy behavior below if we don't need the shared symbol data. if (entityTypes.indexOf("symbol") === -1 && entityTypes.length > 0) { return { entities } } // To provide a deduped copy of shared data between symbol instances, we // identify each symbol by its "disambiguated" id (currently the `mathml` attribute). // An arbitrary symbol entity from within each `mathml` is chosen as an exemplar from // which to look up supporting data that is identical across instances. const disambiguatedSymbolIdsToExemplarEntityIds = entities .filter((row) => isSymbol(row)) .reduce( (dict, symbol) => { const disambiguatedId = (symbol as Symbol).attributes.mathml; if (disambiguatedId !== null) { dict[disambiguatedId] = symbol.id; } return dict; }, {} as { [disambiguatedId: string]: string } ); const exemplarEntityIdsToDisambiguatedSymbolIds = Object.keys(disambiguatedSymbolIdsToExemplarEntityIds).reduce( (dict, key) => { const exemplarEntityId = disambiguatedSymbolIdsToExemplarEntityIds[key]; dict[exemplarEntityId] = key; return dict; }, {} as { [exemplarEntityId: string]: string } ); const dedupedSymbolData = await this._knex("entitydata") .select( "entity_id", "key", "value" ) .orderBy("id", "asc") .whereIn("key", sharedSymbolFields) .whereIn("entity_id", Object.values(disambiguatedSymbolIdsToExemplarEntityIds)) const sharedSymbolData = dedupedSymbolData.reduce( (dict, row) => { const disambiguatedId = exemplarEntityIdsToDisambiguatedSymbolIds[row.entity_id]; if (!(disambiguatedId in dict)) { dict[disambiguatedId] = sharedSymbolFields.reduce( (dict, key) => { dict[key] = []; return dict; }, {} as {[sharedSymbolField: string]: string[]} ); } dict[disambiguatedId][row.key].push(row.value) return dict; }, {} as { [disambiguatedId: string]: SharedSymbolData } ) return { entities, sharedSymbolData }; } createBoundingBoxRows( entity_id: number, bounding_boxes: BoundingBox[] ): Omit<BoundingBoxRow, "id">[] { return bounding_boxes.map((bb) => ({ entity_id, source: bb.source, page: bb.page, left: bb.left, top: bb.top, width: bb.width, height: bb.height, })); } /** * Take an input entity and extract from it a list of rows that can be inserted into the * 'entitydata' table to preserve all that's worth knowing about this entity. It is expected that * if an entity has undergone the validation from the './validation.ts' validators, then all * attributes and relationships are valid and therefore will be entered in the database. */ createEntityDataRows( entity_id: number, source: string, attributes: GenericAttributes, relationships: GenericRelationships ) { const rows: Omit<EntityDataRow, "id">[] = []; const keys = []; const addRow = ( key: string, value: string | null, item_type: EntityDataRowType, of_list: boolean, relation_type?: string | null ) => { rows.push({ entity_id, source, key, value, item_type, of_list, relation_type: relation_type || null, }); }; for (const key of Object.keys(attributes)) { if (["source", "version", "bounding_boxes"].indexOf(key) !== -1) { continue; } if (keys.indexOf(key) === -1) { keys.push(key); } const value = attributes[key]; let values = []; let of_list; if (Array.isArray(value)) { values = value; of_list = true; } else { values = [value]; of_list = false; } for (let v of values) { let item_type: EntityDataRowType | undefined = undefined; if (typeof v === "boolean") { item_type = "boolean"; v = v ? 1 : 0; } else if (typeof v === "number") { /** * This check for whether a number is an integer is based on the polyfill from MDN: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger#Polyfill */ if (isFinite(v) && Math.floor(v) === v) { item_type = "integer"; } else { item_type = "float"; } } else if (typeof v === "string") { item_type = "string"; } if (item_type !== undefined) { addRow(key, String(v), item_type, of_list, null); } } } for (const key of Object.keys(relationships)) { if (keys.indexOf(key) === -1) { keys.push(key); } const value = relationships[key]; if (Array.isArray(value)) { for (const r of value) { addRow(key, r.id, "relation-id", true, r.type); } } else { addRow(key, value.id, "relation-id", false, value.type); } } return { rows, keys }; } async createEntity(paperSelector: PaperSelector, data: EntityCreateData) { /** * Fetch the ID for the specified paper. */ const paperRows = await this._knex("paper") .select("s2_id AS id") .where(paperSelector); const paperId = paperRows[0].id; /** * Create entity with the most recent data version for this paper if the data version was * not specified by the client. */ let version; if (typeof data.attributes.version === "number") { version = data.attributes.version; } else { version = await this.getLatestPaperDataVersion(paperSelector); if (version === null) { throw Error( "No data version was specified, and no data version exists for this paper." ); } } /** * Create new entity. */ const entityRow: Omit<EntityRow, "id"> = { paper_id: paperId, type: data.type, version, source: data.attributes.source, }; const id = Number( (await this._knex("entity").insert(entityRow).returning("id"))[0] ); /** * Insert bounding boxes and data for entity. Must occur after the entity is inserted in * order to have access to the entity ID. */ const boundingBoxRows = this.createBoundingBoxRows( id, data.attributes.bounding_boxes ); const { rows: entityDataRows } = this.createEntityDataRows( id, data.attributes.source, data.attributes, data.relationships as GenericRelationships ); await this._knex.batchInsert("boundingbox", boundingBoxRows); await this._knex.batchInsert("entitydata", entityDataRows); /** * Create a completed version of the entity to return to the client. */ return { ...data, id: String(id), attributes: { ...data.attributes, version, }, }; } async updateEntity(data: EntityUpdateData) { /** * Update entity data. */ let entityRowUpdates: EntityRowUpdates | null = null; if (data.attributes !== undefined) { entityRowUpdates = { source: data.attributes.source, version: data.attributes.version, }; } if (entityRowUpdates !== null && Object.keys(entityRowUpdates).length > 0) { await this._knex("entity") .update(entityRowUpdates) .where({ id: data.id, type: data.type }); } const entityId = Number(data.id); /* * Update bounding boxes. */ if (data.attributes.bounding_boxes !== undefined) { await this._knex("boundingbox").delete().where({ entity_id: data.id }); const boundingBoxRows = this.createBoundingBoxRows( entityId, data.attributes.bounding_boxes ); await this._knex.batchInsert("boundingbox", boundingBoxRows); } /* * Update custom attributes, by removing previous values for known attributes and updating * them to the new values. */ const { rows: attributeRows, keys: attributeKeys, } = this.createEntityDataRows( entityId, data.attributes.source, data.attributes, {} ); for (const key of attributeKeys) { await this._knex("entitydata") .delete() .where({ entity_id: data.id, key }); } await this._knex.batchInsert("entitydata", attributeRows); /* * Update relationships. */ if (data.relationships !== undefined) { const { keys: relationshipKeys, rows: relationshipRows, } = this.createEntityDataRows( entityId, data.attributes.source, {}, data.relationships as GenericRelationships ); for (const key of relationshipKeys) { await this._knex("entitydata") .delete() .where({ entity_id: data.id, key }); } await this._knex.batchInsert("entitydata", relationshipRows); } } async deleteEntity(entity_id: string) { await this._knex("entity").delete().where({ id: entity_id }); } private _knex: Knex; } /** * Expected knex.js parameters for selecting a paper. Map from paper table column ID to value. */ export type PaperSelector = ArxivIdPaperSelector | S2IdPaperSelector; interface ArxivIdPaperSelector { arxiv_id: string; } interface S2IdPaperSelector { s2_id: string; } function isArxivSelector(selector: PaperSelector): selector is ArxivIdPaperSelector { return (selector as ArxivIdPaperSelector).arxiv_id !== undefined; } function isS2Selector(selector: PaperSelector): selector is S2IdPaperSelector { return (selector as S2IdPaperSelector).s2_id !== undefined; } <file_sep>/api/Dockerfile FROM python:3.8.6 # Uncomment the following lines to make PyTorch available to your application. # See https://skiff.allenai.org/gpu.html for more details. # # ENV LD_LIBRARY_PATH /usr/local/nvidia/lib:/usr/local/nvidia/lib64 # ENV NVIDIA_VISIBLE_DEVICES all # ENV NVIDIA_DRIVER_CAPABILITIES compute,utility # RUN pip install torch==1.7.0+cu101 -f https://download.pytorch.org/whl/torch_stable.html WORKDIR /api # Install Python dependencies COPY requirements.txt . RUN pip install -r requirements.txt # Copy over the source code COPY app app/ COPY start.py . # This enables the Flask debugger and activates code that restarts the # API as you make changes ARG FLASK_ENV=development ENV FLASK_ENV $FLASK_ENV # Kick things off ENTRYPOINT [ "python" ] CMD [ "start.py" ] <file_sep>/papersrv/Dockerfile FROM nginx:1.17.0-alpine COPY nginx.conf /etc/nginx/nginx.conf WORKDIR /papers COPY paper paper <file_sep>/ui/src/components/icon/index.ts export * from './ChartIcon'; export * from './InboundCitationIcon'; export * from './InfluentialCitationIcon'; export * from './OutboundCitationIcon'; <file_sep>/ui/src/selectors/annotation.ts /** * Filter a list of annotations to those that appear within a specific page. Conservatively * include IDs that are missing page number information. */ export function annotationsInPage(annotationIds: string[], page: number) { return idsForPage(annotationIds, page, true); } /** * Filter a list of annotation spans to those that appear within a specific page. Conservatively * include IDs that are missing page number information. */ export function annotationSpansInPage(spanIds: string[], page: number) { return idsForPage(spanIds, page, true); } function idsForPage(ids: string[], page: number, includeUnmarked: boolean) { return ids.filter((id) => { const match = id.match(/page-(\d+)/); if (match === null) { return includeUnmarked; } return Number(match[1]) === page; }); } <file_sep>/api/start.py import argparse import os import sys import logging from typing import Tuple from gevent.pywsgi import WSGIServer from flask import Flask, Response, request, jsonify from app.api import create_api from app.utils import StackdriverJsonFormatter from werkzeug.middleware.proxy_fix import ProxyFix def start(): """ Starts up a HTTP server attached to the provider port, and optionally in development mode (which is ideal for local development but unideal for production use). """ parser = argparse.ArgumentParser(description='Starts your application\'s HTTP server.') parser.add_argument( '--port', '-p', help='The port to listen on', default=8000 ) parser.add_argument( '--prod', help= 'If specified the server is started in production mode, where ' + 'the server isn\'t restarted as changes to the source code occur.', action='store_true' ) args = parser.parse_args() # Locally we don't specify any handlers, which causes `basicConfig` to set # up one for us that writes human readable messages. handlers = None # If we're in production we setup a handler that writes JSON log messages # in a format that Google likes. if args.prod: json_handler = logging.StreamHandler() json_handler.setFormatter(StackdriverJsonFormatter()) handlers = [ json_handler ] logging.basicConfig( level=os.environ.get('LOG_LEVEL', default=logging.INFO), handlers=handlers ) logger = logging.getLogger() logger.debug("AHOY! Let's get this boat out to water...") app = Flask("app") # Bind the API functionality to our application. You can add additional # API endpoints by editing api.py. logger.debug("Starting: init API...") app.register_blueprint(create_api(), url_prefix='/') logger.debug("Complete: init API...") # In production we use a HTTP server appropriate for production. if args.prod: logger.debug("Starting: gevent.WSGIServer...") # There are two proxies -- the one that's run as a sibling of this process, and # the Ingress controller that runs on the cluster. # See: https://skiff.allenai.org/templates.html num_proxies = 2 proxied_app = ProxyFix(app, x_for=num_proxies, x_proto=num_proxies, x_host=num_proxies, x_port=num_proxies) http_server = WSGIServer(('0.0.0.0', args.port), proxied_app, log=logger, error_log=logger) app.logger.info(f'Server listening at http://0.0.0.0:{args.port}') http_server.serve_forever() else: logger.debug("Starting: Flask development server...") num_proxies = 1 proxied_app = ProxyFix(app, x_for=num_proxies, x_proto=num_proxies, x_host=num_proxies, x_port=num_proxies) app.run(host='0.0.0.0', port=args.port) if __name__ == '__main__': start() <file_sep>/ui/src/selectors/equation.ts import { Entities } from "../state"; import { isSymbol } from "../api/types"; import { isTopLevelSymbol } from "./symbol"; import { defaultMemoize } from "reselect"; export const equationSymbols = defaultMemoize( (equationId: string, entities: Entities) => { return entities.all .map((id) => entities.byId[id]) .filter((e) => e !== undefined) .filter(isSymbol) .filter((s) => s.relationships.equation.id === equationId); } ); export function equationTopLevelSymbols( equationId: string, entities: Entities ) { return equationSymbols(equationId, entities).filter((s) => isTopLevelSymbol(s, entities) ); } <file_sep>/api/app/api.py from flask import Blueprint, request, current_app def create_api() -> Blueprint: """ Creates an instance of your API. If you'd like to toggle behavior based on command line flags or other inputs, add them as arguments to this function. """ api = Blueprint('api', __name__) # This route simply tells anything that depends on the API that it's # working. If you'd like to redefine this behavior that's ok, just # make sure a 200 is returned. @api.route('/') def index(): return '', 204 # This route just prints out the provided payload to stdout. These messages # are in turn aggregated into a BigQuery database for examination. @api.route('/api/log', methods=['POST']) def log(): event = request.json message = { "message_type": "s2-simplify-event", "event": event } current_app.logger.info(message) return '', 204 return api <file_sep>/ui/src/settings.ts import { SymbolUnderlineMethod } from "./components/entity/EntityAnnotationLayer"; /** * Configurable app-wide settings. Whenever an experimental feature is added that should be * possible to toggle on / off (either during development, or when sharing a prototype with * a user / the team), add it to this list of settings instead of 'state' above. Settings from this * list can be configured in a developer's toolbar, and might eventually be set using * query parameters. */ export interface Settings { /** * Show a primer at the start of the document introducing the tool and definitions. */ primerPageEnabled: boolean; /** * Whether or not to show term and symbol glossary on primer page */ primerPageGlossaryEnabled: boolean; /** * Show instructions in the primer describing how to use the tool. */ primerInstructionsEnabled: boolean; /** * Style annotations to show hints that they're there (e.g., underlines). */ annotationHintsEnabled: boolean; /** * Make entities (like symbols and terms) clickable. */ annotationInteractionEnabled: boolean; /** * When the paper first loads, automatically scroll the the entity with this ID. */ initialFocus: string | null; /** * Show glosses when an entity (i.e., symbol or term) is selected. */ glossesEnabled: boolean; /** * Show FAQs in sidebar */ FAQsEnabled: boolean; /** * Show Section Headers in sidebar */ SectionHeadersEnabled: boolean; /** * Show glosses for citations containing paper summary information. */ citationGlossesEnabled: boolean; /** * Show glosses for terms. */ termGlossesEnabled: boolean; /** * How to determine whether to underline a symbol. For example, underlines can be placed * underneath all symbols with a definition, or under all top-level symbols. */ symbolUnderlineMethod: SymbolUnderlineMethod; /** * Start a within-paper symbol search when a symbol is selected. */ symbolSearchEnabled: boolean; /** * Whether to show definition related features in symbol gloss */ definitionsInSymbolGloss: boolean; /** * Enable the 'declutter' interaction which masks pages to show only those sentences that * contain an entity that the user selected. */ declutterEnabled: boolean; /** * Show preview of the definition of a symbol a corner of the screen when that definition * is not already on the screen. */ definitionPreviewEnabled: boolean; /** * Show callouts over equation when the equation is selected. */ equationDiagramsEnabled: boolean; /** * Use nicknames and definitions to create diagram labels if no explicit diagram label * has been defined for the entity. */ useDefinitionsForDiagramLabels: boolean; /** * Show menu of actions when text is selected. */ textSelectionMenuEnabled: boolean; /** * Enable the annotation of new entities in the paper. */ entityCreationEnabled: boolean; /** * Show the entity property editor for a selected entity. */ entityEditingEnabled: boolean; /** * The presentation format of glosses (i.e., as tooltips, sidenotes, etc.) */ glossStyle: GlossStyle; /** * Replace gloss contents with widgets for users to annotate the quality of gloss contents. */ glossEvaluationEnabled: boolean; /** * Copy the TeX for sentences when a sentence is clicked on. Normally, this should probably be * disabled as it interferes with built-in text selection in pdf.js. */ sentenceTexCopyOnOptionClickEnabled: boolean; } /** * A preset is a named, partial specification of settings. */ interface Preset extends Partial<Settings> { key: string; } /** * Define new presets for settings here. */ const PRESETS: Preset[] = [ { key: "demo", primerInstructionsEnabled: false, useDefinitionsForDiagramLabels: true, termGlossesEnabled: true, declutterEnabled: true, equationDiagramsEnabled: true, }, { key: "sab", termGlossesEnabled: false, citationGlossesEnabled: true, symbolUnderlineMethod: "defined-symbols", primerInstructionsEnabled: true, }, { key: "sab-lite", symbolUnderlineMethod: "top-level-symbols", equationDiagramsEnabled: false, }, { key: "descriptive", FAQsEnabled: false, SectionHeadersEnabled: true, citationGlossesEnabled: true, }, { key: "prescriptive", FAQsEnabled: true, SectionHeadersEnabled: false, citationGlossesEnabled: false, }, { key: "all", FAQsEnabled: true, SectionHeadersEnabled: true, citationGlossesEnabled: true, }, { key: "pdf", annotationInteractionEnabled: false, annotationHintsEnabled: false, glossesEnabled: false, FAQsEnabled: false, SectionHeadersEnabled: false, initialFocus: null, citationGlossesEnabled: false, definitionsInSymbolGloss: false, termGlossesEnabled: false, symbolSearchEnabled: false, declutterEnabled: false, definitionPreviewEnabled: false, equationDiagramsEnabled: false, useDefinitionsForDiagramLabels: false, entityCreationEnabled: false, entityEditingEnabled: false, sentenceTexCopyOnOptionClickEnabled: false, glossEvaluationEnabled: false, }, ]; /** * Get app settings, merging presets matching the key 'preset' with the default settings. */ export function getSettings(presets?: string[]) { const DEFAULT_SETTINGS: Settings = { primerPageEnabled: false, primerPageGlossaryEnabled: false, primerInstructionsEnabled: true, annotationInteractionEnabled: true, annotationHintsEnabled: true, glossesEnabled: true, FAQsEnabled: true, SectionHeadersEnabled: true, initialFocus: null, glossStyle: "tooltip", // from "tooltip" textSelectionMenuEnabled: false, citationGlossesEnabled: true, definitionsInSymbolGloss: false, termGlossesEnabled: true, //swapped symbolUnderlineMethod: "top-level-symbols", symbolSearchEnabled: true, declutterEnabled: true, definitionPreviewEnabled: true, //swapped equationDiagramsEnabled: true, //swapped useDefinitionsForDiagramLabels: false, entityCreationEnabled: false, entityEditingEnabled: false, sentenceTexCopyOnOptionClickEnabled: false, glossEvaluationEnabled: false, }; let settings = DEFAULT_SETTINGS; if (presets) { for (const preset of presets) { for (const p of PRESETS) { if (p.key === preset) { settings = { ...settings, ...p }; } } } } return settings; } export function getPDFReaderOnlySettings(presets?: string[]) { const PDF_READER_SETTINGS: Settings = { primerPageEnabled: false, primerPageGlossaryEnabled: false, primerInstructionsEnabled: false, annotationInteractionEnabled: false, annotationHintsEnabled: false, glossesEnabled: false, FAQsEnabled: false, SectionHeadersEnabled: false, initialFocus: null, glossStyle: "tooltip", // from "tooltip" textSelectionMenuEnabled: false, citationGlossesEnabled: false, definitionsInSymbolGloss: false, termGlossesEnabled: false, symbolUnderlineMethod: "top-level-symbols", symbolSearchEnabled: false, declutterEnabled: false, definitionPreviewEnabled: false, equationDiagramsEnabled: false, useDefinitionsForDiagramLabels: false, entityCreationEnabled: false, entityEditingEnabled: false, sentenceTexCopyOnOptionClickEnabled: false, glossEvaluationEnabled: false, }; let settings = PDF_READER_SETTINGS; if (presets) { for (const preset of presets) { for (const p of PRESETS) { if (p.key === preset) { settings = { ...settings, ...p }; } } } } return settings; } /** * A specification declaring how a setting should appear in a settings editor. */ export interface ConfigurableSetting { key: keyof Settings; /** * A setting can be one of the following types: * * flag: boolean yes / no option (can be switched on / off) * * choice: selection among multiple choices */ type: "flag" | "choice"; label: string; /** * Must be defined if 'type' is "choice". */ choices?: string[]; } export const GLOSS_STYLES = ["tooltip", "sidenote"] as const; export type GlossStyle = typeof GLOSS_STYLES[number]; /** * Any setting that should be editable from the settings editor should have a spec in this list. */ export const CONFIGURABLE_SETTINGS: ConfigurableSetting[] = [ { key: "primerPageEnabled", type: "flag", label: "Primer page", }, { key: "annotationHintsEnabled", type: "flag", label: "Underline annotations", }, { key: "glossStyle", type: "choice", label: "Gloss style", choices: [...GLOSS_STYLES], }, { key: "glossEvaluationEnabled", type: "flag", label: "Evaluate glosses", }, { key: "textSelectionMenuEnabled", type: "flag", label: "Show text selection menu", }, { key: "citationGlossesEnabled", type: "flag", label: "Citation glosses", }, { key: "symbolSearchEnabled", type: "flag", label: "Symbol search", }, { key: "declutterEnabled", type: "flag", label: "Declutter interaction", }, { key: "definitionPreviewEnabled", type: "flag", label: "Definition preview", }, { key: "equationDiagramsEnabled", type: "flag", label: "Equation diagrams", }, { key: "useDefinitionsForDiagramLabels", type: "flag", label: "Use definitions for diagram labels", }, { key: "entityCreationEnabled", type: "flag", label: "Create entities", }, { key: "entityEditingEnabled", type: "flag", label: "Edit entity properties", }, { key: "sentenceTexCopyOnOptionClickEnabled", type: "flag", label: "<Opt> + <Click> to copy sentence TeX", }, ]; <file_sep>/ui/src/state.ts import { SnackbarMode } from "./components/overlay/AppOverlay"; import { DrawerContentType, DrawerMode } from "./components/drawer/Drawer"; import { AreaSelectionMethod } from "./components/control/EntityCreationToolbar"; import { FindMode, FindQuery, SymbolFilter } from "./components/search/FindBar"; import { Settings } from "./settings"; import { Entity, Paper } from "./api/types"; import { PDFPageView, PDFViewer, PDFViewerApplication, } from "./types/pdfjs-viewer"; import { PDFDocumentProxy } from 'pdfjs-dist/types/display/api' /** * An object containing all the shared global state. It is designed to be used as follows: * * 1. For complex properties (i.e., lists and maps), it is expected that when updating these * properties, an entirely new data structure will be created. * This allows components to do strict equality comparisons on these properties to determine * whether or not they have changed. For example, if you add a new citation * to the list of citations, and want the annotations for citations to update, create a new * citations array, and set the 'citations' property to point to this new array. * * 2. If you want to add new properties, keep the structure of the state as flat as possible. * This keeps us from having to write complex code for setting state and for checking on the * equality of properties when re-rendering. * * 3. You should pass data from this state through properties, not context. In the past, all * global state was passed through context. Because the much of the state of this application * is global (e.g., IDs of selected elements, queries for the find-bar, the data that was * retrieved from the API), this caused two problems: * * * Thousands of components would re-render whenever a single property changed on the state, * leading to a feeling of lagginess when using most parts of the interface. * * We couldn't uses React dev tools to find out what properties triggered a re-render, as * this information is not collected for changes to context. * * Although it requires passing much data through properites, for the time being the cost of * more verbose code is worth the trade-off for improving our ability to optimize speed by * having careful control over how global state will trigger re-renders. */ export interface State extends Settings { /* * *** PAPER DATA *** */ entities: Readonly<Entities>; lazyPapers: Map<string, Paper>; /* * *** PDF.JS OBJECTS *** */ pages: Readonly<Pages> | null; pdfViewerApplication: PDFViewerApplication | null; pdfDocument: PDFDocumentProxy | null; pdfViewer: PDFViewer | null; /* * *** USER INTERFACE STATE *** */ /* * ~ Loading states ~ */ areCitationsLoading: boolean; /* * ~ App control panel ~ */ controlPanelShowing: boolean; /* * ~ Selecting annotations and entities ~ */ selectedAnnotationIds: string[]; selectedAnnotationSpanIds: string[]; selectedEntityIds: string[]; multiselectEnabled: boolean; jumpTarget: string | null; /* * ~ Text selection ~ */ textSelection: Selection | null; /** * Time in milliseconds that the selection changed last. Stored in state because * textSelection may be the same object whenever a 'selectionchange' event is * triggered. By storing the milliseconds of the last change, a re-render can * be triggered on each selection change event. */ textSelectionChangeMs: number | null; /* * ~ Drawer (sidebar) state ~ */ drawerMode: DrawerMode; drawerContentType: DrawerContentType; /* * ~ Snackbar (alert) state ~ */ snackbarMode: SnackbarMode; /** * The time in milliseconds when the latest snackbar message was submitted. A simple way to * supply this value is to call `Date.now()` when the message is submitted. This is used to * trigger a re-render of the snackbar with a new message when another message is already showing. */ snackbarActivationTimeMs: number | null; snackbarMessage: string | null; /* * ~ Find bar state ~ /** * When 'isFindActive' is false, the rest of the properties for finding should be set to null. */ isFindActive: boolean; findMode: FindMode; /** * The time in milliseconds that this 'find' action was triggered. A simple way to * supply this value is to call `Date.now()` when a find action is triggered. This is used to * indicate to the find widget that a new 'find' has started, e.g., if a user types 'Ctrl+F' * while the 'find' bar is already open. */ findActivationTimeMs: number | null; findQuery: FindQuery; /** * Valid values are [0..(findMatchCount - 1)] */ findMatchIndex: number | null; findMatchCount: number | null; /** * A list of IDs of matching entities from the search. This will be defined for some find * modes (e.g., 'symbol') and not for others. */ findMatchedEntities: string[] | null; /* * ~ Human annotations ~ */ entityCreationAreaSelectionMethod: AreaSelectionMethod; entityCreationType: KnownEntityType; /** * Whether edits to an entity should apply to other matching entities (e.g., editing a symbol * should also edit other symbols with the same TeX, or editing a term should also edit other * all other appearances of the same term). */ propagateEntityEdits: boolean; /* Added for FAQ hovering. One specifies which FAQ is being hovered over in the sidebar The other specifies if an FAQ was clicked on, which case it becomes the active FAQ */ FAQHoveredID: string | null; selectedFAQID: string | null; } export type Entities = RelationalStore<Entity>; export const KNOWN_ENTITY_TYPES = [ "citation", "symbol", "equation", "sentence", "term", "experience",//added ] as const; export type KnownEntityType = typeof KNOWN_ENTITY_TYPES[number]; export type Papers = { [s2Id: string]: Paper }; export type SymbolFilters = RelationalStore<SymbolFilter>; export interface UserInfo { user: { id: number; email: string | null; }; entriesWithPaperIds: [number, string][]; } export type Pages = { [pageNumber: number]: PageModel }; export interface PageModel { /** * Timestamp of 'pagerendered' event that created this page. */ timeOfLastRender: number; /** * Reference to pdf.js page view object. */ view: PDFPageView; } export interface PaperId { id: string; type: "s2" | "arxiv" | "localfile"; } /** * Collections of data objects are stored in relational stores, comprising two properties: * * all: an ordered list of IDs of the objects * * byId: a map from IDs to objects * This lets us perform a constant-time lookup of an entity by its ID. Entities refer to other * entities using their IDs, rather than containing their data. This convention was adopted * from Redux. For rationale and best practices, see * https://redux.js.org/recipes/structuring-reducers/normalizing-state-shape */ export interface RelationalStore<T> { all: string[]; byId: { [id: string]: T }; } <file_sep>/ui/src/types/katex.d.ts /** * Only the subset of the KaTeX module and members that are used in the code are enumerated here. */ declare module "katex" { declare class ParseError {} /** * Contexts used to determine whether to trust HTML formatting of TeX. See types in * https://github.com/KaTeX/KaTeX/blob/80b0e3dc20c06e9aba6859a799049deed551639f/src/Settings.js#L19 */ type TrustContext = ClassTrustContext; interface ClassTrustContext { command: "\\htmlClass"; class: string; } } declare module "katex/dist/contrib/auto-render" { import katex from "katex"; /** * Automatically discover and render the LaTeX math formulas in an HTML element. A summary * of relevant options has been included below. See also the KaTeX documentation at * https://katex.org/docs/autorender.html#api. */ export default function renderMathInElement( element: HTMLElement, options: RenderOptions ); /** * Only the subset of options that used by the ScholarPhi code have been enumerated here. */ interface RenderOptions { /** * Delimiters indicating what parts of the text are LaTeX formulas. */ delimiters?: DelimiterSpec[]; errorCallback?: (message: string, error: katex.ParseError) => void; /** * Callback to preprocess math LaTeX before rendering it. */ preProcess?: (math: string) => string; /** * A mapping from macros to expansions. See example here: * https://github.com/KaTeX/KaTeX/issues/1801#issuecomment-445813146 */ macros?: { [macro: string]: string }; /** * Allow formatting that could cause security vulnerabilities. For example, permit the * direct specification of CSS classes using LaTeX macros. */ trust?: boolean | ((context: TrustContext) => boolean); } interface DelimiterSpec { /** * String pattern indicating the start of a formula. */ left: string; /** * String pattern indicating the end of a formula. */ right: string; /** * Whether these delimiters indicate that the formula should be shown as a display formula. */ display: boolean; } } <file_sep>/ui/src/api/api.ts import axios, { AxiosResponse } from "axios"; import cookie from "cookie"; import { Entity, EntityCreateData, EntityCreatePayload, EntityUpdateData, EntityUpdatePayload, Paper, Paginated, PaperIdWithEntityCounts, EntityGetResponse, Citation, Equation, Sentence, Symbol, Term, } from "./types"; import { Entity as DedupedEntity, DedupedEntityResponse, isCitation, isEquation, isSentence, isSymbol, isTerm, toLegacyRelationship } from "./deduped"; import { Nullable } from "../types/ui"; const token = cookie.parse(document.cookie)["readerAdminToken"]; const config = { headers: { Authorization: `Bearer ${token}` } }; export async function listPapers(offset: number = 0, size: number = 25) { return axios.get<Paginated<PaperIdWithEntityCounts>>( "/api/v0/papers/list", { params: { offset, size } } ); } /** * API request for paper details need to be batched as it seems that in production, * when more than around 50 paper Ids are requested at once, sometimes the API fails to respond. * @param s2Ids list of Ids of all the papers cited in this paper */ export async function getPapers(s2Ids: string[]) { const PAPER_REQUEST_BATCH_SIZE = 50; // Use a set to remove dupes const dedupeIds = [...new Set(s2Ids)]; // Use .reduce() to break into chunks const s2IdsBatch = dedupeIds.reduce((chunks, s2Id, index) => { const chunkIndex = Math.floor(index / PAPER_REQUEST_BATCH_SIZE); if (chunks[chunkIndex]) { chunks[chunkIndex].push(s2Id); } else { chunks[chunkIndex] = [s2Id]; } return chunks; }, [[]] as string[][]); // Await the results within the async function, use async function in map const results = await Promise.all(s2IdsBatch.map(async (s2Ids) => { const result = await doGet( axios.get<Paper[]>("/api/v0/papers", { params: { id: s2Ids.join(","), }, })); // ...process result return result || []; })); // Use `[].concat(...) to flatten array return ([] as Paper[]).concat(...results); } const ENTITY_API_ALL = 'all'; export async function getEntities(arxivId: string, getAllEntities?: boolean) { const params = getAllEntities ? { type: ENTITY_API_ALL } : {}; const data = await doGet( axios.get(`/api/v0/papers/arxiv:${encodeURIComponent(arxivId)}/entities`, { params }) ); return ((data as any).data || []) as Entity[]; } export async function getPaper(s2Id: string): Promise<Nullable<Paper>> { console.log("Getting paper....", s2Id); const data = await doGet( axios.get<Paper>(`/api/v0/paper/${encodeURIComponent(s2Id)}`, { })); return data; } // This translates from the entities-deduped API's response to the legacy // super-duplicated API response, as a compat shim. // TODO: phase this out in favor of using a more efficient data model in the reader app. function undedupeResponse(response: DedupedEntityResponse): EntityGetResponse { // TODO: Improve error handling; this just pulls the eject handle if the response is an API error if (!!(response as any).error) { throw "API error: " + (response as any).error; } const entities: Entity[] = response.entities.map((deduped: DedupedEntity) => { if (isCitation(deduped)) { const citation: Citation = { id: deduped.id, type: 'citation', attributes: { bounding_boxes: deduped.attributes.bounding_boxes, paper_id: deduped.attributes.paper_id, source: 'tex-pipeline', // hardcoded since most everything comes out of the tex pipeline tags: [], }, relationships: {}, }; return citation; } else if (isEquation(deduped)) { const equation: Equation = { id: deduped.id, type: 'equation', attributes: { bounding_boxes: deduped.attributes.bounding_boxes, source: 'tex-pipeline', // hardcoded since most everything comes out of the tex pipeline tags: [], tex: deduped.attributes.tex, }, relationships: {}, }; return equation; } else if (isSentence(deduped)) { const sentence: Sentence = { id: deduped.id, type: 'sentence', attributes: { bounding_boxes: deduped.attributes.bounding_boxes, source: 'tex-pipeline', // hardcoded since most everything comes out of the tex pipeline tags: [], tex: deduped.attributes.tex, tex_start: deduped.attributes.tex_start, tex_end: deduped.attributes.tex_end, text: deduped.attributes.text, }, relationships: {}, }; return sentence; } else if (isSymbol(deduped)) { // empty string is a safe default, there shouldn't be sharedSymbolData for empty string. const disambiguatedId = deduped.attributes.disambiguated_id || ''; const symbol: Symbol = { id: deduped.id, type: 'symbol', attributes: { bounding_boxes: deduped.attributes.bounding_boxes, source: 'tex-pipeline', // hardcoded since most everything comes out of the tex pipeline tags: [], tex: deduped.attributes.tex, type: deduped.attributes.type, mathml: deduped.attributes.mathml, mathml_near_matches: deduped.attributes.mathml_near_matches, diagram_label: deduped.attributes.diagram_label, is_definition: deduped.attributes.is_definition, nicknames: deduped.attributes.nicknames, definitions: response.sharedSymbolData[disambiguatedId]?.definitions || [], defining_formulas: response.sharedSymbolData[disambiguatedId]?.defining_formulas || [], passages: deduped.attributes.passages, snippets: response.sharedSymbolData[disambiguatedId]?.snippets || [], }, relationships: { equation: toLegacyRelationship( deduped.relationships.equation, 'equation' ), children: deduped.relationships.children.map( (c) => toLegacyRelationship(c, 'symbol') ), parent: toLegacyRelationship(deduped.relationships.parent, 'symbol'), sentence: toLegacyRelationship( deduped.relationships.sentence, 'sentence' ), nickname_sentences: deduped.relationships.nickname_sentences.map( (n) => toLegacyRelationship(n, 'sentence') ), defining_formula_equations: ( response.sharedSymbolData[disambiguatedId]?.defining_formula_equations || [] ).map((s) => toLegacyRelationship(s, 'equation')), definition_sentences: ( response.sharedSymbolData[disambiguatedId]?.definition_sentences || [] ).map((s) => toLegacyRelationship(s, 'sentence')), snippet_sentences: ( response.sharedSymbolData[disambiguatedId]?.snippet_sentences || [] ).map((s) => toLegacyRelationship(s, 'sentence')), }, }; return symbol; } else if (isTerm(deduped)) { const term: Term = { id: deduped.id, type: 'term', attributes: { bounding_boxes: deduped.attributes.bounding_boxes, name: deduped.attributes.name, source: 'tex-pipeline', // hardcoded since most everything comes out of the tex pipeline tags: [], term_type: deduped.attributes.term_type, definitions: deduped.attributes.definitions, definition_texs: deduped.attributes.definition_texs, sources: deduped.attributes.sources, snippets: deduped.attributes.snippets, }, relationships: { sentence: toLegacyRelationship( deduped.relationships.sentence, 'sentence' ), definition_sentences: ( deduped.relationships.definition_sentences || [] ).map((s) => toLegacyRelationship(s, 'sentence')), snippet_sentences: ( deduped.relationships.snippet_sentences || [] ).map((s) => toLegacyRelationship(s, 'sentence')), }, }; return term; } // There's a new kind of entity that hasn't been implemented in the UI. throw "Unknown entity type"; }); return { data: entities, }; } /** * This API returns a compacted representation of the paper's entities and their relationships. * Certain fields of Symbol entity data are pulled into a separate `sharedSymbolData` map, * which is organized by the Symbols' `attributes.disambiguated_id` value. * * NOTE: Currently, this function passes the response through a transform function to make * it compatible with the existing UI code. * * @param arxivId arXiv ID of the viewed paper * @param getAllEntities `true` retrieves entities of all types, `false` retrieves only citations * @returns */ export async function getDedupedEntities(arxivId: string, getAllEntities?: boolean) { const params = getAllEntities ? { type: ENTITY_API_ALL } : {}; const data = await doGet( axios.get<EntityGetResponse>( `/api/v0/papers/arxiv:${encodeURIComponent(arxivId)}/entities-deduped`, { params, //@ts-ignore -- TODO: this pattern works in other projects, is there a version issue somewhere? transformResponse: [].concat(axios.defaults.transformResponse).concat(undedupeResponse) } ) ); console.log(data); //added return data?.data || []; } export async function postEntity( arxivId: string, data: EntityCreateData ): Promise<Entity | null> { console.log("posted function"); //added try { const response = await axios.post( `/api/v0/papers/arxiv:${encodeURIComponent(arxivId)}/entities`, { data } as EntityCreatePayload ); if (response.status === 201) { return (response.data as any).data as Entity; } } catch (e) { console.error("Unexpected response from API for POST entity request.", e); } return null; } export async function patchEntity( arxivId: string, data: EntityUpdateData ): Promise<boolean> { const response = await axios.patch( `/api/v0/papers/arxiv:${encodeURIComponent(arxivId)}/entities/${encodeURIComponent(data.id)}`, { data } as EntityUpdatePayload, config ); if (response.status === 204) { return true; } console.error( "Unexpected response from API for PATCH entity request.", response ); return false; } export async function deleteEntity( arxivId: string, id: string ): Promise<boolean> { const response = await axios.delete( `/api/v0/papers/arxiv:${encodeURIComponent(arxivId)}/entities/${encodeURIComponent(id)}`, config ); if (response.status === 204) { return true; } console.error( "Unexpected response from API for DELETE entity request.", response ); return false; } /** * 'get' is a Promise returned by 'axios.get()' */ async function doGet<T>(get: Promise<AxiosResponse<T>>) { try { const response = await get; if (response.status === 200) { return response.data; } else { console.error(`API Error: Unexpected response ${response}`); } } catch (error) { console.error("API Error:", error); } return null; } <file_sep>/ui/src/selectors/index.ts /* * When designing selectors, selectors that will be run many times with the same arguments and * which might take some time to complete should be wrapped using the 'defaultMemoize' function * from 'reselect'. This function creates a copy of the selector function with a cache size of * one. See the 'matchingSymbols' function for an example. */ export * from "./annotation"; export * from "./entity"; export * from "./equation"; export * from "./symbol"; export * from "./term"; <file_sep>/ui/src/selectors/symbol.ts import { SymbolFilter } from "../components/search/FindBar"; import { Entities } from "../state"; import { isSentence, isSymbol, Relationship, Symbol } from "../api/types"; import { adjacentContext, adjacentDefinition, comparePosition, hasDefinition, inDefinition, orderByPosition, orderExcerpts, } from "./entity"; import { defaultMemoize } from "reselect"; export function diagramLabel( symbol: Symbol, entities: Entities, explicitLabelsOnly?: boolean ): string | null { if (symbol.attributes.diagram_label !== null) { if (symbol.attributes.diagram_label === "SKIP") { return null; } return symbol.attributes.diagram_label; } if (!explicitLabelsOnly) { const definition = nearbyDefinition(symbol.id, entities, true); return definition ? definition.excerpt : null; } return null; } export function isTopLevelSymbol(symbol: Symbol, entities: Entities) { return ( symbol.relationships.parent.id === null || entities.byId[symbol.relationships.parent.id] === undefined ); } /** * Get the descendants of this symbol. Descendants are returned in breadth-first order. For * example, the subscripts of the symbol will be returned before the subscripts of the subscripts. */ export function descendants(symbolId: string, entities: Entities): Symbol[] { const descendantsList: Symbol[] = []; const entity = entities.byId[symbolId]; const visit: Symbol[] = []; if (entity !== undefined && isSymbol(entity)) { visit.push(entity); } while (visit.length > 0) { const descendant = visit.shift() as Symbol; descendant.relationships.children .filter((c) => c.id !== null) .map((c) => entities.byId[c.id as string]) .filter((e) => e !== undefined) .filter(isSymbol) .forEach((s) => { descendantsList.push(s); visit.push(s); }); } return descendantsList; } export const symbolIds = defaultMemoize( (entities: Entities, from?: string[]) => { return entities.all .filter((eId) => isSymbol(entities.byId[eId])) .filter((id) => from === undefined || from.indexOf(id) !== -1); } ); /** * Get a list of IDs of all symbols that with similar MathML. Returned list of symbols will * be in the order the symbols appear in the document. MathML is used for matching rather than * TeX as MathML is more likely to yield precise matches, having been normalized by the backend. */ export function matchingSymbols( symbolIdOrIds: string | string[], entities: Entities, symbolFilters?: SymbolFilter[] ) { if (typeof symbolIdOrIds === "string") { return symbolsMatchingSingleSymbol(symbolIdOrIds, entities, symbolFilters); } else { const matchingSymbolIds = symbolIdOrIds .map((id) => symbolsMatchingSingleSymbol(id, entities, symbolFilters)) .flat(); const uniqueIds = matchingSymbolIds.reduce((dict, id) => { dict[id] = true; return dict; }, {} as { [id: string]: any }); return matchingSymbolIds.filter((id) => uniqueIds[id]); } } const symbolsMatchingSingleSymbol = defaultMemoize( (symbolId: string, entities: Entities, symbolFilters?: SymbolFilter[]) => { const symbol = entities.byId[symbolId] as Symbol; /* * Get ordered list of all symbols for sorting the matching symbols later. Sort all of the * symbols instead of sorting the matching symbols so that the sort can be run once for all * calls to this method and memoized. */ const orderedSymbolIds = orderByPosition(symbolIds(entities), entities); return orderedSymbolIds .map((sId) => entities.byId[sId]) .map((s) => s as Symbol) .filter((otherSymbol) => { if (otherSymbol.attributes.bounding_boxes.length === 0) { return false; } if ( otherSymbol.attributes.mathml === null || otherSymbol.attributes.mathml === "" ) { return false; } /* * If no filters were provided, or if no filters activated or deactivated, every match * returned by the backend is considered valid. */ if ( !symbolFilters || !symbolFilters.some((f) => f.active !== undefined) ) { return otherSymbol.attributes.mathml === symbol.attributes.mathml; } return symbolFilters.some( (f) => otherSymbol.attributes.mathml === f.symbol.attributes.mathml ); }) .map((s) => s.id); } ); /** * Determine if 'symbol1' is a child of 'symbol2'. */ export function isChild(symbol1: Symbol, symbol2: Symbol) { return symbol2.relationships.children.some((c) => c.id === symbol1.id); } /** * Determine if 'symbol1' is a descendant of 'symbol2'. */ export function isDescendant( symbol1: Symbol, symbol2: Symbol, entities: Entities ) { let parent: Relationship = symbol1.relationships.parent; while (parent && parent.id !== null) { const parentEntity = entities.byId[parent.id]; if (parentEntity !== undefined && isSymbol(parentEntity)) { if (parentEntity === symbol2) { return true; } parent = parentEntity.relationships.parent; } else { break; } } return false; } /** * Get a list of the unique MathML equations used in this set of symbols. Guaranteed to match the * order they were found when iterating through the list sequentially. Therefore if you sort the * the symbols, the MathML returned will match that sort order. */ export function symbolMathMls(symbolIds: string[], entities: Entities) { const uniqueMathMls: string[] = []; symbolIds.forEach((sId) => { const mathMl = (entities.byId[sId] as Symbol).attributes.mathml; if (mathMl !== null && uniqueMathMls.indexOf(mathMl) === -1) { uniqueMathMls.push(mathMl); } }); return uniqueMathMls; } export function definitionsAndNicknames( symbolIds: string[], entities: Entities ) { const symbols = symbolIds .map((id) => entities.byId[id]) .filter((e) => e !== undefined) .filter(isSymbol); const excerpts = symbols.map((s) => s.attributes.definitions).flat(); const contexts = symbols .map((s) => s.relationships.definition_sentences) .flat(); excerpts.push(...symbols.map((s) => s.attributes.nicknames).flat()); contexts.push( ...symbols.map((s) => s.relationships.nickname_sentences).flat() ); return orderExcerpts(excerpts, contexts, entities); } export function definingFormulas(symbolIds: string[], entities: Entities) { const symbols = symbolIds .map((id) => entities.byId[id]) .filter((e) => e !== undefined) .filter(isSymbol); const formulas = symbols.map((s) => s.attributes.defining_formulas).flat(); const contexts = symbols .map((s) => s.relationships.defining_formula_equations) .flat(); return orderExcerpts(formulas, contexts, entities); } /** * Get definition that appears right above an entity. (Don't include) * a definition where the entity appears. */ export function adjacentNickname( symbolId: string, entities: Entities, where: "before" | "after" ) { const symbol = entities.byId[symbolId]; if (symbol === undefined || !isSymbol(symbol)) { return null; } const { nicknames } = symbol.attributes; const contexts = symbol.relationships.nickname_sentences; if (nicknames.length === 0 || contexts.length === 0) { return null; } const ordered = orderExcerpts(nicknames, contexts, entities); const sentenceId = symbol.relationships.sentence.id; return adjacentContext(sentenceId, entities, ordered, where); } export function descendantHasDefinition(symbolId: string, entities: Entities) { return descendants(symbolId, entities).some((s) => hasDefinition(s.id, entities) ); } /** * Determine whether an underline should show for a symbol. An underline should show if * it's not selected, there's a definition for the symbol, it isn't in a definition, * and none of its ancestor symbols will be underlined. */ export function shouldUnderline(symbolId: string, entities: Entities) { const symbol = entities.byId[symbolId]; if ( symbol === undefined || !isSymbol(symbol) || !hasDefinition(symbolId, entities) || inDefinition(symbolId, entities) ) { return false; } let ancestorId = symbol.relationships.parent.id; while (ancestorId !== null) { const ancestor = entities.byId[ancestorId]; if (ancestor === undefined || !isSymbol(ancestor)) { break; } if (shouldUnderline(ancestor.id, entities)) { return false; } ancestorId = ancestor.relationships.parent.id; } return true; } /** * Get the first definition or nickname right before the appearance of the symbol, if * possible. If not possible, get the first definition or nickname right after the appearance * of the symbol. If 'includeThisAppearance' is set, the sentence that the symbol appears * will be returned, if it is a definition. */ export function nearbyDefinition( symbolId: string, entities: Entities, includeThisAppearance?: boolean ) { const symbol = entities.byId[symbolId]; if (symbol === undefined || !isSymbol(symbol)) { return null; } if (includeThisAppearance && inDefinition(symbol.id, entities)) { for (let i = 0; i < symbol.attributes.definitions.length; i++) { const context = symbol.relationships.definition_sentences[i]; if (context === undefined || context.id === null) { continue; } const sentence = entities.byId[context.id]; if (sentence === undefined || !isSentence(sentence)) { continue; } if ( sentence.id === symbol.relationships.sentence.id && symbol.attributes.definitions[i] !== undefined ) { return { excerpt: symbol.attributes.definitions[i], contextEntity: sentence, }; } } } const dBefore = adjacentDefinition(symbolId, entities, "before"); const nBefore = adjacentNickname(symbolId, entities, "before"); if (dBefore && nBefore) { return comparePosition(dBefore.contextEntity, nBefore.contextEntity) > 0 ? dBefore : nBefore; } if (dBefore) { return dBefore; } if (nBefore) { return nBefore; } const dAfter = adjacentDefinition(symbolId, entities, "after"); const nAfter = adjacentNickname(symbolId, entities, "after"); if (dAfter && nAfter) { return comparePosition(dAfter.contextEntity, nAfter.contextEntity) < 0 ? dAfter : nAfter; } if (dAfter) { return dAfter; } if (nAfter) { return nAfter; } return null; } /** * A summary of symbol data suitable for logging. This set of properties should * be fast to compute, comprising mostly of property accesses. */ export function symbolLogData(symbol: Symbol) { return { id: symbol.id, name: symbol.attributes.tex, numNicknames: symbol.attributes.nicknames.length, numDefinitions: symbol.attributes.definitions.length, numFormulas: symbol.attributes.defining_formulas.length, numUsages: symbol.attributes.snippets.length, numChildren: symbol.relationships.children.length, hasParent: symbol.relationships.parent.id !== null, pages: symbol.attributes.bounding_boxes.map((b) => b.page), }; } <file_sep>/ui/src/utils/ui.ts import { PDFPageProxy } from "pdfjs-dist/types/display/api"; import React from "react"; import { PageModel, Pages } from "../state"; import { BoundingBox } from "../api/types"; import { PDFPageView } from "../types/pdfjs-viewer"; import { Dimensions, Rectangle } from "../types/ui"; /* * Corresponds to the 'elevation' property of 'Paper' and 'Card' components from Material UI. * Can take on values of 0 to 24 inclusive. See * https://material.io/design/environment/elevation.html#elevation-in-material-design */ export const TOOLTIP_ELEVATION = 8; export function getMouseXY(event: React.MouseEvent) { const rect = event.currentTarget.getBoundingClientRect(); const x = event.clientX - rect.left; const y = event.clientY - rect.top; return { x, y }; } export function isKeypressEscape(event: React.KeyboardEvent | KeyboardEvent) { if ( event.key !== undefined && (event.key === "Esc" || event.key === "Escape") ) { return true; } if (event.keyCode !== undefined && event.keyCode === 27) { return true; } return false; } const PATTERN_NON_WORD_CHAR = /\W/; const PATTERN_WORD_CHAR = /\w/; const ELLIPSIS = "…"; /** * Truncates the provided text such that no more than limit characters are rendered and adds an * ellipsis upon truncation by default. If the text is shorter than the provided limit, the full * text is returned. * * This method was ported from Semantic Scholar's UI codebase. It's a UI * utility. * * @param {string} text The text to truncate. * @param {number} limit The maximum number of characters to show. * @param {boolean} withEllipis whether to include an ellipsis after the truncation, defaults to true * * @return {string} the truncated text, or full text if it's shorter than the provided limit. */ export function truncateText( text: string, limit: number, withEllipsis: boolean = true ): string { if (typeof limit !== "number") { throw new Error("limit must be a number"); } if (withEllipsis) { limit -= ELLIPSIS.length; } if (text.length > limit) { while ( limit > 1 && (!PATTERN_WORD_CHAR.test(text[limit - 1]) || !PATTERN_NON_WORD_CHAR.test(text[limit])) ) { limit -= 1; } if (limit === 1) { return text; } else { const truncatedText = text.substring(0, limit); return withEllipsis ? truncatedText + ELLIPSIS : truncatedText + "."; } } else { return text; } } /** * Find the parent element of a node matching a filter. */ export function findParentElement( node: Node, filter: (element: HTMLElement) => boolean ): HTMLElement | null { let parent: HTMLElement | null = node instanceof HTMLElement ? node : node.parentElement; while (parent !== null) { if (filter(parent)) { return parent; } parent = parent.parentElement; } return null; } /** * Get the page model (if any) that contains this node. */ export function getPageContainingNode( node: Node, pages: Pages ): PageModel | null { const pageElement = findParentElement( node, (e) => e instanceof HTMLDivElement && e.classList.contains("page") ); if (pageElement === null) { return null; } for (const page of Object.values(pages)) { if (page.view.div === pageElement) { return page; } } return null; } /** * Convert a bounding box in ratio coordinates to PDF coordinates (i.e., in points). In the PDF * coordinate system, 'top' is the number of points from the bottom of the page. */ export function convertBoxToPdfCoordinates(view: PDFPageView, box: Rectangle) { /* * Dimensions of the page in PDF coordinates are stored in a page's 'view' property. * To see how these coordinates get loaded from PDF metadata (specifically, the "ViewArea" * tags), see these two links: * * https://github.com/mozilla/pdf.js/blob/cd6d0894894c97264eca993b10d0d9faa02fa829/src/core/document.js#L177 * * https://github.com/mozilla/pdf.js/blob/cd6d0894894c97264eca993b10d0d9faa02fa829/src/core/obj.js#L522 * Also see information about the "ViewArea" tag in the PDF spec, "PDF 32000-1:2008", page 628. */ // const [pdfLeft, pdfBottom, pdfRight, pdfTop] = view.pdfPage.view; const pdfWidth = pdfRight - pdfLeft; const pdfHeight = pdfTop - pdfBottom; return { left: pdfLeft + box.left * pdfWidth, top: pdfBottom + (1 - box.top) * pdfHeight, width: box.width * pdfWidth, height: box.height * pdfHeight, }; } /** * Get the 'left', 'top', 'width', and 'height' CSS parameters for a paper annotation from a * bounding box for that annotation. The bounding box is expected to be expressed in * ratio coordinates (see the docstring for the BoundingBox type). The values returned will be * absolute pixel positions. The caller can optionally specify a scaling favor (scaleCorrection). * You shouldn't need to use it, though in past versions of this interface it was necessary to * correct subtle issues in the positioning of annotations. */ export function getPositionInPageView( pageView: PDFPageView, box: Rectangle, scaleCorrection?: number ) { scaleCorrection = scaleCorrection || 1; const pageDimensions = getPageViewDimensions(pageView); return { left: box.left * pageDimensions.width * scaleCorrection, top: box.top * pageDimensions.height * scaleCorrection, width: box.width * pageDimensions.width * scaleCorrection, height: box.height * pageDimensions.height * scaleCorrection, }; } /** * Get bounding boxes for all ranges in a text selection. Consecutive bounding boxes within a * range are merged together, if sufficiently close to each other. */ export function getBoundingBoxesForSelection( selection: Selection, pages: Pages ) { /* * Get bounding boxes of all selected ranges. */ const boxes: BoundingBox[] = []; for (let i = 0; i < selection.rangeCount; i++) { const range = selection.getRangeAt(i); /* * Find the page that contains this range. */ const page = getPageContainingNode(range.commonAncestorContainer, pages); /* * If a page was found, save bounding boxes for the selection, in ratio coordinates * relative to the page view 'div'. */ if (page !== null) { const { pageNumber } = page.view.pdfPage; const pageRect = page.view.div.getBoundingClientRect(); const rangeRects = range.getClientRects(); let lastBox = undefined; for (let i = 0; i < rangeRects.length; i++) { const rangeRect = rangeRects.item(i); if (rangeRect !== null) { /* * Compute dimensions for a new box. */ const left = (rangeRect.left - pageRect.left) / pageRect.width; const top = (rangeRect.top - pageRect.top) / pageRect.height; const width = rangeRect.width / pageRect.width; const height = rangeRect.height / pageRect.height; const right = left + width; const bottom = top + height; /* * If this box appears right after the last box and is vertically aligned * with the last box, merge it with the last box. This loop takes advantage of * how getClientRects() iterates over boxes in content order (see * https://drafts.csswg.org/cssom-view/#dom-range-getclientrects). */ let boxMergedWithPrevious = false; if (lastBox !== undefined) { const lastBoxRight = lastBox.left + lastBox.width; const lastBoxBottom = lastBox.top + lastBox.height; const SMALL_HORIZONTAL_DELTA = 0.01; // 1% of page width const SMALL_VERTICAL_DElTA = 0.01; // 1% of page height if ( left - lastBoxRight < SMALL_HORIZONTAL_DELTA && Math.abs(top - lastBox.top) < SMALL_VERTICAL_DElTA && Math.abs(bottom - lastBoxBottom) < SMALL_VERTICAL_DElTA ) { lastBox.width = right - lastBox.left; lastBox.top = Math.min(top, lastBox.top); lastBox.height = Math.max(bottom, lastBoxBottom) - lastBox.top; boxMergedWithPrevious = true; } } /* * Create a new bounding box if it couldn't be merged with the previous box. */ if (!boxMergedWithPrevious) { const box: BoundingBox = { left, top, width, height, page: pageNumber - 1, source: "human-annotation", }; boxes.push(box); lastBox = box; } } } } } return boxes; } /** * Call this function whenever you want to get the width and height of a pageView object from * PDF.js. This function avoids gotchas in computing the size of the page view. Width and * height are returned in pixels. */ export function getPageViewDimensions(pageView: PDFPageView): Dimensions { /* * Use the viewport width and height here, instead of the scroll width and height of the * pageView's <div/>. The reason is that the <div/> might increase in its width and height as * we add annotations to it, though the viewport should be set once and stay constant each * time that the page is rendered. */ return { width: pageView.viewport.width, height: pageView.viewport.height }; } /** * Get the page number for a PDFPageView of PDFPageProxy. While the page number used internally * by pdf.js starts at 1, the numbers used by this application start at 0, so this function * converts the pdf.js number to a 0-based number. */ export function getPageNumber(p: PDFPageView | PDFPageProxy) { if ((p as any).pdfPage !== undefined) { return (p as PDFPageView).pdfPage.pageNumber - 1; } else { return (p as PDFPageProxy).pageNumber - 1; } } /** * Programmatically trigger a click of a Material-UI button that makes it look like the button has * actually been clicked. This requires simulating a 'mousedown' event, which starts a background * 'ripple', followed by a 'mouseup' event. The ripple appears to last from the 'mousedown' event * until the 'mouseup' event, and must have some duration. The 'click' event, however, is dispatched * immediately so that the button click can be processed as soon as possible. */ export function simulateMaterialUiButtonClick(element: HTMLButtonElement) { const MOUSE_EVENT_OPTIONS = { cancelable: true, bubbles: true }; const mouseDownEvent = new MouseEvent("mousedown", MOUSE_EVENT_OPTIONS); const mouseUpEvent = new MouseEvent("mouseup", MOUSE_EVENT_OPTIONS); const clickEvent = new MouseEvent("click", MOUSE_EVENT_OPTIONS); /* * Start the ripple effect. */ element.dispatchEvent(mouseDownEvent); /* * Trigger the click as soon as possible. */ element.dispatchEvent(clickEvent); /* * The ripple will continue to expand until the 'mouseup' event is dispatched. For it to look * like the button has been pressed to a user, 'RIPPLE_TIME_MS' needs to be greater than 0, * and is most visually salient if it is more than 100 ms. */ const RIPPLE_TIME_MS = 200; setTimeout(() => { element.dispatchEvent(mouseUpEvent); }, RIPPLE_TIME_MS); } export function sortByFrequency(strings: string[]) { /* * Count up frequency of each item. */ const counts = strings.reduce((c, s) => { c[s] = (c[s] || 0) + 1; return c; }, {} as { [s: string]: number }); /* * Sort items by their frequency. */ const countsKeys = Object.keys(counts); const indexes = countsKeys.map((_, i) => i); indexes.sort((i1, i2) => { const s1 = countsKeys[i1]; const s2 = countsKeys[i2]; return counts[s2] - counts[s1]; }); return indexes.map((i) => countsKeys[i]); } /** * Join a list of strings into a text list, where strings are separated by commas with an * 'and' before the last string. */ export function joinStrings(strings: string[]) { if (strings.length === 0) { return ""; } if (strings.length === 1) { return strings[0]; } if (strings.length === 2) { return strings[0] + " and " + strings[1]; } if (strings.length > 2) { return ( strings.slice(0, strings.length - 1).join(", ") + ", and" + strings[strings.length - 1] ); } } export function getScrollCoordinates(element: HTMLElement) { return { scrollLeft: element.scrollLeft, scrollTop: element.scrollTop, scrollWidth: element.scrollWidth, scrollHeight: element.scrollHeight, clientWidth: element.clientWidth, clientHeight: element.clientHeight, }; } export function getElementCoordinates(element: HTMLElement) { return { offsetLeft: element.offsetLeft, offsetTop: element.offsetTop, clientWidth: element.clientWidth, clientHeight: element.clientHeight, }; } /** * TODO(andrewhead): Handle the case of arXiv publications that have multiple versions. How do we * make sure we're querying for the same version of paper data as the paper that was opened? */ export function extractArxivId(url: string): string | undefined { const matches = url.match(/arxiv\.org\/pdf\/(.*)(?:\.pdf)/) || []; return matches[1]; } <file_sep>/.github/ISSUE_TEMPLATE/entity-localization.md --- name: Entity Localization about: Report a problem in localizing entities title: '' labels: bug, entity-localization assignees: '' --- **Name this issue** Give this issue a name: ``` Entity Localization Bug: [Entity Type]. [Entity Description] [Problem] in paper [Paper ID] ``` *Example*: For example, if the pipeline fails to detect a citation "(Weld et al. 2010)" in arXiv paper "1811.12889", the name of this issue should be: ``` Entity Localization Bug: Citation. (Weld et al. 2010) not detected in arXiv paper 1811.12889 ``` **Assign labels** Assign this issue two labels, one for each of: 1. The entity type (`citation` or `symbols`) 2. The localization issue type (`missing-entity-detection` or `bad-entity-detection`) **Describe the bug** The body of this bug report must include: _Description_: Describe the issue in 1-2 sentences. Is an entity being mistakenly detected where there is none? Are we failing to detect an entity? _Screenshot_: A screenshot showing the entity localization issue in the Reader. _URL (optional)_: A URL to a live version of the Scholar Reader (i.e. an `https://s2-reader.apps.allenai.org` address) where the bug can be seen. _How to fix (optional)_: If you know how the pipeline or UI can be modified to fix this issue, provide a 1-2 sentence description here.
0c74d4c5952741e3f7ab12d0ee4dda74fb328d95
[ "YAML", "Markdown", "Python", "Text", "TypeScript", "Dockerfile" ]
30
TypeScript
talaugust/s2-simplify
56da3e183cd981c918e65d1eb3b304e423775148
a45f6da8ca10980ed0fbdbd83c76879ba50f15ff
refs/heads/master
<file_sep>// // CollectionViewCell.swift // realanime wallpapers // // Created by Amine on 3/2/20. // Copyright © 2020 Amine. All rights reserved. // import UIKit class CollectionViewCell: UICollectionViewCell { @IBOutlet weak var thumbnail: UIImageView! } <file_sep>// // ViewController.swift // realanime wallpapers // // Created by Amine on 3/2/20. // Copyright © 2020 Amine. All rights reserved. // import UIKit import SDWebImage class ViewController: UIViewController, UICollectionViewDataSource { @IBOutlet weak var CollectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() let screen = UIScreen.main.bounds let width = screen.width let layout = CollectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.minimumLineSpacing = 10 layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) layout.itemSize = CGSize(width: (width-20)/2, height: (width-20)/2) CollectionView.delegate = self as? UICollectionViewDelegate CollectionView.dataSource = self // Do any additional setup after loading the view. } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = CollectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell cell.thumbnail.sd_setImage(with: URL(string: "https://i.imgur.com/0AftTgP.jpg")) return cell } } <file_sep>// // data.swift // realanime wallpapers // // Created by Amine on 3/2/20. // Copyright © 2020 Amine. All rights reserved. // import Foundation struct data{ var img:String? var name:String? var isNew:Bool? var isPremium:Bool? }
157d14f9c29985b8e0acb5daf7862ee8811f8aa3
[ "Swift" ]
3
Swift
aminekarimii/realanimewallpapers-ios
9c5cd8ed3ef256b8d0f8060ff188bb99c086825d
219afaeec50eb1dfe1547f6288685be4ea14752f
refs/heads/main
<file_sep>package tutor3 import ( "context" "flag" "fmt" "log" "net/http" "os" "os/signal" "syscall" "time" "github.com/gorilla/mux" ) type app struct { router *mux.Router server *http.Server db DB addr string project string data string util string noAuth bool debug bool } func (a *app) serve() int { done := make(chan os.Signal, 1) signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) go func() { if err := a.server.ListenAndServe(); err != nil && err != http.ErrServerClosed { log.Fatalf("listen: %s\n", err) } }() log.Print("server started on ", a.addr) <-done log.Print("server stopping") ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer func() { cancel() log.Print("server stopped") }() if err := a.server.Shutdown(ctx); err != nil { log.Printf("server shutdown: %s", err) return -1 } return 0 } func (a *app) createClient() (err error) { a.db, err = NewClient(a.project, a.data, a.util) return } func (a *app) makeServer() { a.server = &http.Server{ Addr: a.addr, Handler: a.router, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second, ReadHeaderTimeout: 20 * time.Second, } } func (a *app) addRoutes() { a.router.Use(logRequest) if a.noAuth { log.Println("AUTH DISABLED") } else { a.router.Use(basicAuth) } a.router.HandleFunc("/items", a.list).Methods("GET") a.router.HandleFunc("/items", a.add).Methods("POST") a.router.HandleFunc("/items/{id}", a.get).Methods("GET") a.router.HandleFunc("/items/{id}", a.put).Methods("PUT") a.router.HandleFunc("/items/{id}", a.drop).Methods("DELETE") a.router.HandleFunc("/skus", a.listSKU).Methods("GET") a.router.HandleFunc("/skus/{sku:[0-9]+}", a.getSKU).Methods("GET") } func (a *app) fromArgs(args []string) error { fl := flag.NewFlagSet("service", flag.ContinueOnError) fl.StringVar(&a.addr, "addr", "localhost:8080", "server address") fl.StringVar(&a.project, "proj", "tutor-dev", "GCP project") fl.StringVar(&a.data, "data", "items", "FS data collection") fl.StringVar(&a.util, "util", "util", "FS util collection") fl.BoolVar(&a.debug, "debug", false, "enable debugging") fl.BoolVar(&a.noAuth, "no-auth", false, "disable auth") if err := fl.Parse(args); err != nil { return err } return nil } func (a *app) listRoutes() { visit := func(route *mux.Route, _ *mux.Router, _ []*mux.Route) error { t, err := route.GetPathTemplate() if err != nil { return err } m, err := route.GetMethods() if err != nil { return err } log.Println("route", t, m) return nil } if err := a.router.Walk(visit); err != nil { fmt.Fprintln(os.Stderr, err) } } func RunApp(args []string) int { a := app{router: mux.NewRouter()} if err := a.fromArgs(args); err != nil { fmt.Fprintln(os.Stderr, err) return -2 } if err := a.createClient(); err != nil { fmt.Fprintln(os.Stderr, err) return -2 } a.makeServer() a.addRoutes() if a.debug { a.listRoutes() } return a.serve() } <file_sep># web-tutorial This repo holds the draft tutorial and the example files - [Tutorial](docs/building-a-server.md) - [Code v1 - Basics](tutor) - [Code v2 - Using Firestore](tutor2) - [Code v3 - Firestore transactions](tutor3) - [Code v4 - GraphQL](tutor4) This draft does not (yet) reflect the changes to use [dockertest](https://github.com/ory/dockertest) to run the Firestore emulator <file_sep># Building a web server Let's start with the simplest possible web server in Go: ```go package main import ( "fmt" "log" "net/http" ) func hello(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, web!") } func main() { http.HandleFunc("/", hello) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` The call to `http.ListenAndServe()` starts a server on the indicated address; it normally does not return unless an error occurs, which we'll log. We must indicate how the server should respond to a particular _route_, which is the part of the URL after the hostname. Here we assign a single route `/` (which is basically any and every query) using a handler `hello()`. Routes are managed by a _router_ which here is built into the standard library's HTTP package. Every handler takes two parameters: - a `ResponseWriter` which is used to send the response - the incoming `Request` send by the client/browser Note that the handler doesn't return anything; any error must be indicated by sending a particular HTTP status and/or message through the `ResponseWriter`. We can exercise this server using [`curl`](https://curl.haxx.se/book.html): ``` $ curl http://localhost:8080 Hello, web! ``` We'll be using `curl` as well as [`jq`](https://stedolan.github.io/jq/) throughout this tutorial. ## Routes, middleware, and building out the app First, create a project for this part of the tutorial: ``` $ mkdir tutor $ cd tutor $ go mod init tutor ``` ### Routing We're going to introduce a very important 3rd-party library right off, [Gorilla mux](https://github.com/gorilla/mux). Gorilla mux will replace the standard router and make a lot of things easier. For example, with the standard library, if we want to allow a route to be accessed only with the GET HTTP method, we'd have to write something like this: ```go func hello(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { http.Error(w, "Method not allowed", http. StatusMethodNotAllowed) return } fmt.Fprintln(w, "Hello, web!") } ``` **Note**: any time we set an error, we must remember to return from the function early, and avoid sending non-error responses by accident. Now, using Gorilla mux, we can let the router solve that problem for us: ```go func main() { router := mux.NewRouter() router.HandleFunc("/", hello) log.Fatal(http.ListenAndServe(":8080", router)) } ``` In this case, we create a router, add routes to it, and pass that router to the `ListenAndServe` call. This code allows any HTTP method to access `/`, but a one-line change can fix that: ```go router.HandleFunc("/", hello).Methods(http.MethodGet) ``` In this case, only the GET method can access `/`; other methods will get a 404 response. An HTTP router works by pattern matching: it takes into account both the route, e.g., `/` or `/list` as well as the method(s). The same route may be assigned two different handlers if their allowed methods differ: ```go router.HandleFunc("/", hello).Methods(http.MethodGet) router.HandleFunc("/", goodbye).Methods(http.MethodPost) ``` Also, routes are evaluated in the order they're installed into the router. Gorilla mux allows variable matching in a route ```go router.HandleFunc("/list/{item}", list) ``` which we'll see more in a bit. But we can match a fixed value before the variable: ```go router.HandleFunc("/list/all", listAll) router.HandleFunc("/list/{item}", list) ``` If these two lines were reversed, "all" would always be picked up by the variable match and `listAll()` wouldn't be called. ```go package main import ( "fmt" "log" "net/http" "github.com/gorilla/mux" ) func list(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) item := vars["item"] // we don't need this code; it the variable isn't // provided (e.g., /db/) it won't match the route // // if item == "" { // http.Error(w, "No item", http.StatusNotFound) // return // } fmt.Fprintln(w, "the item is", item) } func main() { router := mux.NewRouter() router.HandleFunc("/db/{item}", list) log.Fatal(http.ListenAndServe(":8080", router)) } ``` Let's try this: ``` $ curl http://localhost:8080/db/a the item is a $ curl http://localhost:8080/db/ 404 page not found ``` where the 404 error message is returned from the router on our behalf. We'll now use separate methods for the route: ```go func enter(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) item := vars["item"] fmt.Fprintln(w, item, "has been posted") } func main() { router := mux.NewRouter() router.HandleFunc("/db/{item}", list).Methods(http.MethodGet) router.HandleFunc("/db/{item}", enter).Methods(http.MethodPost) log.Fatal(http.ListenAndServe(":8080", router)) } ``` with the results ``` $ curl http://localhost:8080/db/1 the item is 1 $ curl http://localhost:8080/db/1 -X POST 1 has been posted ``` We can also use URL arguments, e.g, `/db/XYZ?key=12` by reading a form value: ```go func list(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) item := vars["item"] key := r.FormValue("key") if key != "" { fmt.Fprintln(w, "the item is", item, "and the key is", key) } else { fmt.Fprintln(w, "the item is", item, "(no key)") } } ``` which we can test ``` $ curl http://localhost:8080/db/XYZ the item is XYZ (no key) $ curl http://localhost:8080/db/XYZ?key=1 the item is XYZ and the key is 1 ``` ### Middleware _Middleware_ in the context of a web server is any function that's put between the router and the handlers. Any such function gets called on every request and gets a chance to modify how it's handled. For example, we can log every request by adding logging middleware: ```go func logRequest(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Println(r.Method, r.RequestURI) next.ServeHTTP(w, r) }) } func main() { router := mux.NewRouter() router.Use(logRequest) // installs middleware router.HandleFunc("/db/{item}", list).Methods(http.MethodGet) router.HandleFunc("/db/{item}", enter).Methods(http.MethodPost) log.Fatal(http.ListenAndServe(":8080", router)) } ``` There are some important details here: - the middleware function is a handler, taking the same request and response parameters - the middleware function is also a closure taking a "next" handler - the middleware function does it's work before or after calling that "next" handler If the next handler isn't called, the request won't be handled any further, which could be useful it the middleware is used to handle authentication. Now it's worth pointing out that a "handler" in Go is really something that implements an interface: ```go type Handler interface { ServeHTTP(ResponseWriter, *Request) } type HandlerFunc func(ResponseWriter, *Request) func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) { f(w, r) } ``` where the `HandlerFunc` type is just a way to take a regular function and allow that function to be called through the `ServeHTTP` method. Anyway, the result of installing the `logRequest()` middleware is that we now see logs where we run the server: ``` $ go run main.go 2020/09/27 20:23:14 GET /db/XYZ?key=1 2020/09/27 20:23:19 GET /db/a . . . ``` HTTP has a very simple name and password authentication method (that's not very secure) called [basic authentication](https://en.wikipedia.org/wiki/Basic_access_authentication). If we enable it, every request will need to have a special header with the name and password combined using base64 encoding. The header looks like `Authorization: Basic YWRtaW46c2VjcmV0`. There's no cryptography involved, so in real life HTTPS is required to have any security with this method at all. It's trivial to "decode" this: ``` $ echo -n YWRtaW46c2VjcmV0 | base64 -D admin:secret ``` We'll add another bit of middleware to check for basic auth: ```go func basicAuth(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user, pass, ok := r.BasicAuth() if !ok || user != "admin" || pass != "<PASSWORD>" { w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`) http.Error(w, "Unauthorized", http.StatusUnauthorized) return } next.ServeHTTP(w, r) }) } ``` Now the `Request` object has a method that allows us to get the name and password (or tell that they weren't there). Also note that if the name and password are wrong, the handler stops the request and returns an error. Now we'll need to have curl pass the secret handshake, or else: ``` $ curl http://localhost:8080/db/a -w "%{http_code}\n" Unauthorized 401 $ curl http://localhost:8080/db/a -w "%{http_code}\n" --user admin:secret the item is a (no key) 200 ``` See how we've provided the `-w` argument to curl to print the HTTP status code. Alternatively, we could see all the response headers with ``` $ curl http://localhost:8080/db/a -i HTTP/1.1 401 Unauthorized Content-Type: text/plain; charset=utf-8 Www-Authenticate: Basic realm="Restricted" X-Content-Type-Options: nosniff Date: Mon, 28 Sep 2020 02:33:08 GMT Content-Length: 13 Unauthorized ``` but that's not always as convenient. ### Improving the app structure First, let's point out a pair of articles that are guiding us: - [_How I Write HTTP Services After Eight Years_](https://pace.dev/blog/2018/05/09/how-I-write-http-services-after-eight-years.html) by <NAME> (which was also a talk at [GopherCon 2019](https://www.youtube.com/watch?v=rWBSMsLG8po)) - [_Writing Go CLIs With Just Enough Architecture_](https://blog.carlmjohnson.net/post/2020/go-cli-how-to-and-advice/) by <NAME> The first discusses some thoughts about structuring handlers and middleware and how to make the web server testable. The second is about how to structure the application that starts web service (the part that, for example, takes command-line arguments). Proper structure also helps make the server testable. What we want is to build a `main()` function that does one thing: ```go func main() { os.Exit(runApp(os.Args[1:])) } ``` This is very reminiscent of the Python style of main program: ```python if __name__ == "__main__": main() ``` which allows the real "main" function to be called from anywhere, for example, from a unit test. We'd like to be able to write a test like this one: ```go func TestServer(t *testing.T) { args := []string{"-addr", "localhost:8089"} go runApp(args) client := http.Client{} req, _ := http.NewRequest("GET", "http://localhost:8089/db/xyz", nil) req.SetBasicAuth("admin", "<PASSWORD>") resp, err := client.Do(req) if err != nil { t.Fatal(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { t.Fatal(err) } result := strings.TrimSpace(string(body)) if result != "the item is xyz (no key)" { t.Errorf("invalid response: %v", body) } } ``` Here we run the "main" function `runApp()` with some parameters we pass in (without using the command line); it's in a goroutine so we can continue on with the client code to test the server. We create an HTTP client instead of using `http.Get()` because we need to create a separate HTTP request in order to add the basic auth header. We get the response, read the entire body at once and make it into a string that we can compare to. Note that we're fully starting up the server which will register itself on a network port we've picked. There's a risk to this; the test will fail if some other process on our machine is using port 8089 at the same time. Later we'll see a way to avoid this. The next step is to create `runApp()`. For now, we'll do something like this: ```go func runApp(args []string) int { var a app if err := a.fromArgs(args); err != nil { fmt.Fprintln(os.Stderr, err) return -2 } return a.runServer() } ``` Now, most of our code will be methods on `app` such as `runServer()`, so we need to create it: ```go type app struct { addr string server *http.Server } ``` The `app` class is a great place to put all our dependencies as well as any parameters that we'll set up with flags. Let's go ahead and process those flags: ```go func (a *app) fromArgs(args []string) error { fl := flag.NewFlagSet("service", flag.ContinueOnError) fl.StringVar(&a.addr, "addr", "localhost:8080", "server address") if err := fl.Parse(args); err != nil { return err } return nil } ``` Later we'll see how to use a 3rd-party library to allow configuration by environment variables or flags. Using environment variables is part of building a good ["twelve-factor app"](https://12factor.net) (see also this [Wikipedia entry](https://en.wikipedia.org/wiki/Twelve-Factor_App_methodology)). For now, we'll use flags to make it easy to run the tutorial on the desktop. Most of what went into `main()` before will now appear in `runServer()`. ```go func (a *app) runServer() int { router := mux.NewRouter() router.Use(logRequest) router.Use(basicAuth) router.HandleFunc("/db/{item}", list).Methods(http.MethodGet) router.HandleFunc("/db/{item}", enter).Methods(http.MethodPost) a.server = &http.Server{ Addr: a.addr, Handler: router, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second, ReadHeaderTimeout: 20 * time.Second, } return a.serve() } ``` Note that we're also now following a best practice to set timeouts for the server as a whole. Finally, we can start with a basic service function: ```go func (a *app) serve() int { if err := a.server.ListenAndServe(); err != nil { fmt.Fprintf(os.Stderr, "listen: %s\n", err) return -1 } } ``` However, we can build a better function that allows the server to shut down gracefully (e.g., on receiving an interrupt). Here we'll also run the server in a goroutine while waiting on a channel to handle the signal. We allow 5 seconds for existing requests to finish. ```go func (a *app) serve() int { done := make(chan os.Signal, 1) signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) go func() { err := a.server.ListenAndServe() if err != nil && err != http.ErrServerClosed { log.Fatalf("listen: %s\n", err) } }() log.Print("server started on ", a.addr) <-done log.Print("server stopping") ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer func() { cancel() log.Print("server stopped") }() if err := a.server.Shutdown(ctx); err != nil { log.Printf("server shutdown: %s", err) return -1 } return 0 } ``` So now, the server output looks like: ``` 2020/09/27 21:26:10 server started on localhost:8080 2020/09/27 21:26:16 GET /db/a 2020/09/27 21:26:25 GET /db/XYZ?key=1 . . . 2020/09/27 21:26:38 server stopping 2020/09/27 21:26:38 server stopped ``` assuming we did a `kill` on the server's process ID (PID), e.g. ``` $ ps -ef|grep go 501 77510 35842 0 9:26PM ttys001 0:00.00 grep go 501 77490 35950 0 9:26PM ttys002 0:00.38 go run main.go 501 77506 77490 0 9:26PM ttys002 0:00.01 /var/folders/18/7d1ff7d550scc5v76sj1y0gh0000gn/T/go-build651932460/b001/exe/main $ kill 77506 ``` where we want to kill the _child_ of `go run` which is the actual server program. Before we move on, there's one last thing we want to show, which is using middleware to provide a timeout on handlers. Let's define a slow handler, e.g. ```go func slow(w http.ResponseWriter, r *http.Request) { time.Sleep(6 * time.Second) fmt.Fprintln(w, "slow response") } ``` and some middleware using another Go utility ```go func (a *app) withDeadline(next http.Handler) http.Handler { return http.TimeoutHandler(next, a.timeout, "Timeout\n") } ``` assuming we've added another parameter to the app ```go type app struct { addr string server *http.Server timeout time.Duration } ``` and in our startup, we're using that middleware ```go router.Use(a.withDeadline) router.HandleFunc("/slow", slow) ``` Now, if we try that slow route, we'll get an error ``` $ curl -s http://localhost:8080/slow -i --user admin:secret HTTP/1.1 503 Service Unavailable Date: Mon, 28 Sep 2020 03:31:17 GMT Content-Length: 8 Content-Type: text/plain; charset=utf-8 Timeout ``` Note that we could also choose to apply the middleware only to a specific handler instead of the whole server: ```go router.Handle("/slow", a.withDeadline(http.HandlerFunc(slow))) ``` ## Using Firestore In this next section, we'll add support for reading and writing to Google's [Firestore](https://cloud.google.com/firestore) database. We'll also talk about how to build a "real" REST server. ### Installing the emulator For the rest of this tutorial we'll be using Google's Firestore emulator and not the real database in the cloud. You still must have a Google account to use it, because it relies on the `gcloud` tool. You’ll need Java 8+ in order to run Google’s Firestore emulator on your laptop. Go to [https://www.oracle.com/java/technologies/javase/javase-jdk8-downloads.html](https://www.oracle.com/java/technologies/javase/javase-jdk8-downloads.html) and download the file `jdk-8u251-macosx-x64.dmg`. (You must create an account to do this.) Open the disk image and copy the installer to your actual disk so you can "fix" it for Catalina. Once the installer is copied, run ``` $ xattr -d com.apple.quarantine <path/to/installer> ``` and then you should be able to run the installer. When complete, you should be able to check your work: ``` $ java -version java version "1.8.0_251" Java(TM) SE Runtime Environment (build 1.8.0_251-b08) Java HotSpot(TM) 64-Bit Server VM (build 25.251-b08, mixed mode) ``` In order to run the emulator, Google will also want to download the "beta" command set as well as the emulator. Use ``` $ gcloud beta emulators firestore start --host-port localhost:8086 ``` after which you’ll be prompted twice, once for the beta commands, and once for the emulator. When the emulator runs, you'll see output like this ``` $ gcloud beta emulators firestore start --host-port=localhost:8086 Executing: /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/cloud-firestore-emulator/cloud_firestore_emulator start --host=localhost --port=8086 [firestore] API endpoint: http://localhost:8086 [firestore] If you are using a library that supports the FIRESTORE_EMULATOR_HOST environment variable, run: [firestore] [firestore] export FIRESTORE_EMULATOR_HOST=localhost:8086 [firestore] [firestore] Dev App Server is now running. [firestore] . . . ``` In the shell where you'll run the server, you must do ``` $ export FIRESTORE_EMULATOR_HOST=localhost:8086 ``` and then Google's Firestore library for Go will "magically" find the emulator and not try to contact a real database in the cloud. Later, we'll see how to make the emulator run as part of unit tests. ### Reading and writing In this first section, we'll build out just enough to create and list some type of item in our database. To do that, we'll need to set up a DB client and make it available to our server. We're going to define an interface for all our database functions so that later we can mock the entire database. For now, the Item we'll manage is going to be very simple: a name and some unique ID (a UUID). ```go type Item struct { ID string `json:"id" firestore:"id"` Name string `json:"name" firestore:"name"` } type DB interface { AddItem(context.Context, *Item) (string, error) GetItem(context.Context, string) (*Item, error) ListItems(context.Context) ([]*Item, error) UpdateItem(context.Context, *Item) error DeleteItem(context.Context, string) error } ``` Note that we add struct tags for Firestore so that the database uses the same JSON keys as we use for actual JSON encoding. Next, we're going to create the client we'll use to access the DB. Firestore is a document-based database with _collections_ as a tool to group like kinds of documents. Firestore's documents can be thought of as JSON objects; the properties are the fields of whatever struct (record) we're storing. Firestore is a schema-less database: there is no explicit schema for a collection, but rather documents in a collection need not have all the same properties. Schema-less is flexible but not always safe (in the sense of maintaining data integrity). To access a database, we must name a GCP project (although with the emulator, it can be anything, and need not match any actual project in the cloud). We will also capture the collection name in which we'll store our items. ```go import ( "context" "errors" "fmt" "log" "cloud.google.com/go/firestore" "github.com/google/uuid" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) type Client struct { fs *firestore.Client data *firestore.CollectionRef } ``` ```go func NewClient(project, collection string) (*Client, error) { if project == "" { return nil, errors.New("no projectID") } ctx := context.Background() client, err := firestore.NewClient(ctx, project) if err != nil { return nil, fmt.Errorf("failed to create FS client: %w", err) } c := Client{ fs: client, data: client.Collection(collection), } return &c, nil } func (c *Client) Close() { c.fs.Close() } ``` Once we've run `NewClient()` we're ready to access the database and the documents in our collection. Note that we don't "create" the collection; it's created implicitly when we store the first item. (Operations that actually communicate to the database all take a `Context` parameter; thus, "making" the collection object we add to our client object is not such an operation.) We'll start just creating items and listing them. Feel free to remove some of the `DB` interface methods we won't implement just yet; we'll add them back in a bit. First, we need to create items: ```go func (c *Client) AddItem(ctx context.Context, i *Item) (string, error) { id := uuid.New().String() ref := c.data.Doc(id) i.ID = id // store it, so the caller can see it here too if _, err := ref.Create(ctx, i); err != nil { return "", err } return id, nil } ``` Firestore requires the document's "ID" (which doesn't have to be a field, or be named "ID") to be unique. We create a UUID and use that to make a _document reference_ against our collection, and the use that reference to create the actual document, with the contents of our item. Firestore will use its own serialization of the object to send it to the database. By using `Create()` we tell Firestore that we're making a new document; it's then an error if the ID (the UUID, here) already exists in that collection. (Later we'll use `Set()` to perform updates.) We could try again if we get a UUID we've already seen, with a simple `goto`: ```go func (c *Client) AddItem(ctx context.Context, i *Item) (string, error) { var ref *firestore.DocumentRef add: i.ID = uuid.New().String() ref = c.data.Doc(i.ID) if _, err := ref.Create(ctx, i); err != nil { // it's unlikely to happen once and virtually // impossible for it to happen twice in a row if status.Code(err) == codes.AlreadyExists { goto add } return "", err } return i.ID, nil } ``` Again, an operation that communicates with the database takes a `Context` and returns a possible error; "making" the document ref is local to our app just as making the UUID value. To list all the objects, we'll execute a Firestore query on the collection, asking it to order all documents by their ID. (Only when we fetch the documents is the query actually sent to the database.) Note that the query may return no documents without signaling an error. ```go func (c *Client) ListItems(ctx context.Context) ([]*Item, error) { query := c.data.OrderBy(firestore.DocumentID, firestore.Asc) docs, err := query.Documents(ctx).GetAll() if err != nil { return nil, err } result := make([]*model.Item, 0, len(docs)) for _, doc := range docs { var i Item if err = doc.DataTo(&i); err != nil { log.Printf("item %s decode: %s", doc.Ref.ID, err) continue } result = append(result, &i) } return result, nil } ``` The "document" returned by the query hasn't yet been deserialized; that what the call to `DataTo()` is doing. ### Making handlers to create and list Now that we've got a couple of database operations, let's add that functionality into our server. We're going to dispense with authentication for the rest of the tutorial for convenience, and remove the "slow" route we used to demonstrate timeouts. We're also going to refactor up how we configure the app so that we can support another style of unit tests at the end of this section. Let's start with the `list()` handler. But first, we're going to need to create the client on the app. ```go type app struct { router *mux.Router server *http.Server db DB addr string project string collection string } ``` And then we'll need to set up the parameters ```go func (a *app) fromArgs(args []string) error { fl := flag.NewFlagSet("service", flag.ContinueOnError) fl.StringVar(&a.addr, "addr", "localhost:8080", "server address") fl.StringVar(&a.project, "proj", "tutor-dev", "GCP project") fl.StringVar(&a.collection, "coll", "items", "FS collection") if err := fl.Parse(args); err != nil { return err } return nil } ``` and create and install the client into the app ```go func (a *app) createClient() (err error) { a.db, err = NewClient(a.project, a.collection) return } ``` ```go func RunApp(args []string) int { a := app{router: mux.NewRouter()} if err := a.fromArgs(args); err != nil { fmt.Fprintln(os.Stderr, err) return -2 } if err := a.createClient(); err != nil { fmt.Fprintln(os.Stderr, err) return -2 } . . . } ``` Now that we've done that, we can make the "list" handler a method and get access to dependencies such as the DB client through the app. So we'll right something like ```go func (a *app) list(w http.ResponseWriter, r *http.Request) { . . . } ``` and install it as ```go a.router.HandleFunc("/list", a.list) ``` Here `a.list` is a _method value_ (or _method closure_) which is the method with a receiver object already selected. As a result, it now has the function signature of a `HandlerFunc`, because `a` is already bound. It's very important that `app.list()` take a **pointer** receiver. A method value that takes a pointer receiver keeps the address of the object, much like a normal closure: it will access the current value in memory. By contrast, if we had defined `app.list()` to take `a` by value, the method value would contain a **copy** of `a` (made when we created the server!) which might be bad. Let's now fill in the body: ```go func (a *app) list(w http.ResponseWriter, r *http.Request) { items, err := a.db.ListItems(r.Context()) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") if err = json.NewEncoder(w).Encode(items); err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintln(w, err) return } } ``` All our handlers are going to be reading and writing JSON in the HTTP body; it's how we pass in data or return it to the client. In this case, if the list is empty, we'll return an empty JSON array `[]`. Note that we create the JSON encoder on the `ResponseWriter` directly. Also note the "extra" return if JSON encoding fails. It's too easy to add more code to the handler later at the bottom of the method, and forget to come back and add a return to the error-handling block; just do it now. To create objects, we'll add a `create` handler. It will decode JSON from the body of the request and use that to pass an item to the DB client's `AddItem()` method. ```go func (a *app) add(w http.ResponseWriter, r *http.Request) { var item Item err := json.NewDecoder(r.Body).Decode(&item) if err != nil || item.Name == "" { http.Error(w, "Invalid input", http.StatusBadRequest) return } id, err := a.db.AddItem(r.Context(), &item) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") if err = json.NewEncoder(w).Encode(item); err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintln(w, err) return } } ``` We must also add these routes into our router: ```go a.router.HandleFunc("/list", a.list).Methods(http.MethodGet) a.router.HandleFunc("/create", a.add).Methods(http.MethodPost) ``` So now we're in a position to give it a test. We'll create a couple of items, and then list them out again. Note how we send data through `curl`; don't forget the single quotes around JSON on the command line. (To be completely correct, we should be setting `-H 'Content-Type: application/json'` but that's not critical here). ``` $ curl http://localhost:8080/create -X POST --data '{"name":"spoon"}' {"id":"b34825af-bc2f-4ebb-84f8-0a1d082f9823","name":"spoon"} $ curl http://localhost:8080/create -X POST --data '{"name":"spork"}' {"id":"92d4a080-348e-4ef7-8ec3-80ba008ccd68","name":"spork"} ``` ```js $ curl -s http://localhost:8080/list | jq [ { "id": "92d4a080-348e-4ef7-8ec3-80ba008ccd68", "name": "spork" }, { "id": "b34825af-bc2f-4ebb-84f8-0a1d082f9823", "name": "spoon" } ] ``` When listing, we pass the data to `jq` to pretty-print it (we could also use `jq` for various filtering or transforming operations). We pass the `-s` option to curl so that it doesn't print stats to `stderr` while piping the data to `jq`. ### REST for real [REST](https://en.wikipedia.org/wiki/Representational_state_transfer) (Representational State Transfer) has a very specific meaning; it's not just handling any URLs from non-browser applications. For example, many people think the type of interface we've shown above (with `/list` and `/create` routes) is RESTful, but it's really not. (By the way, <NAME>'s [PhD thesis](https://www.ics.uci.edu/~fielding/pubs/dissertation/fielding_dissertation.pdf), in which he invented REST, is one of a very few theses that have really changed the world.) In REST, URLs are nouns and HTTP methods are the (only) verbs. That is, we use the URL to identify an object and the HTTP method to identify what we're going to do with it. Pure REST is often tied to the acronym CRUD, which stands for Create, Retrieve, Update, and Delete, the four basic operations we can perform on database entries. REST is essentially stateless, and thus it's best suited for database operations. GET is expected to return data without making any changes, thus, it is _idempotent_ (it can be run one or many times with the same result). POST creates data, PUT changes it, and DELETE removes it. DELETE should also be idempotent, but POST and PUT typically aren't. Here's how they map: |Method |Collection: /items |Item: /items/{id} | |:------|:-------------------|:----------------------------| |GET | retrieve all | retrieve (200) | |POST | create (201) or 409 (if ID exists) | | |PUT | | update (200) | |DELETE | | delete (200) | where the item-based GET and PUT return 404 if the ID is not known, while POST returns 409 if it is already known. Ideally, there's no reason for DELETE to fail; if the ID isn't in the database, it still won't be (i.e., just like deleting keys from a Go map). The main limitation of REST is that sometimes we don't just want to update data, but we want to make things happen. In a REST model, we can only do that by issuing PUT requests with data changes that imply a state change (think of setting a light's state to "on" or "off"). That doesn't work as well if we want our server to convert sound files on the fly, as opposed to store information about what CDs are in our library. ### Adding more DB methods Before we can perform all these operations, we're going to need some additional DB client methods. Let's start with getting an item by its ID. We again get a document reference on the collection and immediately get its data. We're going to add some special error-handling logic: if Firestore returns a specific status code, it means the document didn't exist, and we'll create a Go 1.13-style wrapped error to return (we'll see how to use this in just a bit). Otherwise, we deserialize the item and return it. ```go var ErrNotFound = errors.New("not found") func (c *Client) GetItem(ctx context.Context, id string) (*Item, error) { doc, err := c.data.Doc(id).Get(ctx) if err != nil { if status.Code(err) == codes.NotFound { return nil, fmt.Errorf("item %s: %w", id, ErrNotFound) } return nil, fmt.Errorf("item %s: %w", id, err) } var i Item if err = doc.DataTo(&i); err != nil { return nil, fmt.Errorf("item %s decode: %w", id, err) } return &i, nil } ``` Next, let's update an item. We need to try to get it to see if it actually exists in the collection, otherwise we have an error. ```go func (c *Client) UpdateItem(ctx context.Context, i *Item) error { ref := c.data.Doc(i.ID) // set can create or overwrite existing data // so we need to see if it exists first if _, err := ref.Get(ctx); err != nil { if status.Code(err) == codes.NotFound { return fmt.Errorf("item %s: %w", i.ID, ErrNotFound) } return fmt.Errorf("item %s: %w", id, err) } if _, err := ref.Set(ctx, i); err != nil { return err } return nil } ``` ### Building the REST operations So now that we've covered how REST should work, it's clear we need to change our routes and methods a bit. Let's build out all five operations, to match this router plan: ```go a.router.HandleFunc("/items", a.list).Methods(http.MethodGet) a.router.HandleFunc("/items", a.add).Methods(http.MethodPost) a.router.HandleFunc("/items/{id}", a.get).Methods(http.MethodGet) a.router.HandleFunc("/items/{id}", a.put).Methods(http.MethodPut) a.router.HandleFunc("/items/{id}", a.drop).Methods(http.MethodDelete) ``` We don't need to change `app.list()`; we can use it as-is. But we need to change `app.add()` to conform to REST correctly. When the object is created, we return a 201 status code (instead of 200), and attach a `Location` header that references the created object. However, if the object to be created (really, its ID) exists already, we should return a 409 "conflict" status. ```go func (a *app) add(w http.ResponseWriter, r *http.Request) { var item Item err := json.NewDecoder(r.Body).Decode(&item) if err != nil || item.Name == "" { http.Error(w, "Invalid input", http.StatusBadRequest) return } if item.ID != "" { http.Error(w, "Key assigned", http.StatusConflict) return } id, err := a.db.AddItem(r.Context(), &item) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } w.Header().Set("Content-Type", "application/json") w.Header().Set("Location", a.location(r.URL, r.Host, id)) w.WriteHeader(http.StatusCreated) // we're not going to return an error if the encoding // fails, because we've already returned Location _ = json.NewEncoder(w).Encode(item) } ``` We're going to assume that if an ID was passed in, we'll have a conflict: the input data for a new object shouldn't have an ID assigned at all. We **must** set the status before we encode the output. It's a little-known detail about Go's HTTP package that if we write to the `ResponseWriter` before setting the status, it will be "200 OK" and we won't be able to change it (actually, we'll get a warning if we try to). It is safe to add headers before or after writing the status. Here we create a location header using our server's URL and the created id, using a utility function. ```go func (a *app) location(url *url.URL, host, id string) string { return fmt.Sprintf("http://%s%s/%s", host, url.String(), id) } ``` The header will look like ``` Location: http://localhost:8080/items/92d4a080-348e-4ef7-8ec3-80ba008ccd68 ``` when it's sent back to the client; the client must be able to use this URL as-is and immediately to fetch the object just created. Since we're using the `Location` header, we don't really have to return the new object, so if its encoding fails, we won't override the status code because we have actually created the object and must report that. Next we'll handle returning an individual item, given its ID. We must handle the case where the ID in fact doesn't correspond to an actual item in the database (for example, the item was already deleted). ```go func (a *app) get(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] item, err := a.db.GetItem(r.Context(), id) if err != nil { if errors.Is(err, ErrNotFound) { http.Error(w, err.Error(), http.StatusNotFound) return } http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") if err = json.NewEncoder(w).Encode(item); err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintln(w, err) return } } ``` This is one of three handlers that must get the ID from the URL given the route `/item/{id}`, that is, where the last part of the URL is matched as a variable. `mux.Vars()` returns a map of all such variables; in the unlikely event its missing (which as we saw before shouldn't happen), we'd look up an empty ID and fail in a "normal" way. Note our use of `errors.Is()` to see if the underlying cause is a "not found" error: in our DB client method we deliberately wrapped such an error when Firestore told us the key didn't correspond to a document. We're using a new pattern of error handling established in Go 1.13; see the blog post [Working with Errors in Go 1.13](https://blog.golang.org/go1.13-errors). Updating an item is similar; we must get the ID but also take data from the request body: ```go func (a *app) put(w http.ResponseWriter, r *http.Request) { var item Item vars := mux.Vars(r) id := vars["id"] err := json.NewDecoder(r.Body).Decode(&item) if err != nil || item.Name == "" { http.Error(w, "Invalid input", http.StatusBadRequest) return } item.ID = id // in case it was left out of the object data if err = a.db.UpdateItem(r.Context(), &item); err != nil { if errors.Is(err, errNotFound) { http.Error(w, err.Error(), http.StatusNotFound) return } http.Error(w, err.Error(), http.StatusInternalServerError) return } } ``` We validate the incoming data (here validation is trivial: does it have a name?) and then call the update method, which will fail if the object doesn't exist already. We handle that just as for the `get` handler above. Note that we're not required to return data or a `Location` header. Finally, deleting an item isn't too hard; all we need from the request is the ID, and deletion always succeeds unless there's an internal error. ```go func (a *app) drop(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] if err := a.db.DeleteItem(r.Context(), id); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } } ``` ### Testing without a server Our first test example ran pretty much the complete program. Here in a second example we'll show running a test using mocks that don't require network access at all. #### DB mocks We'll have to create a mock database which serves the same methods as the real Firestore client, with behavior as close as possible to the real thing. For now, we'll assume we don't need thread safety in our DB mock, but we may want to induce deliberate failures. ```go var ( errShouldFail = errors.New("mock should fail") errInvalid = errors.New("invalid operation") ) type mockDB struct { data map[string]*Item fail bool } ``` All our methods will mirror those of Firestore as well as how we wrap that logic in our real client. For example, the implementation of `AddItem()` should assign UUIDs in the same way. ```go func (m *mockDB) AddItem(_ context.Context, i *Item) (string, error) { if m.fail { return "", errShouldFail } if m.data == nil { m.data = make(map[string]*Item) } else if i.ID != "" { return "", errInvalid } add: i.ID = uuid.New().String() if _, ok := m.data[i.ID]; ok { goto add } m.data[i.ID] = i return i.ID, nil } ``` Note how we first check whether the method should "just fail" before we do any real work; also, Go doesn't initialize maps for us, so we'll need to do that to avoid a panic the first time an object is created. We also fail if the item already has an ID, since it may already exist. The other access methods are straightforward translations of database access to map access: ```go func (m *mockDB) GetItem(_ context.Context, id string) (*Item, error) { if m.fail { return nil, errShouldFail } if i, ok := m.data[id]; ok { return i, nil } return nil, ErrNotFound } ``` ```go func (m *mockDB) ListItems(_ context.Context) ([]*Item, error) { if m.fail { return nil, errShouldFail } result := make([]*Item, 0, len(m.data)) for _, i := range m.data { result = append(result, i) } return result, nil } ``` ```go func (m *mockDB) UpdateItem(_ context.Context, i *Item) error { if m.fail { return errShouldFail } if _, ok := m.data[i.ID]; !ok { return errInvalid } m.data[i.ID] = i return nil } ``` ```go func (m *mockDB) DeleteItem(_ context.Context, id string) error { if m.fail { return errShouldFail } if m.data != nil { delete(m.data, id) } return nil } ``` Finally, we'd like a way to preload some data for test purposes: ```go func (m *mockDB) preload() { if m.data == nil { m.data = make(map[string]*Item) } for i := 1; i < 10; i++ { id := uuid.New().String() item := Item{ID: id, Name: fmt.Sprintf("item-%d", i)} m.data[id] = &item } } ``` Again, we must pre-create the Go map for safety. #### Restructuring the app We also need to break up the app's setup routines a bit, since we won't actually start a server, but will need access to the router and mock DB. Specifically, we need to break out the part where we set up routes, since we'll need to do that without creating an actual HTTP server. ```go func (a *app) makeServer() { a.server = &http.Server{ Addr: a.addr, Handler: a.router, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second, ReadHeaderTimeout: 20 * time.Second, } } ``` ```go func (a *app) addRoutes() { a.router.Use(logRequest) a.router.HandleFunc("/items", a.list).Methods(http.MethodGet) a.router.HandleFunc("/items", a.add).Methods(http.MethodPost) a.router.HandleFunc("/items/{id}", a.get).Methods(http.MethodGet) a.router.HandleFunc("/items/{id}", a.put).Methods(http.MethodPut) a.router.HandleFunc("/items/{id}", a.drop).Methods(http.MethodDelete) } ``` ```go func RunApp(args []string) int { a := app{router: mux.NewRouter()} if err := a.fromArgs(args); err != nil { fmt.Fprintln(os.Stderr, err) return -2 } if err := a.createClient(); err != nil { fmt.Fprintln(os.Stderr, err) return -2 } a.makeServer() a.addRoutes() return a.serve() } ``` #### Running the test Our test code will create a mock DB and then create an app with a router and that mock. We can then call the router with test requests and a special recorder that captures the handler's output. Note that the hostname part of the URL doesn't matter, since we're not actually connecting using a network. ```go func TestWithMocks(t *testing.T) { d := &mockDB{} a := app{ router: mux.NewRouter(), db: d, } d.preload() a.addRoutes() r := httptest.NewRequest("GET", "http://who-cares/items", nil) w := httptest.NewRecorder() a.router.ServeHTTP(w, r) resp := w.Result() if resp.StatusCode != http.StatusOK { t.Errorf("invalid response: %d", resp.StatusCode) } var result []Item if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { t.Fatal(err) } if len(result) != len(d.data) { t.Errorf("invalid result: %#v", result) } fmt.Println(result) } ``` We can then decode the output and see if we got a list with items in it. We can also test a couple of failure scenarios. First, we can actually make the mock DB fail and verify we get an "internal failure" error. ```go func TestFailWithMocks(t *testing.T) { d := &mockDB{fail: true} a := app{ router: mux.NewRouter(), db: d, noAuth: true, } d.preload() a.addRoutes() r := httptest.NewRequest("GET", "http://who-cares/items", nil) w := httptest.NewRecorder() a.router.ServeHTTP(w, r) resp := w.Result() if resp.StatusCode != http.StatusInternalServerError { t.Errorf("invalid response: %d", resp.StatusCode) } } ``` Second, we can give the app an invalid item ID and see that we get a "not found" response. ```go func TestNotFoundWithMocks(t *testing.T) { d := new(mockDB) a := app{ router: mux.NewRouter(), db: d, noAuth: true, } d.preload() a.addRoutes() r := httptest.NewRequest("GET", "http://who-cares/items/1", nil) w := httptest.NewRecorder() a.router.ServeHTTP(w, r) resp := w.Result() if resp.StatusCode != http.StatusNotFound { t.Errorf("invalid response: %d", resp.StatusCode) } } ``` Later we'll see how some of these tests could be combined into a table-driven unit test. ### Testing with a test server This third test example fits between the first two; we'll mock the database but use Go's standard library test server, which will find a free port for us, so we're not at risk of having tests fail due to a port collision. The key parts are - we call `httptest.NewServer()` to make the test server - we get the test server's URL which has a random port assignment ```go func TestWithMockServer(t *testing.T) { d := &mockDB{} r := mux.NewRouter() s := httptest.NewServer(r) a := app{ router: r, db: d, noAuth: true, } d.preload() a.addRoutes() resp, err := http.Get(s.URL + "/items") if err != nil { t.Fatal(err) } if resp.StatusCode != http.StatusOK { t.Errorf("invalid response: %d", resp.StatusCode) } var result []Item if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { t.Fatal(err) } if len(result) != len(d.data) { t.Errorf("invalid result: %#v", result) } fmt.Println(result) } ``` There's not a lot of added benefit to this style of test over the second example, unless you have client code or utilities that expect to make a network connection in the test. ## Firestore transactions In our next section, we're going to add an auto-incrementing ID to each item we store in the database. Here we'll call it a _SKU_ (which in retail means "stock keeping unit"). Firestore doesn't support this type of ID itself (as many SQL databases do), but we can fake it. Along the way we show how to run transactions in Firestore, because only in a transaction can we assign such an ID to database entries safely. We'll change our `Item` definition with a new field ```go type Item struct { ID string `json:"id" firestore:"id"` Name string `json:"name" firestore:"name"` SKU int `json:"sku" firestore:"sku"` } ``` ### Creating the sequence We need to extend our client with some private methods. First, when we create the client, we must see if the sequence number "document" exists and create it if it doesn't (which will always be true at least once). (Note that when we use the Firestore emulator, it "forgets" all data any time we stop it. At the same time, if we leave it running with data when we start unit tests, we may get unexpected failures because the database doesn't start in a known state.) Let's add a "startup" function into `NewClient()`, right after we make the client object: ```go if err = c.startSKU(ctx); err != nil { return nil, err } ``` Then we use this method to create a sequence if it's missing. Note that we can get a document ref outside the transaction since that's a local operation (no context, no error). What's critically important is that within the closure we pass to `RunTransaction()`, all attempts to read or write use `tx` (the transaction passed in) instead of the client. ```go const ( skuDoc = "Next$SKU" nextField = "next" startSKU = 1000 ) func (c *Client) startSKU(ctx context.Context) error { ref := c.data.Doc(skuDoc) commit := func(ctx context.Context, tx *firestore.Transaction) error { doc, err := tx.Get(ref) if err != nil { if status.Code(err) == codes.NotFound { log.Println("no SKU doc, adding it") data := map[string]interface{}{ nextField: startSKU, } if err := tx.Create(ref, data); err != nil { return fmt.Errorf("add SKU failed: %s", err) } return nil } return err } valRef, err := doc.DataAt(nextField) if err != nil { return err } if val, ok := valRef.(int64); ok { log.Printf("started SKU, %s = %v", nextField, val) return nil } return fmt.Errorf("can't read %s: %v", nextField, doc.Data()) }) return c.fs.RunTransaction(ctx, commit) } ``` We didn't define a structure for our sequence "document"; instead we just use `map[string]{interface}` in a way similar to raw JSON. If the document exists, we get the value of one field and use reflection to get its value as an integer. Now, it turns out that the code above has a small problem, which we see immediately if we run the unit tests we already have (you always do that when changing code, don't you?). We put our sequence "document" into the same collection we use for items, and so when we list an "empty" database, we actually get an empty item back. (Please check this, and see if you can figure out why the item is empty.) To avoid this problem, we'll use a separate collection just for keeping track of the sequence. First, we add a parameter to the app config ```go type app struct { router *mux.Router server *http.Server db DB addr string project string data string util string } ``` and add an option for it in `fromArgs()` ```go fl.StringVar(&a.data, "data", "items", "FS data collection") fl.StringVar(&a.util, "util", "util", "FS util collection") ``` then pass it to `NewClient` ```go func (a *app) createClient() (err error) { a.db, err = NewClient(a.project, a.data, a.util) return } ``` where it's used to make the client ```go func NewClient(project, data, util string) (*Client, error) { . . . c := Client{ fs: client, data: client.Collection(data), util: client.Collection(util), } . . . ``` and finally we change the first line of `startSKU()` to use that "utility" collection and not the regular one: ```go func (c *Client) startSKU(ctx context.Context) error { ref := c.util.Doc(skuDoc) . . . ``` We will also need a utility function we can run inside a transaction to get the next value in the sequence ```go func getNext(seqRef *firestore.DocumentRef, tx *firestore.Transaction) (int, error) { seq, err := tx.Get(seqRef) // tx.Get, NOT ref.Get! if err != nil { return 0, err } valRef, err := seq.DataAt(nextField) if err != nil { return 0, err } val, ok := valRef.(int64) if !ok { return 0, fmt.Errorf("can't read %s", nextField) } return int(val), nil } ``` Again, it's critically important that we get data through the transaction and not from the collection. ### Using the sequence to create items The only DB client method we need to rewrite is `Client.AddItem()`. It will look almost the same, but we'll factor out our create logic into a function that replaces the usual Firestore `Create()` call. ```go func (c *Client) AddItem(ctx context.Context, i *Item) (string, error) { var ref *firestore.DocumentRef add: i.ID = uuid.New().String() ref = c.data.Doc(i.ID) if err := c.create(ctx, ref, i); err != nil { // it's unlikely to happen once and virtually // impossible for it to happen twice in a row if status.Code(err) == codes.AlreadyExists { goto add } return "", err } return i.ID, nil } ``` Now our private client `Client.create()` method can run the transaction to get and update the sequence number while creating the item in Firestore. One key detail about Firestore transactions is that _all reads must precede any writes_. In this case that's not a big deal, since we can't use the sequence number until we've read it. Again, note that we get the sequence document from the "utility" collection, but use the document ref passed in to `create` and captured in the closure to create the item. ```go func (c *Client) create(ctx context.Context, ref *firestore.DocumentRef, item *Item) error { seqRef := c.util.Doc(skuDoc) commit := func(ctx context.Context, tx *firestore.Transaction) error { next, err := getNext(seqRef, tx) if err != nil { return err } item.SKU = next // if the transaction fails, this write will // also fail, so we shouldn't waste SKUs update := []firestore.Update{{ Path: nextField, Value: next + 1, }} if err := tx.Update(seqRef, update); err != nil { return err } // using Create here will prevent overwriting an // existing offer with the same UUID if err := tx.Create(ref, item); err != nil { return err } return nil }) return c.fs.RunTransaction(ctx, commit) } ``` In the event two transactions try to update the sequence number at the same time, one will fail and be retried by Firestore. Therefore, the closure we pass in to `RunTransaction()` must be safe to run more than once. If the closure must return data (by altering a variable local to `create()` it will need to (re-) create that data accordingly. However, if the closure returns an error of its own, Firestore will not run the closure again. ### Testing creation Now that we've done this much, let's try to create some items and list them. Note that we don't have to change any of the web server handlers; they'll continue to work exactly as they are. ``` $ curl http://localhost:8080/items -X POST --data '{"name":"spoon"}' -i HTTP/1.1 201 Created Content-Type: application/json Location: http://localhost:8080/items/b34825af-bc2f-4ebb-84f8-0a1d082f9823 Date: Sun, 27 Sep 2020 21:13:35 GMT Content-Length: 72 {"id":"b34825af-bc2f-4ebb-84f8-0a1d082f9823","name":"spoon","sku":1000} $ curl http://localhost:8080/items -X POST --data '{"name":"spork"}' {"id":"92d4a080-348e-4ef7-8ec3-80ba008ccd68","name":"spork","sku":1001} $ curl http://localhost:8080/items -X POST --data '{"name":"fork"}' {"id":"e3828057-1373-4f98-ae08-e7ff2c7aa2ba","name":"fork","sku":1002} ``` ```js $ curl -s http://localhost:8080/items | jq [ { "id": "92d4a080-348e-4ef7-8ec3-80ba008ccd68", "name": "spork", "sku": 1001 }, { "id": "b34825af-bc2f-4ebb-84f8-0a1d082f9823", "name": "spoon", "sku": 1000 }, { "id": "e3828057-1373-4f98-ae08-e7ff2c7aa2ba", "name": "fork", "sku": 1002 } ] ``` Note that as we created items, their SKUs were assigned in order, but when we list the items, they're ordered by UUID (go back and look at the logic in `Client.ListItems()`). ### Searching by SKU Now that we have SKUs assigned to our items, we might like to list the SKUs or retrieve an item by SKU rather than by UUID. The "get by SKU" handler will allow us to show how to run a simple Firestore query. Let's define a couple of new routes and then we'll fill in the handlers. ```go a.router.HandleFunc("/skus", a.listSKU).Methods(http.MethodGet) a.router.HandleFunc("/skus/{sku}", a.getSKU).Methods(http.MethodGet) ``` First, let's get a listing. We're going to use logic very similar to listing items, except we'll only return a map of SKU to item UUID. We need to add a new accessor to our DB client. In this case, our DB lookup will order by the "sku" field and not the document ID. ```go func (c *Client) ListSKUs(ctx context.Context) (map[string]string, error) { query := c.data.OrderBy("sku", firestore.Asc) docs, err := query.Documents(ctx).GetAll() if err != nil { return nil, err } result := make(map[string]string, len(docs)) for _, doc := range docs { var i Item if err = doc.DataTo(&i); err != nil { log.Printf("item %s decode: %s", doc.Ref.ID, err) continue } sku := strconv.Itoa(i.SKU) result[sku] = i.ID } return result, nil } ``` While we're here, we'll add an accessor to get an item by SKU. Instead of creating a document ref using an ID, we create a query with a "where" clause to match any items with the correct value in the "sku" field. Note that the query may return no documents without an error, so we check the length of the return list. ```go func (c *Client) GetItemBySKU(ctx context.Context, sku int) (*Item, error) { query := c.data.Where("sku", "==", sku) docs, err := query.Documents(ctx).GetAll() if err != nil { log.Printf("error finding sku %d: %s", sku, err) return nil, err } if len(docs) == 0 { return nil, fmt.Errorf("sku %d: %w", sku, ErrNotFound) } var i Item if err = docs[0].DataTo(&i); err != nil { log.Printf("item %s decode: %s", docs[0].Ref.ID, err) return nil, err } return &i, nil } ``` In theory, we'll never have more than one document with the same SKU, so for now we won't handle that case. In real life, there are ways to duplicate a SKU in Firestore by accident, and we might want to be more aggressive about checking for that here and elsewhere. Note that we'll also have to add these methods to the DB interface definition and to the `mockDB` type. ```go type DB interface { AddItem(context.Context, *Item) (string, error) GetItem(context.Context, string) (*Item, error) GetItemBySKU(context.Context, int) (*Item, error) ListItems(context.Context) ([]*Item, error) ListSKUs(context.Context) (map[string]string, error) UpdateItem(context.Context, *Item) error DeleteItem(context.Context, string) error } ``` ```go func (m *mockDB) GetItemBySKU(_ context.Context, sku int) (*Item, error) { if m.fail { return nil, errShouldFail } for _, v := range m.data { if v.SKU == sku { return v, nil } } return nil, ErrNotFound } ``` ```go func (m *mockDB) ListSKUs(_ context.Context) (map[string]string, error) { if m.fail { return nil, errShouldFail } result := make(map[string]string, len(m.data)) for _, i := range m.data { result[strconv.Itoa(i.SKU)] = i.ID } return result, nil } ``` Now that we have DB accessors, we can write the handlers. Both of them look very much like the `/items` route handlers. To list SKUs, we just call the correct accessor and serialize the result. ```go func (a *app) listSKU(w http.ResponseWriter, r *http.Request) { skus, err := a.db.ListSKUs(r.Context()) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") if err = json.NewEncoder(w).Encode(skus); err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintln(w, err) return } } ``` To find by SKU, we only need to get a different variable from the route and use a different DB accessor. We do need to handle validating that the "sku" variable is a valid integer. ```go func (a *app) getSKU(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) s := vars["sku"] sku, err := strconv.Atoi(s) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } item, err := a.db.GetItemBySKU(r.Context(), sku) if err != nil { if errors.Is(err, errNotFound) { http.Error(w, err.Error(), http.StatusNotFound) return } http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") if err = json.NewEncoder(w).Encode(item); err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintln(w, err) return } } ``` Let's try them out. Given the items we created above, ```js $ curl -s http://localhost:8080/skus | jq { "1000": "b34825af-bc2f-4ebb-84f8-0a1d082f9823", "1001": "92d4a080-348e-4ef7-8ec3-80ba008ccd68", "1002": "e3828057-1373-4f98-ae08-e7ff2c7aa2ba" } $ curl -s http://localhost:8080/skus/1001 | jq { "id": "92d4a080-348e-4ef7-8ec3-80ba008ccd68", "name": "spork", "sku": 1001 } $ curl -s http://localhost:8080/skus/1 -w "%{http_code}\n" sku 1: not found 404 $ curl -s http://localhost:8080/skus/A -w "%{http_code}\n" strconv.Atoi: parsing "A": invalid syntax 400 ``` ### A few router details Gorilla mux allows us to specify regular expression patterns for variables in routes. For example, we can partly solve the problem of non-integer SKU values by changing the route to require a value using only digits: ```go a.router.HandleFunc("/skus/{sku:[0-9]+}", a.getSKU).Methods(http.MethodGet) ``` such that the error we see from that last example above becomes ``` $ curl -s http://localhost:8080/skus/A -w "%{http_code}\n" 404 page not found ``` Note that `[0-9]+` requires at least one digit due to the `+` sign. Also note that Gorilla mux treats trailing slashes "strictly". That means a route `/users` cannot be accessed with `/users/` and vice versa. If you want to treat both `/users` and `/users/` (note: no variable) the same, you have a couple of options: - register both routes with the same handler and method(s) - "fix" the route before it's handed off to the router For the second option, here's an interesting article [Dealing with Trailing Slashes on RequestURI in Go with Mux](https://natedenlinger.com/dealing-with-trailing-slashes-on-requesturi-in-go-with-mux/) that shows an example. ### Starting the emulator in tests Here we'll adapt another good article [Unit Testing with Firestore Emulator and Go](https://www.captaincodeman.com/2020/03/04/unit-testing-with-firestore-emulator-and-go) so that our unit tests can always have an emulator. In Go, if we define a function `TestMain` it will be run before all unit tests in our module. We then run the tests and report a final exit value. ```go func TestMain(m *testing.M) { stop, err := startEmulator() if err != nil { log.Println("*** FAILED TO START EMULATOR ***") os.Exit(-1) } // it would be nice if we could catch a panic // and ensure we close the emulator properly, // but we can't because UTs are in goroutines result := m.Run() // don't defer, since we don't return // but rather exit with a code stop() os.Exit(result) } ``` The `startEmulator()` function is a bit involved. ```go func startEmulator() (func(), error) { const firestoreEmulatorHost = "FIRESTORE_EMULATOR_HOST" // we assume that if this env variable is already set, // there is an emulator running externally we can use if os.Getenv(firestoreEmulatorHost) != "" { return func() {}, nil } cmd := exec.Command("gcloud", "beta", "emulators", "firestore", "start", "--host-port=localhost:8086") // this makes it killable cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} // capture its output so we can check it's started stderr, err := cmd.StderrPipe() if err != nil { log.Fatal(err) } defer stderr.Close() if err := cmd.Start(); err != nil { log.Fatal(err) } timer := time.After(20 * time.Second) done := make(chan string) // we'll scrape the command's output in a separate // goroutine so we can timeout if it hangs up go func() { defer close(done) buf := make([]byte, 1024) for { n, err := stderr.Read(buf[:]) if err != nil { if err == io.EOF { return } log.Fatalf("reading stderr: %v", err) } if n > 0 { d := string(buf[:n]) // checking for an obvious failure if strings.Contains(d, "Exception") { done <- strings.TrimSuffix(d, "\n") return } // checking for the message that it's started if strings.Contains(d, "Dev App Server is now running") { done <- "running" return } // and capturing the FIRESTORE_EMULATOR_HOST value to set; // we will get this before we get the startup message above if pos := strings.Index(d, firestoreEmulatorHost+"="); pos > 0 { host := d[pos+len(firestoreEmulatorHost)+1 : len(d)-1] os.Setenv(firestoreEmulatorHost, host) } } } }() stop := func() { if err = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL); err != nil { log.Printf("failed to stop emulator pid=%d\n", cmd.Process.Pid) return } log.Printf("stopped emulator pid=%d\n", cmd.Process.Pid) } select { case result := <-done: if result == "running" { log.Printf("emulator running; pid=%d\n", cmd.Process.Pid) return stop, nil } // i.e., print something like "address in use" message log.Println(result) case <-timer: // fall through } stop() return func() {}, fmt.Errorf("failed to start emulator") } ``` First, we check to see if the emulator is already running (which we assume if the environment variable. In Drone CI/CD, we typically run the Firestore emulator as a step from a Docker container that already has all the software installed, so we wouldn't want to start it here. Next we start the emulator, and then we kick off a goroutine to scrape its output looking for either the magic phrase ("emulator running") or some type of Java exception (typically, port already in use). We also take actually set the environment variable in our process so when we try to make a Firestore client, it sees the emulator. We don't want to wait for ever if something goes wrong, so we use `select` to choose between two alternatives: the scraper can tell us we've started or not, or we hit a timeout waiting for it (because somehow our command hung up). Finally, we return a `stop()` function that can correctly stop the emulator by killing the correct process id (PID). Note that in some cases, if we already know we've failed, we just call stop() and don't return it. Now, this is all somewhat complicated; if you're not familiar with Go's concurrency model, just use it, and then come back and study it later when you've gone further in the tutorial. #### Utilities There are also a couple of utility functions that might be useful, to preload and clean up the emulator. Ideally, each unit test should stand alone: add to the emulator any initial data, and remove **all** data from it, whether preloaded or added in the unit test. We'll show the cleanup routine, since it's pretty generic, and leave preloading as an exercise. You could preload from files, or perhaps from a map literal in the code, for example. The cleanup function makes no assumptions; given only the project, it will find all collections and remove all documents from all of them, using a batch write for the deletion. It avoids using the software under test. ```go func clearEmulator(project string) error { ctx := context.Background() client, err := firestore.NewClient(ctx, project) if err != nil { return fmt.Errorf("deleting: %s", err) } defer client.Close() batch := client.Batch() colls := client.Collections(ctx) for coll, err := colls.Next(); err != iterator.Done; coll, err = colls.Next() { if err != nil { return fmt.Errorf("clearing: %s", err) } iter := coll.Documents(ctx) defer iter.Stop() for doc, err := iter.Next(); err != iterator.Done; doc, err = iter.Next() { if err != nil { return fmt.Errorf("clearing: %s", err) } batch.Delete(doc.Ref) log.Println("unloaded " + doc.Ref.ID) } } if _, err := batch.Commit(ctx); err != nil { return fmt.Errorf("clearing: %s", err) } return nil } ``` A typical unit test would then do something like this: ```go func TestMeSport(t *testing.T) { if err := preloadEmulator(projectID, . . .); err != nil { t.Fatal(fmt.Errorf("couldn't preload: %w", err)) } defer func() { if err := clearEmulator(projectID); err != nil { t.Errorf("failed to empty") } }() . . . ``` ## GraphQL In our last section, we'll add GraphQL support using the [gqlgen](https://gqlgen.com) library. This library provides the most complete support for GraphQL among the various choices for Go. It will also auto-generate much of our code for us in a way that promotes compile-time type safety. By the way, GraphQL as a technology has the same limitation as REST, in that it's concerned with CRUD operations. It may not be well-suited for some command-focused (as opposed to data-focused) APIs, such as the sound file conversion example we mentioned before. ### Setup We're going to let `gqlgen` create a dummy project, and then we'll copy our existing tutorial into that new directory. This will be surprisingly easy, with just a few loose ends we need to tie up. ``` $ mkdir tutor4 $ cd tutor4 $ go mod init tutor4 $ go get github.com/99designs/gqlgen $ go run github.com/99designs/gqlgen init Exec "go run ./server.go" to start GraphQL server ``` Except we're not going to start it yet. We have several things we need to do first. 1. copy over the existing source files 2. edit the schema 3. remove our definition of Item 4. move db.go and db_test.go to its own package to avoid a cycle 5. inject the DB client into the Resolver type 6. regenerate 7. copy Item to new file and add firestore field names 8. edit the schema to point to model using @goModel directive 9. fix the use of Item in our existing code (use model.Item) 10. plug the graphQL handlers into our app setup 11. fill in the three resolvers we need 12. profit !! In my case, I had the following files to copy: ``` $ ls app.go db.go go.mod model.go serve_test.go cmd db_test.go go.sum serve.go ``` Note that `cmd/main.go` doesn't need to change. We're going to end up with this tree ``` $ tree . ├── app.go ├── cmd │   └── main.go ├── db │   ├── db.go │   └── db_test.go ├── go.mod ├── go.sum ├── gqlgen.yml ├── graph │   ├── generated │   │   └── generated.go │   ├── model │   │   ├── item.go │   │   └── models_gen.go │   ├── resolver.go │   ├── schema.graphqls │   └── schema.resolvers.go ├── serve.go ├── serve_test.go └── server-gen.txt ``` The file `model.go` can go away for now. `server-gen.txt` is what the `init` command created as `server-gen.go`; we'll copy a couple of lines out of it but otherwise ignore it. (We must rename it so it doesn't create a problem when we build.) Let's go ahead and take care of #4; if we wait it will just cause errors: ``` $ mkdir db $ mv db*.go db $ find ./db -name '*.go' -exec sed -i '' 's/tutor4/db/' {} + ``` That's because we need to open `graph/resolver.go` and make a change so that our resolvers have access to the DB client (#5): ```go import "tutor4/db" type Resolver struct { Client db.DB } ``` and once we've done that, we'll have an eventual import cycle (once we reference the GraphQL stuff from our app) that we might as well break now. Now that the DB code has moved, add `tutor4/db` everywhere the DB code is used, just as we did in `resolver.go`. ### Editing code OK, back to #2; we still don't have a schema for _our_ app, just for the dummy app. Edit `graph/schema.graphqls`, remove everything that's there, and replace it with this: ```graphql type Item { id: ID! name: String! sku: Int! } type Query { items: [Item!]! } input NewItem { name: String! } type Mutation { createItem(input: NewItem!): Item! } ``` Also, remove the original `model.go` file with its definition of type `Item` (#3). Let's jump over #4 and #5 (we just did them above), and regenerate code from our schema (#6). This will replace certain files, but shouldn't mess with our updated `resolver.go`: ``` go run github.com/99designs/gqlgen generate ``` So one small drawback to `gqlgen` is that we can't get custom struct tags for our model objects easily. Our choices are - copy the model object, fix the tags, and don't regenerate it - create a plugin that alters how `gqlgen` generates the model object - live without struct tags for Firestore serialization The second option isn't that hard, given some examples on the Internet, but we're not going down that road for now. Model objects are created in `graph/models/model_gen.go`, so we'll place our "fixed" definition in the same directory (#7). Move the text for type `Item` from `model_gen.go` into a new file `graph/models/item.go`, and update it so it looks like ```go type Item struct { ID string `json:"id" firestore:"id"` Name string `json:"name" firestore:"name"` SKU int `json:"sku" firestore:"sku"` } ``` which is pretty much what we had before; we're just adding back the Firestore tags (compared to the generated `Item`); if we don't, we'll have a problem with our queries that use the field name "sku" (capitalization). Now, if we don't do one more step, the next time we regenerate we'll get a duplicate (and not quite desired) version of `Item` in `model_gen.go`. To avoid that, we're going to tell `gqlgen` to use our existing model object and not create one. We need to re-edit our schema file to make it look like this (#8): ```graphql directive @goModel(model:String,models:[String!]) on OBJECT|INPUT_OBJECT|SCALAR|ENUM|INTERFACE|UNION type Item @goModel(model: "tutor4/graph/model.Item") { id: ID! name: String! sku: Int! } . . . ``` The first line just activates a built-in directive specific to `gqlgen` that allows us to use an existing type; then we use it on `Item` to identify our type. The next step is to carry out a couple a simple transformation: change `Item` to `model.Item` everywhere (#9). Before we fill in the resolvers, let's add the GraphQL routes into our app. We need to add the GraphQL engine into our app type: ```go import ( . . . "github.com/99designs/gqlgen/graphql/handler" "github.com/99designs/gqlgen/graphql/playground" "tutor4/db" "tutor4/graph" "tutor4/graph/generated" ) type app struct { router *mux.Router server *http.Server graphql *handler.Server . . . } ``` In `app.go`, we need to update `addRoutes()`. First, add these lines to the top of the function, which creates the server with our DB injected into the resolver (#10): ```go r := graph.Resolver{Client: a.db} c := generated.Config{Resolvers: &r} s := generated.NewExecutableSchema(c) a.graphql = handler.NewDefaultServer(s) ``` and then add two new routes below: ```go play := playground.Handler("GraphQL playground", "/graphql") a.router.Handle("/", play) a.router.Handle("/graphql", a.graphql) ``` ### Adding resolvers Finally, we're ready to add our custom resolver code (#11). Edit `graph/schema.resolvers.go` and we'll find two functions whose body is just a panic. Yes, just two functions that we need to provide; everything else has been generated for us (more than 2000 lines of code! compile-time safe code!). First, we need to fill in `CreateItem`. It's going to look remarkably similar to our `add` handler, except that we don't need to deserialize any JSON (that's already done) and we don't need to write HTTP errors to the response, just return an error (if any) from the function. ```go func (r *mutationResolver) CreateItem(ctx context.Context, input model.NewItem) (*model.Item, error) { if input.Name == "" { return nil, fmt.Errorf("no name") } item := model.Item{ Name: input.Name, } _, err := r.Client.AddItem(ctx, &item) if err != nil { return nil, err } return &item, nil } ``` We do need to copy data from the input type `model.NewItem` (which was generated for us, and we'll keep) into our `Item` type. Then we just access the resolver's DB dependency and write it to the database. The `Items` method is even easier; we just fetch data from the database and return it! ```go func (r *queryResolver) Items(ctx context.Context) ([]*model.Item, error) { items, err := r.Client.ListItems(ctx) if err != nil { return nil, err } return items, nil } ``` That's it! If we've done the steps correctly, we can start up our server and get to work. One option is to open a browser window and navigate to `http://localhost:8080`. That will start a GraphQL playground where you can inspect the schema and execute requests (right now, only to create an item or list all items). Note that we left all our REST-based methods in place, so you can still add or list data as before, in case you want to preload the database or need to remove an item. Alternatively, we can run GraphQL queries with curl. Note that now we **must** include the content-type header or we'll get an error. Also, we must use POST. The GraphQL server will normally return a 200 response even if there's an error (see below for an error example, where it's part of the returned JSON). ```js $ curl -s http://localhost:8080/graphql -X POST -H 'Content-Type: application/json' \ --data '{"operationName":null,"variables":{},"query":"{items {name sku}}"}' | jq { "data": { "items": [] } } ``` Actually, if we're not using them, we can omit the `operationName` and `variables` fields: ```js $ curl -s http://localhost:8080/graphql -X POST -H 'Content-Type: application/json' \ --data '{"query":"{items {name sku}}"}' | jq { "data": { "items": [] } } ``` OK, we still have no data. So let's try to add some: ```js $ curl -s http://localhost:8080/graphql -X POST -H 'Content-Type: application/json' \ --data '{"query":"mutation {createItem(input:{name: \"knife\"}) {id sku}}"}' | jq { "data": { "createItem": { "id": "45e8d301-d584-4c8d-be8d-40953b0c3f08", "sku": 1000 } } } ``` ```js $ curl -s http://localhost:8080/graphql -X POST -H 'Content-Type: application/json' \ --data '{"query":"mutation {createItem(input:{name: \"spork\"}) {id sku}}"}' | jq { "data": { "createItem": { "id": "55ae421d-5a43-486c-b3b4-db3eda664bde", "sku": 1001 } } } ``` ```js $ curl -s http://localhost:8080/graphql -X POST -H 'Content-Type: application/json' \ --data '{"query":"{items {id name sku}}"}' | jq { "data": { "items": [ { "id": "45e8d301-d584-4c8d-be8d-40953b0c3f08", "name": "knife", "sku": 1000 }, { "id": "55ae421d-5a43-486c-b3b4-db3eda664bde", "name": "spork", "sku": 1001 } ] } } ``` ### One more thing Let's add the ability to get an Item by its SKU. We'll need to add to our schema, regenerate, and then fill in one more resolver. First, change type `Query` in the schema: ```graphql type Query { items: [Item!]! item(sku: Int!): Item } ``` Note that the return type for the `item(sku)` lookup does not have a bang (exlamation point, `!`) at the end: if we can't find the SKU in the database, we'll return null. Now regenerate the code. The file `graph/resolver.go` should be unchanged except that we'll now have one more resolver to fill in. Again, that's pretty easy: ```go func (r *queryResolver) Item(ctx context.Context, sku int) (*model.Item, error) { item, err := r.Client.GetItemBySKU(ctx, sku) if err != nil { return nil, err } return item, nil } ``` Note that we no longer need to convert the incoming SKU to an integer, as we did with the REST handler. Restart the server (we left the DB running, so it should still have data), and let's give it a try: ```js $ curl -s http://localhost:8080/graphql -X POST -H 'Content-Type: application/json' \ --data '{"query":"{item(sku:1001) {id name}}"}' -w "%{http_code}\n" | jq { "data": { "item": { "id": "55ae421d-5a43-486c-b3b4-db3eda664bde", "name": "spork" } } } 200 ``` ```js $ curl -s http://localhost:8080/graphql -X POST -H 'Content-Type: application/json' \ --data '{"query":"{item(sku:100) {id name}}"}' -w "%{http_code}\n" | jq { "errors": [ { "message": "sku 100: not found", "path": [ "item" ] } ], "data": { "item": null } } 200 ``` ```js $ curl -s http://localhost:8080/graphql -X POST -H 'Content-Type: application/json' \ --data '{"query":"{item(sku:A) {id name}}"}' -w "%{http_code}\n" | jq { "errors": [ { "message": "Expected type Int!, found A.", "locations": [ { "line": 1, "column": 11 } ], "extensions": { "code": "GRAPHQL_VALIDATION_FAILED" } } ], "data": null } 200 ``` Notice how the GraphQL handler returns errors in case we don't have that SKU, or if the SKU in our query is not an integer (validation was done for us). Also notice that the logging middleware we added to our router works perfectly well with GraphQL queries, since from the router's perspective, the GraphQL handler is just another handler. ``` $ go run ./cmd 2020/09/28 17:28:47 no SKU doc, adding it 2020/09/28 17:28:47 server started on localhost:8080 2020/09/28 17:35:36 POST /graphql {"query":"{items {name sku}}"} 2020/09/28 17:38:12 POST /graphql {"query":"mutation {createItem(input:{name: \"knife\"}) {id sku}}"} 2020/09/28 17:39:58 POST /graphql {"query":"mutation {createItem(input:{name: \"spork\"}) {id sku}}"} 2020/09/28 17:40:13 POST /graphql {"query":"{items {id name sku}}"} 2020/09/28 17:50:42 POST /graphql {"query":"{item(sku:1001) {id name}}"} 2020/09/28 17:51:20 POST /graphql {"query":"{item(sku:100) {id name}}"} 2020/09/28 17:51:28 POST /graphql {"query":"{item(sku:A) {id name}}"} ``` If you're wondering where the GraphQL input came from, we added a bit to the logging middleware at some point, capturing the whole input and providing it back to the request in a replacecment `Body`: ```go func logRequest(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { buf, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } r.Body = ioutil.NopCloser(bytes.NewBuffer(buf)) log.Println(r.Method, r.RequestURI, bytes.NewBuffer(buf).String()) next.ServeHTTP(w, r) }) } ``` It's possible to capture and log the output of from serving the request (you'd do that after calling `ServeHTTP`), but that involves replacing the `ResponseWriter`. It's not too hard, and there are examples on the Internet, so we'll leave that as an exercise. ### Summary There's one important thing to note here: how little code we had to write in order to serve GraphQL, compared to REST. We wrote essentially three methods to wrap DB access functions, plus a couple of extra lines to configure the app at startup. That's in large part because we used `gqlgen` which generated lots of tedious boilerplate code for us. This is step #12: **profit!** Using auto-generated GraphQL takes less work for more functionality and safety. An aside on safety: Go is a compiled language, and we'd like to validate at compile time as much of our code (and GraphQL model) as possible. Some other GraphQL libraries require us lots of tedious code that isn't checked until runtime (do you have enough unit tests? do you even know how many you need?). This isn't much better than building in Python or JS where you really don't know anything about your program until you run it. Compile-time safety is a very important benefit of `gqlgen`, just as much as the cost savings of all the code we didn't have to write. ## Moving on That wraps up this tutorial on building REST and GraphQL web servers with Go. Feel free to expand on this and try some things. For example, add more interesting data to `Item` and then add methods to query that data from Firestore and through GraphQL. Also, add GraphQL mutators to change and/or delete data. Note that there's not much point in adding the GraphQL equivalent of `/skus` routes; it's enough to use the existing `items` query and get a list which can specify what fields to return. <file_sep>package graph // This file will be automatically regenerated based on the schema, any resolver implementations // will be copied through when generating and any unknown code will be moved to the end. import ( "context" "fmt" "tutor4/graph/generated" "tutor4/graph/model" ) func (r *mutationResolver) CreateItem(ctx context.Context, input model.NewItem) (*model.Item, error) { if input.Name == "" { return nil, fmt.Errorf("no name") } item := model.Item{ Name: input.Name, } _, err := r.Client.AddItem(ctx, &item) if err != nil { return nil, err } return &item, nil } func (r *queryResolver) Items(ctx context.Context) ([]*model.Item, error) { items, err := r.Client.ListItems(ctx) if err != nil { return nil, err } return items, nil } func (r *queryResolver) Item(ctx context.Context, sku int) (*model.Item, error) { item, err := r.Client.GetItemBySKU(ctx, sku) if err != nil { return nil, err } return item, nil } // Mutation returns generated.MutationResolver implementation. func (r *Resolver) Mutation() generated.MutationResolver { return &mutationResolver{r} } // Query returns generated.QueryResolver implementation. func (r *Resolver) Query() generated.QueryResolver { return &queryResolver{r} } type mutationResolver struct{ *Resolver } type queryResolver struct{ *Resolver } <file_sep>package tutor3 import ( "context" "errors" "fmt" "log" "strconv" "cloud.google.com/go/firestore" "github.com/google/uuid" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) type DB interface { AddItem(context.Context, *Item) (string, error) GetItem(context.Context, string) (*Item, error) GetItemBySKU(context.Context, int) (*Item, error) ListItems(context.Context) ([]*Item, error) ListSKUs(context.Context) (map[string]string, error) UpdateItem(context.Context, *Item) error DeleteItem(context.Context, string) error } type Client struct { fs *firestore.Client data *firestore.CollectionRef util *firestore.CollectionRef } func NewClient(project, data, util string) (*Client, error) { if project == "" { return nil, errors.New("no projectID") } ctx := context.Background() client, err := firestore.NewClient(ctx, project) if err != nil { return nil, fmt.Errorf("failed to create FS client: %w", err) } c := Client{ fs: client, data: client.Collection(data), util: client.Collection(util), } if err = c.startSKU(ctx); err != nil { return nil, err } return &c, nil } func (c *Client) Close() { c.fs.Close() } func (c *Client) startSKU(ctx context.Context) error { ref := c.util.Doc(skuDoc) return c.fs.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error { doc, err := tx.Get(ref) if err != nil { if status.Code(err) == codes.NotFound { log.Println("no SKU doc, adding it") data := map[string]interface{}{ nextField: startSKU, } if err := tx.Create(ref, data); err != nil { return fmt.Errorf("add SKU failed: %s", err) } return nil } return err } valRef, err := doc.DataAt(nextField) if err != nil { return err } if val, ok := valRef.(int64); ok { log.Printf("started SKU, %s = %v", nextField, val) return nil } return fmt.Errorf("can't read %s: %v", nextField, doc.Data()) }) } func getNext(seqRef *firestore.DocumentRef, tx *firestore.Transaction) (int, error) { seq, err := tx.Get(seqRef) // tx.Get, NOT docRef.Get! if err != nil { return 0, err } valRef, err := seq.DataAt(nextField) if err != nil { return 0, err } val, ok := valRef.(int64) if !ok { return 0, fmt.Errorf("can't read %s", nextField) } return int(val), nil } func (c *Client) create(ctx context.Context, ref *firestore.DocumentRef, item *Item) error { seqRef := c.util.Doc(skuDoc) return c.fs.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error { next, err := getNext(seqRef, tx) if err != nil { return err } item.SKU = next // if the transaction fails, this write will // also fail, so we shouldn't waste SKUs update := []firestore.Update{{ Path: nextField, Value: next + 1, }} if err := tx.Update(seqRef, update); err != nil { return err } // using Create here will prevent overwriting an // existing offer with the same UUID if err := tx.Create(ref, item); err != nil { return err } return nil }) } var errNotFound = errors.New("not found") func (c *Client) AddItem(ctx context.Context, i *Item) (string, error) { var ref *firestore.DocumentRef add: i.ID = uuid.New().String() ref = c.data.Doc(i.ID) if err := c.create(ctx, ref, i); err != nil { // it's unlikely to happen even once and virtually // impossible for it to happen twice in a row if status.Code(err) == codes.AlreadyExists { goto add } return "", err } return i.ID, nil } func (c *Client) GetItem(ctx context.Context, id string) (*Item, error) { doc, err := c.data.Doc(id).Get(ctx) if err != nil { if status.Code(err) == codes.NotFound { return nil, fmt.Errorf("%s: %w", id, errNotFound) } return nil, fmt.Errorf("item %s: %w", id, err) } var i Item if err = doc.DataTo(&i); err != nil { return nil, fmt.Errorf("item %s decode: %w", id, err) } return &i, nil } func (c *Client) GetItemBySKU(ctx context.Context, sku int) (*Item, error) { query := c.data.Where("sku", "==", sku) docs, err := query.Documents(ctx).GetAll() if err != nil { log.Printf("error finding sku %d: %s", sku, err) return nil, err } if len(docs) == 0 { return nil, fmt.Errorf("sku %d: %w", sku, errNotFound) } var i Item if err = docs[0].DataTo(&i); err != nil { log.Printf("item %s decode: %s", docs[0].Ref.ID, err) return nil, err } return &i, nil } func (c *Client) ListItems(ctx context.Context) ([]*Item, error) { query := c.data.OrderBy(firestore.DocumentID, firestore.Asc) docs, err := query.Documents(ctx).GetAll() if err != nil { return nil, err } result := make([]*Item, 0, len(docs)) for _, doc := range docs { var i Item if err = doc.DataTo(&i); err != nil { log.Printf("item %s decode: %s", doc.Ref.ID, err) continue } result = append(result, &i) } return result, nil } func (c *Client) ListSKUs(ctx context.Context) (map[string]string, error) { query := c.data.OrderBy("sku", firestore.Asc) docs, err := query.Documents(ctx).GetAll() if err != nil { return nil, err } result := make(map[string]string, len(docs)) for _, doc := range docs { var i Item if err = doc.DataTo(&i); err != nil { log.Printf("item %s decode: %s", doc.Ref.ID, err) continue } sku := strconv.Itoa(i.SKU) result[sku] = i.ID } return result, nil } func (c *Client) UpdateItem(ctx context.Context, i *Item) error { ref := c.data.Doc(i.ID) // set can create or overwrite existing data // so we need to see if it exists first if _, err := ref.Get(ctx); err != nil { if status.Code(err) == codes.NotFound { return fmt.Errorf("%s: %w", i.ID, errNotFound) } return err } if _, err := ref.Set(ctx, i); err != nil { return err } return nil } func (c *Client) DeleteItem(ctx context.Context, id string) error { _, err := c.data.Doc(id).Delete(ctx) if err != nil { return err } return nil } <file_sep>package tutor import ( "io/ioutil" "net/http" "strings" "testing" ) func TestServer(t *testing.T) { args := []string{"-addr", "localhost:8089"} go runApp(args) client := http.Client{} req, _ := http.NewRequest("GET", "http://localhost:8089/db/xyz", nil) req.SetBasicAuth("admin", "secret") resp, err := client.Do(req) if err != nil { t.Fatal(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { t.Fatal(err) } result := strings.TrimSpace(string(body)) if result != "the item is xyz (no key)" { t.Errorf("invalid response: %v", body) } } <file_sep>package tutor import ( "context" "flag" "fmt" "log" "net/http" "os" "os/signal" "syscall" "time" "github.com/gorilla/mux" ) func logRequest(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Println(r.RequestURI) next.ServeHTTP(w, r) }) } func basicAuth(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user, pass, ok := r.BasicAuth() if !ok || user != "admin" || pass != "<PASSWORD>" { w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`) http.Error(w, "Unauthorized", http.StatusUnauthorized) return } next.ServeHTTP(w, r) }) } func (a *app) withDeadline(next http.Handler) http.Handler { return http.TimeoutHandler(next, a.timeout, "Timeout\n") } func slow(w http.ResponseWriter, r *http.Request) { time.Sleep(6 * time.Second) fmt.Fprintln(w, "slow response") } func list(w http.ResponseWriter, r *http.Request) { key := r.FormValue("key") vars := mux.Vars(r) item := vars["item"] if item == "" { http.Error(w, "No item", http.StatusNotFound) return } if key != "" { fmt.Fprintln(w, "the item is", item, "and the key is", key) } else { fmt.Fprintln(w, "the item is", item, "(no key)") } } func enter(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) item := vars["item"] if item == "" { http.Error(w, "No item", http.StatusNotFound) return } fmt.Fprintln(w, item, "has been posted") } type app struct { addr string server *http.Server timeout time.Duration } func (a *app) serve() int { done := make(chan os.Signal, 1) signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) go func() { if err := a.server.ListenAndServe(); err != nil && err != http.ErrServerClosed { log.Fatalf("listen: %s\n", err) } }() log.Print("server started on ", a.addr) <-done log.Print("server stopping") ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer func() { cancel() log.Print("server stopped") }() if err := a.server.Shutdown(ctx); err != nil { log.Printf("server shutdown: %s", err) return -1 } return 0 } func (a *app) runServer() int { router := mux.NewRouter() router.Use(logRequest) router.Use(basicAuth) router.Use(a.withDeadline) router.HandleFunc("/db/{item}", list).Methods("GET") router.HandleFunc("/db/{item}", enter).Methods("POST") router.HandleFunc("/slow", slow).Methods("GET") a.server = &http.Server{ Addr: a.addr, Handler: router, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second, ReadHeaderTimeout: 20 * time.Second, } return a.serve() } func (a *app) fromArgs(args []string) error { fl := flag.NewFlagSet("service", flag.ContinueOnError) fl.StringVar(&a.addr, "addr", "localhost:8080", "server address") fl.DurationVar(&a.timeout, "time", 5*time.Second, "method timeout") if err := fl.Parse(args); err != nil { return err } return nil } func runApp(args []string) int { var a app if err := a.fromArgs(args); err != nil { fmt.Fprintln(os.Stderr, err) return -2 } return a.runServer() } <file_sep>package tutor3 import ( "encoding/json" "errors" "fmt" "log" "net/http" "net/url" "strconv" "github.com/gorilla/mux" ) func logRequest(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Println(r.Method, r.RequestURI) next.ServeHTTP(w, r) }) } func basicAuth(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user, pass, ok := r.BasicAuth() if !ok || user != "admin" || pass != "<PASSWORD>" { w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`) http.Error(w, "Unauthorized", http.StatusUnauthorized) return } next.ServeHTTP(w, r) }) } func (a *app) list(w http.ResponseWriter, r *http.Request) { items, err := a.db.ListItems(r.Context()) if err != nil { if errors.Is(err, errNotFound) { http.Error(w, err.Error(), http.StatusNotFound) return } http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") if err = json.NewEncoder(w).Encode(items); err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintln(w, err) } } func (a *app) listSKU(w http.ResponseWriter, r *http.Request) { items, err := a.db.ListSKUs(r.Context()) if err != nil { if errors.Is(err, errNotFound) { http.Error(w, err.Error(), http.StatusNotFound) return } http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") if err = json.NewEncoder(w).Encode(items); err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintln(w, err) } } func (a *app) location(url *url.URL, host, id string) string { return fmt.Sprintf("http://%s%s/%s", host, url.String(), id) } func (a *app) add(w http.ResponseWriter, r *http.Request) { var item Item err := json.NewDecoder(r.Body).Decode(&item) if err != nil || item.Name == "" { http.Error(w, "Invalid input", http.StatusBadRequest) return } if item.ID != "" { http.Error(w, "Key assigned", http.StatusConflict) return } id, err := a.db.AddItem(r.Context(), &item) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } w.Header().Set("Content-Type", "application/json") w.Header().Set("Location", a.location(r.URL, r.Host, id)) w.WriteHeader(http.StatusCreated) // we're not going to return an error if the encoding // fails, because we've already returned Location _ = json.NewEncoder(w).Encode(item) } func (a *app) get(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] item, err := a.db.GetItem(r.Context(), id) if err != nil { if errors.Is(err, errNotFound) { http.Error(w, err.Error(), http.StatusNotFound) return } http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") if err = json.NewEncoder(w).Encode(item); err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintln(w, err) } } func (a *app) getSKU(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) s := vars["sku"] sku, err := strconv.Atoi(s) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } item, err := a.db.GetItemBySKU(r.Context(), sku) if err != nil { if errors.Is(err, errNotFound) { http.Error(w, err.Error(), http.StatusNotFound) return } http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") if err = json.NewEncoder(w).Encode(item); err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintln(w, err) } } func (a *app) put(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] var item Item err := json.NewDecoder(r.Body).Decode(&item) if err != nil || item.Name == "" { http.Error(w, "Invalid input", http.StatusBadRequest) return } item.ID = id // in case it was left out of the object data if err = a.db.UpdateItem(r.Context(), &item); err != nil { if errors.Is(err, errNotFound) { http.Error(w, err.Error(), http.StatusNotFound) return } http.Error(w, err.Error(), http.StatusInternalServerError) return } } func (a *app) drop(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] if err := a.db.DeleteItem(r.Context(), id); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } } <file_sep>package main import ( "os" "tutor3" ) func main() { os.Exit(tutor3.RunApp(os.Args[1:])) } <file_sep>package tutor2 import ( "context" "encoding/json" "errors" "flag" "fmt" "log" "net/http" "net/url" "os" "os/signal" "syscall" "time" "github.com/gorilla/mux" ) func logRequest(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Println(r.Method, r.RequestURI) next.ServeHTTP(w, r) }) } func basicAuth(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user, pass, ok := r.BasicAuth() if !ok || user != "admin" || pass != "<PASSWORD>" { w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`) http.Error(w, "Unauthorized", http.StatusUnauthorized) return } next.ServeHTTP(w, r) }) } func (a *app) list(w http.ResponseWriter, r *http.Request) { items, err := a.db.ListItems(r.Context()) if err != nil { if errors.Is(err, errNotFound) { http.Error(w, err.Error(), http.StatusNotFound) return } http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") if err = json.NewEncoder(w).Encode(items); err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintln(w, err) } } func (a *app) location(url *url.URL, host, id string) string { return fmt.Sprintf("http://%s%s/%s", host, url.String(), id) } func (a *app) add(w http.ResponseWriter, r *http.Request) { var item Item err := json.NewDecoder(r.Body).Decode(&item) if err != nil || item.Name == "" { http.Error(w, "Invalid input", http.StatusBadRequest) return } if item.ID != "" { http.Error(w, "Key assigned", http.StatusConflict) return } id, err := a.db.AddItem(r.Context(), &item) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } w.Header().Set("Content-Type", "application/json") w.Header().Set("Location", a.location(r.URL, r.Host, id)) w.WriteHeader(http.StatusCreated) // we're not going to return an error if the encoding // fails, because we've already returned Location _ = json.NewEncoder(w).Encode(item) } func (a *app) get(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] item, err := a.db.GetItem(r.Context(), id) if err != nil { if errors.Is(err, errNotFound) { http.Error(w, err.Error(), http.StatusNotFound) return } http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") if err = json.NewEncoder(w).Encode(item); err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintln(w, err) } } func (a *app) put(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] var item Item err := json.NewDecoder(r.Body).Decode(&item) if err != nil || item.Name == "" { http.Error(w, "Invalid input", http.StatusBadRequest) return } item.ID = id // in case it was left out of the object data if err = a.db.UpdateItem(r.Context(), &item); err != nil { if errors.Is(err, errNotFound) { http.Error(w, err.Error(), http.StatusNotFound) return } http.Error(w, err.Error(), http.StatusInternalServerError) return } } func (a *app) drop(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] if err := a.db.DeleteItem(r.Context(), id); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } } type app struct { router *mux.Router server *http.Server db DB addr string project string collection string noAuth bool debug bool } func (a *app) serve() int { done := make(chan os.Signal, 1) signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) go func() { if err := a.server.ListenAndServe(); err != nil && err != http.ErrServerClosed { log.Fatalf("listen: %s\n", err) } }() log.Print("server started on ", a.addr) <-done log.Print("server stopping") ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer func() { cancel() log.Print("server stopped") }() if err := a.server.Shutdown(ctx); err != nil { log.Printf("server shutdown: %s", err) return -1 } return 0 } func (a *app) createClient() (err error) { a.db, err = NewClient(a.project, a.collection) return } func (a *app) makeServer() { a.server = &http.Server{ Addr: a.addr, Handler: a.router, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second, ReadHeaderTimeout: 20 * time.Second, } } func (a *app) addRoutes() { a.router.Use(logRequest) if a.noAuth { log.Println("AUTH DISABLED") } else { a.router.Use(basicAuth) } a.router.HandleFunc("/items", a.list).Methods("GET") a.router.HandleFunc("/items", a.add).Methods("POST") a.router.HandleFunc("/items/{id}", a.get).Methods("GET") a.router.HandleFunc("/items/{id}", a.put).Methods("PUT") a.router.HandleFunc("/items/{id}", a.drop).Methods("DELETE") } func (a *app) fromArgs(args []string) error { fl := flag.NewFlagSet("service", flag.ContinueOnError) fl.StringVar(&a.addr, "addr", "localhost:8080", "server address") fl.StringVar(&a.project, "proj", "tutor-dev", "GCP project") fl.StringVar(&a.collection, "coll", "items", "FS collection") fl.BoolVar(&a.debug, "debug", false, "enable debugging") fl.BoolVar(&a.noAuth, "no-auth", false, "disable auth") if err := fl.Parse(args); err != nil { return err } return nil } func (a *app) listRoutes() { visit := func(route *mux.Route, _ *mux.Router, _ []*mux.Route) error { t, err := route.GetPathTemplate() if err != nil { return err } m, err := route.GetMethods() if err != nil { return err } log.Println("route", t, m) return nil } if err := a.router.Walk(visit); err != nil { fmt.Fprintln(os.Stderr, err) } } func RunApp(args []string) int { a := app{router: mux.NewRouter()} if err := a.fromArgs(args); err != nil { fmt.Fprintln(os.Stderr, err) return -2 } if err := a.createClient(); err != nil { fmt.Fprintln(os.Stderr, err) return -2 } a.makeServer() a.addRoutes() if a.debug { a.listRoutes() } return a.serve() } <file_sep>package model type Item struct { ID string `json:"id" firestore:"id"` Name string `json:"name" firestore:"name"` Sku int `json:"sku" firestore:"sku"` } <file_sep>package tutor3 const ( skuDoc = "Next$SKU" nextField = "next" startSKU = 1000 ) type Item struct { ID string `json:"id" firestore:"id"` Name string `json:"name" firestore:"name"` SKU int `json:"sku" firestore:"sku"` } <file_sep>package db import ( "context" "errors" "fmt" "strconv" "github.com/google/uuid" "tutor4/graph/model" ) var ( errShouldFail = errors.New("mock should fail") errInvalid = errors.New("invalid operation") ) // mockDB is not thread-safe; we expect to run // UTs one at a time or with their own mock type mockDB struct { data map[string]*model.Item next int fail bool } func (m *mockDB) AddItem(_ context.Context, i *model.Item) (string, error) { if m.fail { return "", errShouldFail } if m.data == nil { m.data = make(map[string]*model.Item) m.next = 1000 } else if i.ID != "" { return "", errInvalid } add: i.ID = uuid.New().String() if _, ok := m.data[i.ID]; ok { goto add } i.SKU = m.next m.data[i.ID] = i m.next++ return i.ID, nil } func (m *mockDB) GetItem(_ context.Context, id string) (*model.Item, error) { if m.fail { return nil, errShouldFail } if i, ok := m.data[id]; ok { return i, nil } return nil, ErrNotFound } func (m *mockDB) GetItemBySKU(_ context.Context, sku int) (*model.Item, error) { if m.fail { return nil, errShouldFail } for _, v := range m.data { if v.SKU == sku { return v, nil } } return nil, ErrNotFound } func (m *mockDB) ListItems(_ context.Context) ([]*model.Item, error) { if m.fail { return nil, errShouldFail } result := make([]*model.Item, 0, len(m.data)) for _, i := range m.data { result = append(result, i) } return result, nil } func (m *mockDB) ListSKUs(_ context.Context) (map[string]string, error) { if m.fail { return nil, errShouldFail } result := make(map[string]string, len(m.data)) for _, i := range m.data { result[strconv.Itoa(i.SKU)] = i.ID } return result, nil } func (m *mockDB) UpdateItem(_ context.Context, i *model.Item) error { if m.fail { return errShouldFail } if m.data == nil { return errInvalid } m.data[i.ID] = i return nil } func (m *mockDB) DeleteItem(_ context.Context, id string) error { if m.fail { return errShouldFail } if m.data == nil { return errInvalid } delete(m.data, id) return nil } func (m *mockDB) preload() { if m.data == nil { m.data = make(map[string]*model.Item) m.next = 1000 } for i := 1; i < 10; i++ { id := uuid.New().String() item := model.Item{ID: id, Name: fmt.Sprintf("item-%d", i), SKU: m.next} m.data[id] = &item m.next++ } } <file_sep>module tutor2 go 1.14 require ( cloud.google.com/go/firestore v1.3.0 github.com/google/uuid v1.1.2 github.com/gorilla/mux v1.8.0 google.golang.org/grpc v1.32.0 ) <file_sep>package tutor2 import ( "context" "errors" "fmt" "log" "cloud.google.com/go/firestore" "github.com/google/uuid" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) type DB interface { AddItem(context.Context, *Item) (string, error) GetItem(context.Context, string) (*Item, error) ListItems(context.Context) ([]*Item, error) UpdateItem(context.Context, *Item) error DeleteItem(context.Context, string) error } type Client struct { fs *firestore.Client data *firestore.CollectionRef } func NewClient(project, collection string) (*Client, error) { if project == "" { return nil, errors.New("no projectID") } client, err := firestore.NewClient(context.Background(), project) if err != nil { return nil, fmt.Errorf("failed to create FS client: %w", err) } c := Client{ fs: client, data: client.Collection(collection), } return &c, nil } func (c *Client) Close() { c.fs.Close() } type Item struct { ID string `json:"id" firestore:"id"` Name string `json:"name" firestore:"name"` } var ErrNotFound = errors.New("not found") func (c *Client) AddItem(ctx context.Context, i *Item) (string, error) { var ref *firestore.DocumentRef add: i.ID = uuid.New().String() ref = c.data.Doc(i.ID) if _, err := ref.Create(ctx, i); err != nil { // it's unlikely to happen even once and virtually // impossible for it to happen twice in a row if status.Code(err) == codes.AlreadyExists { goto add } return "", err } return i.ID, nil } func (c *Client) GetItem(ctx context.Context, id string) (*Item, error) { doc, err := c.data.Doc(id).Get(ctx) if err != nil { if status.Code(err) == codes.NotFound { return nil, fmt.Errorf("%s: %w", id, ErrNotFound) } return nil, fmt.Errorf("item %s: %w", id, err) } var i Item if err = doc.DataTo(&i); err != nil { return nil, fmt.Errorf("item %s decode: %w", id, err) } return &i, nil } func (c *Client) ListItems(ctx context.Context) ([]*Item, error) { query := c.data.OrderBy(firestore.DocumentID, firestore.Asc) docs, err := query.Documents(ctx).GetAll() if err != nil { return nil, err } result := make([]*Item, 0, len(docs)) for _, doc := range docs { var i Item if err = doc.DataTo(&i); err != nil { log.Printf("item %s decode: %s", doc.Ref.ID, err) continue } result = append(result, &i) } return result, nil } func (c *Client) UpdateItem(ctx context.Context, i *Item) error { ref := c.data.Doc(i.ID) // set can create or overwrite existing data // so we need to see if it exists first if _, err := ref.Get(ctx); err != nil { if status.Code(err) == codes.NotFound { return fmt.Errorf("%s: %w", i.ID, ErrNotFound) } return err } if _, err := ref.Set(ctx, i); err != nil { return err } return nil } func (c *Client) DeleteItem(ctx context.Context, id string) error { _, err := c.data.Doc(id).Delete(ctx) if err != nil { return err } return nil } <file_sep>package tutor4 import ( "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/gorilla/mux" ) // TestWithApp **MUST** have a Firestore emulator // running and also uses the network; it may be // fragile if the port is already in use // // but it's a full door-to-door test of the app func TestWithApp(t *testing.T) { args := []string{"-addr", "localhost:8089"} go RunApp(args) time.Sleep(2 * time.Second) client := http.Client{} req, _ := http.NewRequest("GET", "http://localhost:8089/items", nil) req.SetBasicAuth("admin", "secret") resp, err := client.Do(req) if err != nil { t.Fatal(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { t.Fatal(err) } result := strings.TrimSpace(string(body)) if result != "[]" { t.Errorf("invalid response: %q: %[1]v", body) } } // TestWithMocks requires no network at all, so // the URL host doesn't really matter func TestWithMocks(t *testing.T) { d := new(mockDB) a := app{ router: mux.NewRouter(), db: d, noAuth: true, } d.preload() a.addRoutes() r := httptest.NewRequest("GET", "http://who-cares/items", nil) w := httptest.NewRecorder() a.router.ServeHTTP(w, r) resp := w.Result() if resp.StatusCode != http.StatusOK { t.Errorf("invalid response: %d", resp.StatusCode) } var result []Item if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { t.Fatal(err) } if len(result) != len(d.data) { t.Errorf("invalid result: %#v", result) } fmt.Println(result) for i := range result { if result[i].SKU < 1000 || result[i].SKU > 1009 { t.Errorf("invalid SKU: %#v", result[i]) } } } // TestWithMockServer uses only the loopback // connection with a random port func TestWithMockServer(t *testing.T) { d := new(mockDB) r := mux.NewRouter() s := httptest.NewServer(r) a := app{ router: r, db: d, noAuth: true, } d.preload() a.addRoutes() resp, err := http.Get(s.URL + "/items") if err != nil { t.Fatal(err) } if resp.StatusCode != http.StatusOK { t.Errorf("invalid response: %d", resp.StatusCode) } var result []Item if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { t.Fatal(err) } if len(result) != len(d.data) { t.Errorf("invalid result: %#v", result) } fmt.Println(result) } // TestFailWithMocks creates a DB that won't work func TestFailWithMocks(t *testing.T) { d := &mockDB{fail: true} a := app{ router: mux.NewRouter(), db: d, noAuth: true, } d.preload() a.addRoutes() r := httptest.NewRequest("GET", "http://who-cares/items", nil) w := httptest.NewRecorder() a.router.ServeHTTP(w, r) resp := w.Result() if resp.StatusCode != http.StatusInternalServerError { t.Errorf("invalid response: %d", resp.StatusCode) } } // TestNotFoundWithMocks tries to get an item that doesn't exist func TestNotFoundWithMocks(t *testing.T) { d := new(mockDB) a := app{ router: mux.NewRouter(), db: d, noAuth: true, } d.preload() a.addRoutes() r := httptest.NewRequest("GET", "http://who-cares/items/1", nil) w := httptest.NewRecorder() a.router.ServeHTTP(w, r) resp := w.Result() if resp.StatusCode != http.StatusNotFound { t.Errorf("invalid response: %d", resp.StatusCode) } } <file_sep>package main import ( "os" "tutor4" ) func main() { os.Exit(tutor4.RunApp(os.Args[1:])) } <file_sep>package main import ( "os" "tutor2" ) func main() { os.Exit(tutor2.RunApp(os.Args[1:])) }
51767442e14c7f2241014f3d58d0ac7ed05df73f
[ "Markdown", "Go Module", "Go" ]
18
Go
mholiday-nyt/web-tutorial
63bf0fe47dfb09b1ccc59806c46f00952ca7f652
6c77c932a301bd96fd5f535d6f7c7ae90e41f966
refs/heads/main
<file_sep>#!/usr/bin/env python # coding: utf-8 import os import random import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import time import torch.nn.functional as F from torch.utils.data import Dataset from torch.utils.data import DataLoader class CustomDataset(Dataset): def __init__(self, x_data, y_data, a_data): """ Store `x_data`. to `self.x`, `a_data` to `self.a`, and `y_data` to `self.y`. """ self.x = x_data self.a = a_data self.y = y_data def __len__(self): """ Return the number of samples (i.e. windows) """ return len(self.x) def __getitem__(self, index): """ Generates one sample of data. """ if torch.is_tensor(index): index = index.tolist() x = self.x[index] a = self.a[index] y = self.y[index] # convert activity and labels to tensor a = torch.tensor(a, dtype=torch.float32) y = torch.tensor(y, dtype=torch.float32) return x, a, y def cli_main(): _START_RUNTIME = time.time() # set seed seed = 96710 random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) os.environ["PYTHONHASHSEED"] = str(seed) # read pickle for subject 1 x_pkl = pd.read_pickle("../../data/interim/PPG_FieldStudy_CNN_Input/S1.pkl") # create dataframe xdf = pd.DataFrame(list(x_pkl.items()),columns = ['window_ID','Data']) # read lables for subject 1 file = '../../data/interim/PPG_FieldStudy_Windowed_Activity_Recognition/S1_labels.csv' ydf = pd.read_csv(file) #print(ydf.head(3)) # merge data and labels data_subject = pd.merge(xdf, ydf, on="window_ID") # create custom dataset dataset = CustomDataset(data_subject['Data'], data_subject['predicted_activity'], data_subject['Label']) # split dataset to train and test data train_size = int(0.8 * len(dataset)) test_size = len(dataset) - train_size train_dataset, test_dataset = torch.utils.data.random_split(dataset, [train_size, test_size]) # load a batch of train dataset data_loader = DataLoader(train_dataset, batch_size=128, shuffle=True, num_workers=0) loader_iter = iter(data_loader) x, a, y = next(loader_iter) # check dimensions print("shapeof x:", x.shape) print("shapeof a:",a.shape) print("shapeof y:",y.shape) #print(x) #print(a) #print(y) # end time _END_RUNTIME = time.time() # total time taken print(f"Runtime is {_END_RUNTIME - _START_RUNTIME}") pass if __name__ == '__main__': cli_main() <file_sep>#!/usr/bin/python import os from pathlib import Path, PurePath import random import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import time import torch.nn.functional as F from torch.utils.data import Dataset from torch.utils.data import DataLoader from tqdm import tqdm import re from sklearn.metrics import mean_absolute_error # set device device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') class CustomDataset(Dataset): def __init__(self, x_data, y_data): """ Store `x_data`. to `self.x` and `y_data` to `self.y`. """ self.x = x_data self.y = y_data def __len__(self): """ Return the number of samples (i.e. windows) """ return len(self.x) def __getitem__(self, index): """ Generates one sample of data. """ if torch.is_tensor(index): index = index.tolist() x = self.x['Data'][index] #self.x[index] y = self.y[index] activity = torch.tensor(self.x['predicted_activity'][index],dtype=torch.float32) # convert labels to tensor y = torch.tensor(y, dtype=torch.float32) return x, y ,activity def load_data(train_dataset, val_dataset): train_loader = torch.utils.data.DataLoader(train_dataset, batch_size = 256, shuffle = True) val_loader = torch.utils.data.DataLoader(val_dataset, batch_size = 256, shuffle = False) return train_loader, val_loader # CNN model class HeartbeatCNN(nn.Module): def __init__(self): super(HeartbeatCNN, self).__init__() self.conv1 = nn.Conv2d(4, 8, (1, 1), stride=(1, 1)) self.conv2 = nn.Conv2d(8, 16, (3, 3), stride=(1, 1)) self.conv3 = nn.Conv2d(16, 32, (1, 3), stride=(1, 1)) self.conv4 = nn.Conv2d(32, 64, (1, 3), stride=(1, 1)) self.conv5 = nn.Conv2d(64, 128, (1, 3), stride=(1, 1)) self.conv6 = nn.Conv2d(128, 256, (1, 3), stride=(1, 1)) self.conv7 = nn.Conv2d(256, 512, (1, 3), stride=(1, 1)) self.conv8 = nn.Conv2d(512, 1024, (1, 3), stride=(1, 1)) self.conv9 = nn.Conv2d(1024, 2048, (1, 3), stride=(1, 1)) self.conv10 = nn.Conv2d(2048, 32, (1, 1), stride=(1, 1)) self.pool = nn.MaxPool2d((1, 2), (1, 2)) self.flatten = nn.Flatten() self.fc1 = nn.Linear(193, 64) self.fc2 = nn.Linear(64, 1) self.dropout = nn.Dropout(p=0.5) def forward(self, x, activity): x = F.elu(self.conv1(x)) x = F.elu(self.conv2(x)) x = self.pool(F.elu(self.conv3(x))) x = self.pool(F.elu(self.conv4(x))) x = self.pool(F.elu(self.conv5(x))) x = self.pool(F.elu(self.conv6(x))) x = self.pool(F.elu(self.conv7(x))) x = self.pool(F.elu(self.conv8(x))) x = self.pool(F.elu(self.conv9(x))) x = F.elu(self.conv10(x)) x = self.flatten(x) activity = activity.resize_((activity.shape[0], 1)) x = torch.cat((x,activity),dim=1) x = F.elu(self.fc1(x)) x = self.dropout(x) x = self.fc2(x) return x def train_model(model, train_loader, n_epoch = None, optimizer=None, criterion=None): model.train() # prep model for training for epoch in range(n_epoch): curr_epoch_loss = [] for data, target,activity in tqdm(train_loader, bar_format='{l_bar}{bar:20}{r_bar}{bar:-20b}'): data, target = data.to(device), target.to(device) outputs = model.forward(data,activity) outputs = outputs.view(outputs.size(0)) loss = criterion(outputs, target) optimizer.zero_grad() loss.backward() optimizer.step() curr_epoch_loss.append(loss.cpu().detach().numpy()) print(f"Epoch {epoch}: curr_epoch_loss={np.mean(curr_epoch_loss)}") return model def eval_model(model, val_loader): model.eval() Y_pred = [] Y_true = [] for data, target, activity in tqdm(val_loader, bar_format='{l_bar}{bar:20}{r_bar}{bar:-20b}'): data, target = data.to(device), target.to(device) # run the inputs through the model outputs = model.forward(data,activity) # get predicted and target values pred_value = outputs.detach().cpu().numpy() target_value = target.detach().cpu().numpy() # append values to the lists Y_pred.append(pred_value) Y_true.append(target_value) # concatenate predictions and test data Y_pred = np.concatenate(Y_pred, axis=0) Y_true = np.concatenate(Y_true, axis=0) return Y_pred, Y_true def cli_main(): # set device # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # set seed seed = 42 random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) os.environ["PYTHONHASHSEED"] = str(seed) # Get all the processed data in interim folder data_path = "./data/" # find all files in folder files = [f.path for f in os.scandir(data_path) if f.is_file()] # sort in order by subject (numerical part) files.sort(key=lambda f: int(re.sub('\D', '', f))) # Get all the labels data in interim folder labels_path = "./labels" labels = [f.path for f in os.scandir(labels_path) if f.is_file() and 'labels' in PurePath(f).name] # sort in order by subject (numerical part) labels.sort(key=lambda f: int(re.sub('\D', '', f))) #print(files) #print(labels) #initialize CNN model model = HeartbeatCNN() #print(model) # check how many GPUs are available and parallelize model if torch.cuda.device_count() > 1: print("Using", torch.cuda.device_count(), "GPUs!") model = nn.DataParallel(model) # send model to GPU model.to(device) #initialize criterion and optimizer criterion = torch.nn.MSELoss() optimizer = torch.optim.Adam(model.parameters(), lr = 0.003) #set number of epochs n_epochs = 6 # save mae results mae_list = {} # iterate over all subjects for f, l in zip(files, labels): # current subject to process current_subject = os.path.splitext(os.path.basename(f))[0] # read pickle for subject x_pkl = pd.read_pickle(f) # create dataframe xdf = pd.DataFrame(list(x_pkl.items()),columns = ['window_ID','Data']) # read lables for subject ydf = pd.read_csv(l) # merge data and labels data_subject = pd.merge(xdf, ydf, on="window_ID") # create custom dataset dataset = CustomDataset(data_subject[['Data','predicted_activity']],data_subject['Label']) # split dataset to train and test data train_size = int(0.8 * len(dataset)) test_size = len(dataset) - train_size train_dataset, val_dataset = torch.utils.data.random_split(dataset, [train_size, test_size]) #load data into train and val train_loader, val_loader = load_data(train_dataset, val_dataset) # train model model = train_model(model, train_loader, n_epoch = n_epochs, optimizer=optimizer, criterion=criterion) # evaluate model y_pred, y_true = eval_model(model, val_loader) # calculate model performance mae = mean_absolute_error(y_true, y_pred) print(f"Subject {current_subject}: mae={mae}") mae_list[str(current_subject)] = mae # print mae results for all subjects/activities for key, value in mae_list.items(): print(key, ' : ', value) if __name__ == '__main__': cli_main() <file_sep># -*- coding: utf-8 -*- import logging from pathlib import Path, PurePath import pandas as pd import numpy as np import os def processData(file, output_path): # file name current_subject = os.path.split(file)[-1] # read data signals = pd.read_csv(file) # subset x, y, z acceleration, measured heart rate and activity signals = signals[['window_ID','wrist_ACC_x','wrist_ACC_y','wrist_ACC_z','wrist_BVP', 'Activity']] # group signals by activity sig_activity = [x for _, x in signals.groupby('Activity')] # save processed data to appropriate path # filename w/o ext current_subject = os.path.splitext(current_subject)[0] # save grouped signals in individual files for x in sig_activity: dump_dir = os.path.join(output_path, current_subject + "_Activity_" + str(x['Activity'].iloc[0]) + ".csv") x.to_csv(dump_dir,index=False) # Give prompt print("Processing of " + current_subject + " is complete ! \n") pass def cli_main(): # Get all the patient data in raw folder data_path = "../../data/interim/PPG_FieldStudy_Windowed/" files = [f.path for f in os.scandir(data_path) if f.is_file() and 'labels' not in PurePath(f).name] #  Make output path for saving the processed results output_path = "../../data/interim/PPG_FieldStudy_Activities/" if not os.path.exists(output_path): os.makedirs(output_path) #  Process each of the files and export to output path for file in files: #print(file) processData(file, output_path) if __name__ == '__main__': cli_main() <file_sep>numpy pandas tsfresh matplotlib category_encoders<file_sep># -*- coding: utf-8 -*- import logging from pathlib import Path import pandas as pd import numpy as np import pickle import matplotlib.pyplot as plt import gc from category_encoders.cat_boost import CatBoostEncoder from glob import glob import os import tsfresh from tsfresh.utilities.dataframe_functions import roll_time_series def load_data(path): with open(path, "rb") as f: data = pickle.load(f, encoding="latin-1") signal = pd.DataFrame(data["signal"]) ACC = pd.DataFrame(signal["chest"].ACC) ACC = ACC.iloc[::175, :] ACC.columns = ["ACC_x", "ACC_y", "ACC_z"] ACC.reset_index(drop=True, inplace=True) ECG = pd.DataFrame(signal["chest"].ECG) ECG = ECG.iloc[::175, :] ECG.reset_index(drop=True, inplace=True) Resp = pd.DataFrame(signal["chest"].Resp) Resp = Resp.iloc[::175, :] Resp.columns = ["Resp"] Resp.reset_index(drop=True, inplace=True) chest = pd.concat([ACC], sort=False) chest["Resp"] = Resp chest["ECG"] = ECG chest.reset_index(drop=True, inplace=True) chest = chest.add_prefix('chest_') ACC = pd.DataFrame(signal["wrist"].ACC) ACC = ACC.iloc[::8, :] ACC.columns = ["ACC_x", "ACC_y", "ACC_z"] ACC.reset_index(drop=True, inplace=True) EDA = pd.DataFrame(signal["wrist"].EDA) EDA.columns = ["EDA"] BVP = pd.DataFrame(signal["wrist"].BVP) BVP = BVP.iloc[::16, :] BVP.columns = ["BVP"] BVP.reset_index(drop=True, inplace=True) TEMP = pd.DataFrame(signal["wrist"].TEMP) TEMP.columns = ["TEMP"] wrist = pd.concat([ACC], sort=False) wrist["BVP"] = BVP wrist["TEMP"] = TEMP wrist.reset_index(drop=True, inplace=True) wrist = wrist.add_prefix('wrist_') signals = chest.join(wrist) for k, v in data["questionnaire"].items(): signals[k] = v rpeaks = data['rpeaks'] counted_rpeaks = [] index = 0 # index of rpeak element time = 175 # time portion count = 0 # number of rpeaks while (index < len(rpeaks)): rpeak = rpeaks[index] if (rpeak > time): # Rpeak appears after the time portion counted_rpeaks.append(count) count = 0 time += 175 else: count += 1 index += 1 # The rpeaks will probably end before the time portion so we need to fill the last portions with 0 if (len(counted_rpeaks) < np.size(signals, axis=0)): while (len(counted_rpeaks) < np.size(signals, axis=0)): counted_rpeaks.append(0) peaks = pd.DataFrame(counted_rpeaks) peaks.columns = ["Rpeaks"] signals = signals.join(peaks) activity = pd.DataFrame(data["activity"]).astype(int) activity.columns = ["Activity"] signals = signals.join(activity) label = pd.DataFrame(data["label"]) label = pd.DataFrame(np.repeat(label.values, 8, axis=0)) label.columns = ["Label"] if (np.size(label, axis=0) < np.size(activity, axis=0)): mean = label.mean() while (np.size(label, axis=0) < np.size(activity, axis=0)): label = label.append(mean, ignore_index=True) signals = signals.join(label) signals['Subject'] = data["subject"] gc.collect() return signals def processChestData(data): signal = pd.DataFrame(data["signal"]) ACC = pd.DataFrame(signal["chest"].ACC) ACC = ACC.iloc[::175, :] ACC.columns = ["ACC_x", "ACC_y", "ACC_z"] ACC.reset_index(drop=True, inplace=True) ECG = pd.DataFrame(signal["chest"].ECG) ECG = ECG.iloc[::175, :] ECG.reset_index(drop=True, inplace=True) Resp = pd.DataFrame(signal["chest"].Resp) Resp = Resp.iloc[::175, :] Resp.columns = ["Resp"] Resp.reset_index(drop=True, inplace=True) chest = pd.concat([ACC], sort=False) chest["Resp"] = Resp chest["ECG"] = ECG chest.reset_index(drop=True, inplace=True) chest = chest.add_prefix('chest_') pass def plot_confusion_matrix_2(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ import itertools if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.ylabel('True label') plt.xlabel('Predicted label') y = np.repeat(np.arange(0,len(classes)),15) plt.xlim(-0.5, len(np.unique(y))-0.5) plt.ylim(len(np.unique(y))-0.5, -0.5) plt.tight_layout() def findActivityAndEncode(signals,current_subject): # encode the necessary fields with CategoryBooster's encoder, which prevents data leaks on windows features_for_activity_recognition = ['wrist_ACC_x', 'wrist_ACC_y', 'wrist_ACC_z', 'wrist_BVP', 'wrist_TEMP'] X = signals[features_for_activity_recognition].values y = signals.Activity from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) from sklearn.ensemble import RandomForestClassifier rf = RandomForestClassifier(random_state=42) rf.fit(X_train, y_train); y_pred = rf.predict(X_test) score = rf.score(X_test, y_test) print(score) from sklearn.metrics import plot_confusion_matrix plot_confusion_matrix(rf, X_test, y_test,normalize='true') plt.title('Activity Score: '+ str(score)) output_path = "../../reports/figures/activity_recognition/" if not os.path.exists(output_path): os.makedirs(output_path) plt.savefig(output_path + current_subject) # predict the activity predicted_activities = rf.predict(X) signals['predicted_activity'] = predicted_activities # remove the unnecessary signals del signals["WEIGHT"] del signals["Gender"] del signals["AGE"] del signals["HEIGHT"] del signals["SKIN"] del signals["SPORT"] del signals["Activity"] cols = ["predicted_activity"] # Define train and target target = signals[['Label']] signals = signals.drop('Label', axis=1) # Define catboost encoder cbe_encoder = CatBoostEncoder(cols=cols) # Fit encoder and transform the features cbe_encoder.fit(signals, target) signals = cbe_encoder.transform(signals) signals['Label'] = target gc.collect() return signals def rollWindows(signals): """ Make distinct windows of 8 seconds, which are sliding Since target labels are made by taking "mean" of the 8 second heartbeat windows, the current sliding windows will provide more data and smoother transition to window changes """ # First, add time as seconds in 4 Hz as ordering column signals.reset_index(level=0, inplace=True) #signals=signals.iloc[:1000] signals = roll_time_series(signals, column_id="Subject", column_sort="index", max_timeshift=7, min_timeshift=7) signals['window_ID'] = signals['id'].apply(lambda x1: x1[0] + "_" + str(x1[1])) # Put the window ID to first place and remove excess id column del signals['id'] del signals['Subject'] #  we have subject embedded in window_ID now #  Reorder to get the window ID to first column cols = list(signals.columns) cols = [cols[-1]] + cols[:-1] signals = signals[cols] # make the window labels by taking the mean of HR over the 8 second sliding window window_labels = signals.groupby(['window_ID']).mean()['Label'] return signals,window_labels def processData(subfolder, output_path): # patient_path = "../../data/raw/PPG_FieldStudy/S1/S1.pkl" current_subject = os.path.split(subfolder)[-1] patient_path = os.path.join(subfolder, current_subject + ".pkl") signals = load_data(patient_path) #signals =signals[:10000] signals = findActivityAndEncode(signals,current_subject) signals,window_labels = rollWindows(signals) # save processed data to appropriate path dump_dir = os.path.join(output_path, current_subject + ".csv") signals.to_csv(dump_dir,index=False) # Save the labels of the windows to the appropriate path # add the predicted activities to label file as well for brevity del signals['Label'] window_labels = pd.DataFrame(window_labels) window_labels = pd.merge(window_labels, signals, left_on=window_labels.index, right_on='window_ID') window_labels = window_labels[['window_ID', 'Label', 'predicted_activity']] window_labels.drop_duplicates(subset=['window_ID'], keep='first', inplace=True) window_labels_dump_dir = os.path.join(output_path,current_subject+ "_labels.csv") window_labels.to_csv(window_labels_dump_dir) # Give prompt print("Processing of " + current_subject + " is complete ! \n") pass def cli_main(): # Get all the patient data in raw folder data_path = "../../data/raw/PPG_FieldStudy/" subfolders = [f.path for f in os.scandir(data_path) if f.is_dir()] #  Make output path for saving the processed results output_path = "../../data/interim/PPG_FieldStudy_Windowed_Activity_Recognition/" if not os.path.exists(output_path): os.makedirs(output_path) #  Process each of the files and export to output path for subfolder in subfolders: processData(subfolder, output_path) if __name__ == '__main__': cli_main() <file_sep># -*- coding: utf-8 -*- import logging from pathlib import Path import pandas as pd import numpy as np import pickle import matplotlib.pyplot as plt import gc from category_encoders.cat_boost import CatBoostEncoder from glob import glob import os import tsfresh from tsfresh.utilities.dataframe_functions import roll_time_series def load_data(path): with open(path, "rb") as f: data = pickle.load(f, encoding="latin-1") signal = pd.DataFrame(data["signal"]) ACC = pd.DataFrame(signal["chest"].ACC) ACC = ACC.iloc[::175, :] ACC.columns = ["ACC_x", "ACC_y", "ACC_z"] ACC.reset_index(drop=True, inplace=True) ECG = pd.DataFrame(signal["chest"].ECG) ECG = ECG.iloc[::175, :] ECG.reset_index(drop=True, inplace=True) Resp = pd.DataFrame(signal["chest"].Resp) Resp = Resp.iloc[::175, :] Resp.columns = ["Resp"] Resp.reset_index(drop=True, inplace=True) chest = pd.concat([ACC], sort=False) chest["Resp"] = Resp chest["ECG"] = ECG chest.reset_index(drop=True, inplace=True) chest = chest.add_prefix('chest_') ACC = pd.DataFrame(signal["wrist"].ACC) ACC = ACC.iloc[::8, :] ACC.columns = ["ACC_x", "ACC_y", "ACC_z"] ACC.reset_index(drop=True, inplace=True) EDA = pd.DataFrame(signal["wrist"].EDA) EDA.columns = ["EDA"] BVP = pd.DataFrame(signal["wrist"].BVP) BVP = BVP.iloc[::16, :] BVP.columns = ["BVP"] BVP.reset_index(drop=True, inplace=True) TEMP = pd.DataFrame(signal["wrist"].TEMP) TEMP.columns = ["TEMP"] wrist = pd.concat([ACC], sort=False) wrist["BVP"] = BVP wrist["TEMP"] = TEMP wrist.reset_index(drop=True, inplace=True) wrist = wrist.add_prefix('wrist_') signals = chest.join(wrist) for k, v in data["questionnaire"].items(): signals[k] = v rpeaks = data['rpeaks'] counted_rpeaks = [] index = 0 # index of rpeak element time = 175 # time portion count = 0 # number of rpeaks while (index < len(rpeaks)): rpeak = rpeaks[index] if (rpeak > time): # Rpeak appears after the time portion counted_rpeaks.append(count) count = 0 time += 175 else: count += 1 index += 1 # The rpeaks will probably end before the time portion so we need to fill the last portions with 0 if (len(counted_rpeaks) < np.size(signals, axis=0)): while (len(counted_rpeaks) < np.size(signals, axis=0)): counted_rpeaks.append(0) peaks = pd.DataFrame(counted_rpeaks) peaks.columns = ["Rpeaks"] signals = signals.join(peaks) activity = pd.DataFrame(data["activity"]).astype(int) activity.columns = ["Activity"] signals = signals.join(activity) label = pd.DataFrame(data["label"]) label = pd.DataFrame(np.repeat(label.values, 8, axis=0)) label.columns = ["Label"] if (np.size(label, axis=0) < np.size(activity, axis=0)): mean = label.mean() while (np.size(label, axis=0) < np.size(activity, axis=0)): label = label.append(mean, ignore_index=True) signals = signals.join(label) signals['Subject'] = data["subject"] gc.collect() return signals def processChestData(data): signal = pd.DataFrame(data["signal"]) ACC = pd.DataFrame(signal["chest"].ACC) ACC = ACC.iloc[::175, :] ACC.columns = ["ACC_x", "ACC_y", "ACC_z"] ACC.reset_index(drop=True, inplace=True) ECG = pd.DataFrame(signal["chest"].ECG) ECG = ECG.iloc[::175, :] ECG.reset_index(drop=True, inplace=True) Resp = pd.DataFrame(signal["chest"].Resp) Resp = Resp.iloc[::175, :] Resp.columns = ["Resp"] Resp.reset_index(drop=True, inplace=True) chest = pd.concat([ACC], sort=False) chest["Resp"] = Resp chest["ECG"] = ECG chest.reset_index(drop=True, inplace=True) chest = chest.add_prefix('chest_') pass def encodeFields(signals): # encode the necessary fields with CategoryBooster's encoder, which prevents data leaks on windows cols = ["Gender", "SKIN", "SPORT", "Activity"] # Define train and target target = signals[['Label']] signals = signals.drop('Label', axis=1) # Define catboost encoder cbe_encoder = CatBoostEncoder(cols=cols) # Fit encoder and transform the features cbe_encoder.fit(signals, target) signals = cbe_encoder.transform(signals) signals['Label'] = target gc.collect() return signals def rollWindows(signals): """ Make distinct windows of 8 seconds, which are sliding Since target labels are made by taking "mean" of the 8 second heartbeat windows, the current sliding windows will provide more data and smoother transition to window changes """ # First, add time as seconds in 4 Hz as ordering column signals.reset_index(level=0, inplace=True) #signals=signals.iloc[:1000] signals = roll_time_series(signals, column_id="Subject", column_sort="index", max_timeshift=7, min_timeshift=7) signals['window_ID'] = signals['id'].apply(lambda x1: x1[0] + "_" + str(x1[1])) # Put the window ID to first place and remove excess id column del signals['id'] del signals['Subject'] #  we have subject embedded in window_ID now #  Reorder to get the window ID to first column cols = list(signals.columns) cols = [cols[-1]] + cols[:-1] signals = signals[cols] # make the window labels by taking the mean of HR over the 8 second sliding window window_labels = signals.groupby(['window_ID']).mean()['Label'] return signals,window_labels def processData(subfolder, output_path): # patient_path = "../../data/raw/PPG_FieldStudy/S1/S1.pkl" current_subject = os.path.split(subfolder)[-1] patient_path = os.path.join(subfolder, current_subject + ".pkl") signals = load_data(patient_path) signals = encodeFields(signals) signals,window_labels = rollWindows(signals) # save processed data to appropriate path dump_dir = os.path.join(output_path, current_subject + ".csv") signals.to_csv(dump_dir,index=False) # Save the labels of the windows to the appropriate path window_labels_dump_dir = os.path.join(output_path,current_subject+ "_labels.csv") window_labels.to_csv(window_labels_dump_dir) # Give prompt print("Processing of " + current_subject + " is complete ! \n") pass def cli_main(): # Get all the patient data in raw folder data_path = "../../data/raw/PPG_FieldStudy/" subfolders = [f.path for f in os.scandir(data_path) if f.is_dir()] #  Make output path for saving the processed results output_path = "../../data/interim/PPG_FieldStudy_Windowed/" if not os.path.exists(output_path): os.makedirs(output_path) #  Process each of the files and export to output path for subfolder in subfolders: processData(subfolder, output_path) if __name__ == '__main__': cli_main() <file_sep># -*- coding: utf-8 -*- import logging from pathlib import Path import pandas as pd import numpy as np import pickle import matplotlib.pyplot as plt import gc from category_encoders.cat_boost import CatBoostEncoder from glob import glob from itertools import product import os import multiprocessing.pool from functools import reduce,partial import time from multiprocessing import Pool from tsfresh.utilities.dataframe_functions import impute from tsfresh import extract_features available_features= { "time_reversal_asymmetry_statistic": [{"lag": lag} for lag in range(1, 4)], "c3": [{"lag": lag} for lag in range(1, 4)], "cid_ce": [{"normalize": True}, {"normalize": False}], "symmetry_looking": [{"r": r * 0.05} for r in range(20)], "large_standard_deviation": [{"r": r * 0.05} for r in range(1, 20)], "quantile": [{"q": q} for q in [.1, .2, .3, .4, .6, .7, .8, .9]], "autocorrelation": [{"lag": lag} for lag in range(10)], "agg_autocorrelation": [{"f_agg": s, "maxlag": 40} for s in ["mean", "median", "var"]], "partial_autocorrelation": [{"lag": lag} for lag in range(10)], "number_cwt_peaks": [{"n": n} for n in [1, 5]], "number_peaks": [{"n": n} for n in [1, 3, 5, 10, 50]], "binned_entropy": [{"max_bins": max_bins} for max_bins in [10]], "index_mass_quantile": [{"q": q} for q in [.1, .2, .3, .4, .6, .7, .8, .9]], "cwt_coefficients": [{"widths": width, "coeff": coeff, "w": w} for width in [(2, 5, 10, 20)] for coeff in range(15) for w in (2, 5, 10, 20)], "spkt_welch_density": [{"coeff": coeff} for coeff in [2, 5, 8]], "ar_coefficient": [{"coeff": coeff, "k": k} for coeff in range(10 + 1) for k in [10]], "change_quantiles": [{"ql": ql, "qh": qh, "isabs": b, "f_agg": f} for ql in [0., .2, .4, .6, .8] for qh in [.2, .4, .6, .8, 1.] for b in [False, True] for f in ["mean", "var"] if ql < qh], "fft_coefficient": [{"coeff": k, "attr": a} for a, k in product(["real", "imag", "abs", "angle"], range(100))], "fft_aggregated": [{"aggtype": s} for s in ["centroid", "variance", "skew", "kurtosis"]], "value_count": [{"value": value} for value in [0, 1, -1]], "range_count": [{"min": -1, "max": 1}, {"min": 1e12, "max": 0}, {"min": 0, "max": 1e12}], "approximate_entropy": [{"m": 2, "r": r} for r in [.1, .3, .5, .7, .9]], "friedrich_coefficients": (lambda m: [{"coeff": coeff, "m": m, "r": 30} for coeff in range(m + 1)])(3), "max_langevin_fixed_point": [{"m": 3, "r": 30}], "linear_trend": [{"attr": "pvalue"}, {"attr": "rvalue"}, {"attr": "intercept"}, {"attr": "slope"}, {"attr": "stderr"}], "agg_linear_trend": [{"attr": attr, "chunk_len": i, "f_agg": f} for attr in ["rvalue", "intercept", "slope", "stderr"] for i in [5, 10, 50] for f in ["max", "min", "mean", "var"]], "augmented_dickey_fuller": [{"attr": "teststat"}, {"attr": "pvalue"}, {"attr": "usedlag"}], "number_crossing_m": [{"m": 0}, {"m": -1}, {"m": 1}], "energy_ratio_by_chunks": [{"num_segments": 10, "segment_focus": i} for i in range(10)], "ratio_beyond_r_sigma": [{"r": x} for x in [0.5, 1, 1.5, 2, 2.5, 3, 5, 6, 7, 10]], "linear_trend_timewise": [{"attr": "pvalue"}, {"attr": "rvalue"}, {"attr": "intercept"}, {"attr": "slope"}, {"attr": "stderr"}], "count_above": [{"t": 0}], "count_below": [{"t": 0}], "lempel_ziv_complexity": [{"bins": x} for x in [2, 3, 5, 10, 100]], "fourier_entropy": [{"bins": x} for x in [2, 3, 5, 10, 100]], "permutation_entropy": [{"tau": 1, "dimension": x} for x in [3, 4, 5, 6, 7]], "query_similarity_count": [{"query": None, "threshold": 0.0}], "matrix_profile": [{"threshold": 0.98, "feature": f} for f in ["min", "max", "mean", "median", "25", "75"]]} current_considered_features = {"maximum": None, "minimum": None, "mean_abs_change": None, "variation_coefficient": None, "fft_coefficient": [{"coeff": k, "attr": a} for a, k in product(["real", "imag", "abs", "angle"], range(25))], "sum_of_reoccurring_values": None, "linear_trend": [{"attr": "pvalue"}, {"attr": "rvalue"}, {"attr": "intercept"}, {"attr": "slope"}, {"attr": "stderr"}], "cid_ce": [{"normalize": True}, {"normalize": False}], "mean": None, "benford_correlation": None, "c3": [{"lag": lag} for lag in range(1, 4)], "max_langevin_fixed_point": [{"m": 3, "r": 30}], "number_crossing_m": [{"m": 0}, {"m": -1}, {"m": 1}], "autocorrelation": [{"lag": lag} for lag in range(5)], "percentage_of_reoccurring_values_to_all_values": None, "absolute_sum_of_changes": None, } def extractFeaturesAndSave(col_name,patient_data_path,output_path): # set the current considered feature extraction features_to_be_extracted = current_considered_features #  name of the column for window ID's window_ID = "window_ID" #  Sorting (time) column time_col = "index" cols = [window_ID,time_col,col_name] # just use id,time and column to extract features df = pd.read_csv(patient_data_path,usecols=cols) # nrows=1000 for key in features_to_be_extracted.keys(): feature_file_name = output_path + "/" + col_name + "_" + key + ".csv" # check if feature is already extracted if os.path.isfile(feature_file_name): continue # do not extract again settings = {key: features_to_be_extracted[key]} print("Extracting: " + feature_file_name) start = time.time() # without stacked dataframe extracted_features = extract_features(df, column_id=window_ID, column_sort=time_col, default_fc_parameters=settings,n_jobs=0) # n_jobs=0 end = time.time() print("Extracting: " + feature_file_name + " took" + str(end - start) + " seconds") """Impute the highly sparse features to get ready for training""" print("Start imputation") # replace NaN's with medians, -inf's with min value and +inf with max value # if no finite value exists, fill with zeros impute(extracted_features) print("End imputation") """Save the extracted features to file for later use""" extracted_features.to_csv(feature_file_name) # remove and collect garbage del extracted_features gc.collect() class NoDaemonProcess(multiprocessing.Process): """ Customize the multiprocessing class """ # make 'daemon' attribute always return False def _get_daemon(self): return False def _set_daemon(self, value): pass daemon = property(_get_daemon, _set_daemon) class MyPool(multiprocessing.pool.Pool): """""" Process = NoDaemonProcess def cli_main(): # Get all the patient data, which was encoded and windowed in interim folder data_path = "../../data/interim/PPG_FieldStudy_Windowed/" subfiles = glob(data_path + "/*.csv") #  Make output path for saving the processed results output_path = "../../data/processed/PPG_FieldStudy_Extracted/" if not os.path.exists(output_path): os.makedirs(output_path) #  Process each of the files and export to output path for patient_data_path in subfiles: """for each patient data, extract the features column by column so that they can be used as desired,seperately or altogether""" if "labels" in patient_data_path: continue # Extract current subject from filename and make a dedicated directory current_subject = os.path.splitext(os.path.split(patient_data_path)[-1])[0] patient_output_path = os.path.join(output_path,current_subject) if not os.path.exists(patient_output_path): os.makedirs(patient_output_path) # find columns col_list = pd.read_csv(patient_data_path, nrows=2).columns col_list = list(col_list)[2:] if "Label" in col_list: col_list.remove("Label") # remove label from extraction # Create the partial function with pool and start extraction in parallel func = partial(extractFeaturesAndSave,patient_data_path=patient_data_path ,output_path= patient_output_path) pool = Pool() # MyPool() pool.map(func, col_list) pool.close() pool.join() #extractFeaturesAndSave(patient_data_path=patient_data_path,col_name=col_name,output_path= patient_output_path) if __name__ == '__main__': cli_main()<file_sep># -*- coding: utf-8 -*- import logging from pathlib import Path, PurePath import pandas as pd import numpy as np import os from scipy import signal import pickle from tqdm import tqdm from scipy.stats import zscore import torch def save_object(obj, filename): with open(filename, 'wb') as output: # Overwrites any existing file. pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL) def processData(file, output_path): """ input: file - file to be processed output_path - file to save processed data """ # current file to process current_subject = os.path.split(file)[-1] fname=os.path.splitext(current_subject)[0] #print(fname) # read data from csv file signals = pd.read_csv(file) #print(signals.shape) # group signals by activity sig_window = [x for _, x in signals.groupby('window_ID')] # dictionary of lists to save window transforms dictlist = {} # loop over all window_IDs for x in tqdm(sig_window, bar_format='{l_bar}{bar:20}{r_bar}{bar:-20b}'): # list of dataframes to store results listSxx = [] # take short time Fourier transform of the relevant columns for var in ['wrist_ACC_x','wrist_ACC_y','wrist_ACC_z','wrist_BVP']: #print("Processing of " + current_subject + " " + var + "\n") _ , _, Sxx = signal.stft(sig_window[0][var], fs=8, nfft=2048, nperseg=8) # calculate magnitude, transpose, and convert to DataFrame Sxx = pd.DataFrame(np.transpose(np.abs(Sxx))) # z-score normalization by row Sxx = Sxx.apply(zscore, axis=1) # convert transformed data to list of tensors list_of_tensors = [torch.tensor(df, dtype=torch.float32) for df in Sxx] # stack tensors to get tyhe right sshape (3, 1025) tstack = torch.stack(list_of_tensors) # append dataframes to the list listSxx.append(tstack) # stack the channel tensors - yields a tensor (4, 3, 1025) cstack = torch.stack(listSxx) # add stacked channels to the dictionary with window_ID as key dictlist[str(x['window_ID'].iloc[0])] = cstack # save processed data to appropriate path dump_file = os.path.join(output_path, fname+".pkl") save_object(dictlist,dump_file) # Give prompt print("Processing of " + current_subject + " is complete ! \n") pass def cli_main(): # Get all the patient data in raw folder data_path = "../../data/interim/PPG_FieldStudy_Windowed_Activity_Recognition/" # find all files in folder files = [f.path for f in os.scandir(data_path) if f.is_file() and 'labels' not in PurePath(f).name] # sort them by time files.sort(key=lambda x: os.path.getmtime(x)) #  Make output path for saving the processed results output_path = "../../data/interim/PPG_FieldStudy_CNN_Input/" if not os.path.exists(output_path): os.makedirs(output_path) #  Process each of the files and save to output path for file in files: processData(file, output_path) #processData(files[0], output_path) if __name__ == '__main__': cli_main() <file_sep>from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='PPG Dalia dataset HR estimation', author='UIUC-teamDL', license='MIT', ) <file_sep># -*- coding: utf-8 -*- import logging from pathlib import Path, PurePath import pandas as pd import numpy as np import os from scipy import signal import matplotlib.pyplot as plt import pickle from tqdm import tqdm import re def plotData(file, output_path): """ input: file - file to be processed output_path - file to save processed data """ # current file to process current_subject = os.path.split(file)[-1] fname=os.path.splitext(current_subject)[0] #print(fname) # read data from csv file signals = pd.read_csv(file) #print(signals.shape) # take short time Fourier transform of the relevant columns for var in ['wrist_ACC_x','wrist_ACC_y','wrist_ACC_z','wrist_BVP']: #print("Processing of " + current_subject + " " + var + "\n") # _ , _, Sxx = signal.stft(sig_window[0][var], fs=8, nfft=2048, nperseg=8) f, t, Sxx = signal.spectrogram(signals[var][12000:15000], fs=8, nfft=2048, nperseg=8) plt.pcolormesh(t, f, Sxx, shading='auto') plt.title(var) plt.ylabel('Frequency [Hz]') plt.xlabel('Time [sec]') plt.savefig(output_path + current_subject + var + '.png') # Give prompt print("Processing of " + current_subject + " is complete ! \n") pass def cli_main(): # Get all the patient data in raw folder data_path = "../../data/interim/PPG_FieldStudy_Windowed_Activity_Recognition/" # find all files in folder files = [f.path for f in os.scandir(data_path) if f.is_file() and 'labels' not in PurePath(f).name] # sort in order by subject (numerical part) files.sort(key=lambda f: int(re.sub('\D', '', f))) #  Make output path for saving the processed results output_path = "../../reports/figures/spectra/" if not os.path.exists(output_path): os.makedirs(output_path) #  Process each of the files and save to output path for file in files: plotData(file, output_path) #plotData(files[0], output_path) if __name__ == '__main__': cli_main()
d39f0c63fca0a2d6ccde8801282a5f261fa86d70
[ "Python", "Text" ]
10
Python
denizhankara/PPG-DaLiA
cd5da28ee4da2b6f83750f1cae6cfc6cdcc7f04b
68372dcf0de91c8c0b0a313785d9afeb9aba220c
refs/heads/master
<repo_name>Nuclearfossil/sample<file_sep>/premake5.lua -- premake5.lua workspace "Sample" configurations { "Debug", "Release" } platforms { "x86", "x86_64" } location "build" project "Sample01" kind "ConsoleApp" language "C++" location "build/sample01" targetdir "bin/%{cfg.buildcfg}" files { "%{prj.name}/src/**.h", "%{prj.name}/src/**.cpp" } filter "configurations:Debug" defines { "DEBUG" } flags { "Symbols" } filter "configurations:Release" defines { "NDEBUG" } optimize "On" filter "platforms:x86" system "Windows" architecture "x86" filter "platforms:x86_64" system "Windows" architecture "x86_64" <file_sep>/sample01/src/main.cpp #include <stdio.h> int main(int argc, char * argv[]) { puts("Hello there!"); return 0; }
277605200d3954d03e1aafc03b40642fe127474d
[ "C++", "Lua" ]
2
Lua
Nuclearfossil/sample
6aecede6ee85a60138127f929986b330a07d877a
3b65cd0aa4d41b8c5da31c9f6512a7c93999d9b0
refs/heads/master
<repo_name>TTeemu/CourDDP<file_sep>/README.md # CourDDP repo for coursera developing data products course # Purpose Purpose of this repository is to show server.R and ui.R files for shiny-app develop for corsera Developing Data Products course. # Instuctions In the application one can examine the influence of adding and removing terms in linear regression setting thusly examine under- and over fitting phenomena. #Link https://tteemu.shinyapps.io/CourseraDevDataProd/ <file_sep>/ui.R # This is the user-interface definition of a Shiny web application. # You can find out more about building applications with Shiny here: # # http://shiny.rstudio.com # library(shiny) shinyUI(fluidPage( # Application title titlePanel("Over-fitting and under-ftting with linear regression"), # Sidebar with a slider input for number of bins sidebarLayout( sidebarPanel( sliderInput("sample", "From, to", min = 2, max = 20, value = 10, step=0.01), sliderInput("terms", "Number and order of polynomial terms", min = 2, max = 10, value = 2), sliderInput("norn", "normal random standard deviation", min = 0.01, max = 2, value = 0.05), p("Purpose of this shiny-app is to show the problem associated with over-fitting by adding additional terms in linear regression"), p("The model to fit is the following form: y = a + B1x^1 +B2x^2 + .... + Bnx^n and so forth depending on the terms included in the model "), p("In the plot the red line shows the real data producing function without noise and black line shows the prediction function") ), # Show a plot of the generated distribution mainPanel( plotOutput("scatPlot"), h3("Model summary:"), verbatimTextOutput("summary") ) ) )) <file_sep>/server.R # This is the server logic for a Shiny web application. # You can find out more about building applications with Shiny here: # # http://shiny.rstudio.com # library(shiny) library(caret) shinyServer(function(input, output) { output$scatPlot <- renderPlot({ # generate sample data set.seed(100) x <- seq(2,input$sample,by=0.05) y <- sin(x)+rnorm(length(x),0,input$norn) X <- matrix(data=NA,nrow=length(x),ncol=10) X[,1] <- x for(i in 2:10){ X[,i] <- (X[,1])^i } if(input$terms == 1){ dat <- as.data.frame(cbind(y,x)) overFit <- lm(y~x,data=dat) }else{ overFit <- train(x=X[,1:input$terms],y=y,method="lm") } # draw the histogram with the specified number of bins plot(x,y,type="p",col="black",main="sin(x) , prediction model and sin(x) + rnorm(0,sd)") lines(x,predict(overFit,X[,1:input$terms])) lines(x,sin(x),col="red") output$summary <- renderPrint({ summary(overFit) }) }) })
66aee638e6e9ad34fb2ed44018facc439618e82d
[ "Markdown", "R" ]
3
Markdown
TTeemu/CourDDP
8d04a88c7784702547fe75414d3569abfb5a3031
f50baffbb1cf3f1e83de7eedd7dcb50e1a2129e1
refs/heads/master
<repo_name>jrubiales/apertium-formats-transpilers<file_sep>/src/main/java/org/apertium/transpiler/freya/Freya2XML.java package org.apertium.transpiler.freya; import java.io.IOException; import org.antlr.v4.runtime.*; /** * * @author juanfran */ public class Freya2XML { String filePath; public Freya2XML() { } public Freya2XML(String filePath) { this.filePath = filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public String getFilePath() { return filePath; } public void parse() throws IOException { ANTLRFileStream in = new ANTLRFileStream(filePath); FreyaLexer lexer = new FreyaLexer(in); CommonTokenStream tokens = new CommonTokenStream(lexer); FreyaParser parser = new FreyaParser(tokens); parser.stat(); } } <file_sep>/README.md # Apertium Formats Transpilers # This repository provides some tools that arise aiming to design a simple text based format to write structural transfer rules and dictionaries. The provided tools consist of four transpilers which two of them is used to generate the translations between the transfer file formats and the other two to generate the translations between the dictionaries files, that is, exist two transpilers to convert from the actual format (XML) to the new format and vice versa both for the Dictionaries files, and another two for the Transfer files. ## Language Features ## * High-Level language * Easy to extend * Fast and Efficient * Portable compiler * Semantic errors ## Transpilers ## The name of the transpilers are Freya and Loki for the transfer files and dictionaries respectively. Input | Transpiler | Output --------------------- | -------------- | ------------- XML Dictionary (.xml) | Loki | Loki format (.lk) Loki format (.lk) | Loki | XML Dictionary (.xml) XML Transfer (.xml) | Freya | Freya format (.fy) Freya format (.fy) | Freya | XML Transfer (.xml) ## Building from source ## The project is developed using Netbeans IDE and Maven to manage it and simplify the use of third party dependencies. ## Using the transpilers ## java -jar ApertiumFormatsTranspilers [Transpiler type] [File] Transpiler type: + loki: Transpile from XML to Loki format (filename.lk) or vice versa. + freya: Transpile from XML to Freya format (filename.fy) or vice versa. File: + If this argument is a XML file, the transpiler will convert from XML to Loki/Freya format. Otherwise it will covert from Loki/Freya format to XML. The transpiler will detect the input file and will output the appropriate format automatically. ## Translations examples ## ### Dictionaries ### ``` <alphabet>·ÀÁÂÄÇÈÉÊËÌÍÎÏÑÒÓÔÖÙÚÛÜàáâäçèéêëìíîïñòóôöùúûüABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz</alphabet> alphabet = "·ÀÁÂÄÇÈÉÊËÌÍÎÏÑÒÓÔÖÙÚÛÜàáâäçèéêëìíîïñòóôöùúûüABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"; ``` ``` <sdefs> <sdef n="n" /> <sdef n="GD" /> <sdef n="det" /> </sdefs> symbols = n, GD, det; ``` ``` <section id="main" type="standard"> <e r="LR"> <p> <l>dog<s n="n"/></l> <r>gos<s n="n"/><s n="GD"/></r> </p> </e> <e r="RL"> <p> <l>the<s n="det"/></l> <r>el<s n="det"/></r> </p> </e> </section> section main(type="standard") entry "dog" n > "gos" n GD"; end /* end entry */ entry "the" det < "e" det; end /* end entry */ end /* end section */ ``` ## Semantic errors ## ``` symbols = n, adj, ... , adj; "Symbol adj is already defined (1:69)" ``` ``` symbols = np; section main(type ="standard") entry "dog" n < "gos" n ; end /* end entry */ end /* end section */ "Undefined symbol: n (6:18)" "Undefined symbol: n (6:28)" ```<file_sep>/src/main/java/org/apertium/transpiler/freya/Type.java package org.apertium.transpiler.freya; /** * * @author juanfran */ public class Type { public static final int CATLEX = 1, ATTR = 2, VAR = 3, LIST = 4, MACRO = 5, CHUNK = 6; }
9a22353aa0dcdbb193b5113b737f957ad620974a
[ "Markdown", "Java" ]
3
Java
jrubiales/apertium-formats-transpilers
67aeece4387947e6ec532a430412f83bc9ebcc05
005c4f871ebd75ef78dc4d8470a4f340502c1175
refs/heads/master
<repo_name>linksmart/thing-directory<file_sep>/Dockerfile FROM golang:1.14-alpine as builder COPY . /home WORKDIR /home ENV CGO_ENABLED=0 ARG version ARG buildnum RUN go build -v -ldflags "-X main.Version=$version -X main.BuildNumber=$buildnum" ########### FROM alpine RUN apk --no-cache add ca-certificates ARG version ARG buildnum LABEL NAME="LinkSmart Thing Directory" LABEL VERSION=${version} LABEL BUILD=${buildnum} WORKDIR /home COPY --from=builder /home/thing-directory . COPY sample_conf/thing-directory.json /home/conf/ COPY wot/wot_td_schema.json /home/conf/ ENV TD_STORAGE_DSN=/data VOLUME /data EXPOSE 8081 ENTRYPOINT ["./thing-directory"] # Note: this loads the default config files from /home/conf/. Use --help to to learn about CLI arguments.<file_sep>/catalog/ldbstorage.go // Copyright 2014-2016 Fraunhofer Institute for Applied Information Technology FIT package catalog import ( "bytes" "context" "encoding/json" "flag" "fmt" "log" "net/url" "sync" "github.com/linksmart/service-catalog/v3/utils" "github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb/opt" ) // LevelDB storage type LevelDBStorage struct { db *leveldb.DB wg sync.WaitGroup } func NewLevelDBStorage(dsn string, opts *opt.Options) (Storage, error) { url, err := url.Parse(dsn) if err != nil { return nil, err } // Open the database file db, err := leveldb.OpenFile(url.Path, opts) if err != nil { return nil, err } return &LevelDBStorage{db: db}, nil } // CRUD func (s *LevelDBStorage) add(id string, td ThingDescription) error { if id == "" { return fmt.Errorf("ID is not set") } bytes, err := json.Marshal(td) if err != nil { return err } found, err := s.db.Has([]byte(id), nil) if err != nil { return err } if found { return &ConflictError{id + " is not unique"} } err = s.db.Put([]byte(id), bytes, nil) if err != nil { return err } return nil } func (s *LevelDBStorage) get(id string) (ThingDescription, error) { bytes, err := s.db.Get([]byte(id), nil) if err == leveldb.ErrNotFound { return nil, &NotFoundError{id + " is not found"} } else if err != nil { return nil, err } var td ThingDescription err = json.Unmarshal(bytes, &td) if err != nil { return nil, err } return td, nil } func (s *LevelDBStorage) update(id string, td ThingDescription) error { bytes, err := json.Marshal(td) if err != nil { return err } found, err := s.db.Has([]byte(id), nil) if err != nil { return err } if !found { return &NotFoundError{id + " is not found"} } err = s.db.Put([]byte(id), bytes, nil) if err != nil { return err } return nil } func (s *LevelDBStorage) delete(id string) error { found, err := s.db.Has([]byte(id), nil) if err != nil { return err } if !found { return &NotFoundError{id + " is not found"} } err = s.db.Delete([]byte(id), nil) if err != nil { return err } return nil } func (s *LevelDBStorage) list(page int, perPage int) ([]ThingDescription, int, error) { total, err := s.total() if err != nil { return nil, 0, err } offset, limit, err := utils.GetPagingAttr(total, page, perPage, MaxPerPage) if err != nil { return nil, 0, &BadRequestError{fmt.Sprintf("Unable to paginate: %s", err)} } // TODO: is there a better way to do this? // github.com/syndtr/goleveldb/leveldb/iterator devices := make([]ThingDescription, limit) s.wg.Add(1) iter := s.db.NewIterator(nil, nil) i := 0 for iter.Next() { var td ThingDescription err = json.Unmarshal(iter.Value(), &td) if err != nil { return nil, 0, err } if i >= offset && i < offset+limit { devices[i-offset] = td } else if i >= offset+limit { break } i++ } iter.Release() s.wg.Done() err = iter.Error() if err != nil { return nil, 0, err } return devices, total, nil } func (s *LevelDBStorage) listAllBytes() ([]byte, error) { s.wg.Add(1) iter := s.db.NewIterator(nil, nil) var buffer bytes.Buffer buffer.WriteString("[") separator := byte(',') first := true for iter.Next() { if first { first = false } else { buffer.WriteByte(separator) } buffer.Write(iter.Value()) } buffer.WriteString("]") iter.Release() s.wg.Done() err := iter.Error() if err != nil { return nil, err } return buffer.Bytes(), nil } func (s *LevelDBStorage) total() (int, error) { c := 0 s.wg.Add(1) iter := s.db.NewIterator(nil, nil) for iter.Next() { c++ } iter.Release() s.wg.Done() err := iter.Error() if err != nil { return 0, err } return c, nil } func (s *LevelDBStorage) iterator() <-chan ThingDescription { serviceIter := make(chan ThingDescription) go func() { defer close(serviceIter) s.wg.Add(1) defer s.wg.Done() iter := s.db.NewIterator(nil, nil) defer iter.Release() for iter.Next() { var td ThingDescription err := json.Unmarshal(iter.Value(), &td) if err != nil { log.Printf("LevelDB Error: %s", err) return } serviceIter <- td } err := iter.Error() if err != nil { log.Printf("LevelDB Error: %s", err) } }() return serviceIter } func (s *LevelDBStorage) iterateBytes(ctx context.Context) <-chan []byte { bytesCh := make(chan []byte, 0) // must be zero go func() { defer close(bytesCh) s.wg.Add(1) defer s.wg.Done() iter := s.db.NewIterator(nil, nil) defer iter.Release() Loop: for iter.Next() { select { case <-ctx.Done(): //log.Println("LevelDB: canceled") break Loop default: b := make([]byte, len(iter.Value())) copy(b, iter.Value()) bytesCh <- b } } err := iter.Error() if err != nil { log.Printf("LevelDB Error: %s", err) } }() return bytesCh } func (s *LevelDBStorage) Close() { s.wg.Wait() err := s.db.Close() if err != nil { log.Printf("Error closing storage: %s", err) } if flag.Lookup("test.v") == nil { log.Println("Closed leveldb.") } } <file_sep>/catalog/events.go package catalog // EventListener interface that listens to TDD events. type EventListener interface { CreateHandler(new ThingDescription) error UpdateHandler(old ThingDescription, new ThingDescription) error DeleteHandler(old ThingDescription) error } // eventHandler implements sequential fav-out/fan-in of events from registry type eventHandler []EventListener func (h eventHandler) created(new ThingDescription) error { for i := range h { err := h[i].CreateHandler(new) if err != nil { return err } } return nil } func (h eventHandler) updated(old ThingDescription, new ThingDescription) error { for i := range h { err := h[i].UpdateHandler(old, new) if err != nil { return err } } return nil } func (h eventHandler) deleted(old ThingDescription) error { for i := range h { err := h[i].DeleteHandler(old) if err != nil { return err } } return nil } <file_sep>/init.go // Copyright 2014-2016 Fraunhofer Institute for Applied Information Technology FIT package main import ( "log" "os" ) const ( EnvVerbose = "VERBOSE" // print extra information e.g. line number) EnvDisableLogTime = "DISABLE_LOG_TIME" // disable timestamp in logs ) func init() { log.SetOutput(os.Stdout) log.SetFlags(0) logFlags := log.LstdFlags if evalEnv(EnvDisableLogTime) { logFlags = 0 } if evalEnv(EnvVerbose) { logFlags = logFlags | log.Lshortfile } log.SetFlags(logFlags) } // evalEnv returns the boolean value of the env variable with the given key func evalEnv(key string) bool { return os.Getenv(key) == "1" || os.Getenv(key) == "true" || os.Getenv(key) == "TRUE" } <file_sep>/notification/sse.go package notification import ( "encoding/json" "fmt" "log" "net/http" "strings" "github.com/gorilla/mux" "github.com/linksmart/thing-directory/catalog" "github.com/linksmart/thing-directory/wot" ) const ( QueryParamType = "type" QueryParamFull = "diff" HeaderLastEventID = "Last-Event-ID" ) type SSEAPI struct { controller NotificationController contentType string } func NewSSEAPI(controller NotificationController, version string) *SSEAPI { contentType := "text/event-stream" if version != "" { contentType += ";version=" + version } return &SSEAPI{ controller: controller, contentType: contentType, } } func (a *SSEAPI) SubscribeEvent(w http.ResponseWriter, req *http.Request) { diff, err := parseQueryParameters(req) if err != nil { catalog.ErrorResponse(w, http.StatusBadRequest, err) return } eventTypes, err := parsePath(req) if err != nil { catalog.ErrorResponse(w, http.StatusBadRequest, err) return } flusher, ok := w.(http.Flusher) if !ok { catalog.ErrorResponse(w, http.StatusInternalServerError, "Streaming unsupported") return } w.Header().Set("Content-Type", a.contentType) messageChan := make(chan Event) lastEventID := req.Header.Get(HeaderLastEventID) a.controller.subscribe(messageChan, eventTypes, diff, lastEventID) go func() { <-req.Context().Done() // unsubscribe to events and close the messageChan a.controller.unsubscribe(messageChan) }() for event := range messageChan { //data, err := json.MarshalIndent(event.Data, "data: ", "") data, err := json.Marshal(event.Data) if err != nil { log.Printf("error marshaling event %v: %s", event, err) } fmt.Fprintf(w, "event: %s\n", event.Type) fmt.Fprintf(w, "id: %s\n", event.ID) fmt.Fprintf(w, "data: %s\n\n", data) flusher.Flush() } } func parseQueryParameters(req *http.Request) (bool, error) { diff := false req.ParseForm() // Parse diff or just ID if strings.EqualFold(req.Form.Get(QueryParamFull), "true") { diff = true } return diff, nil } func parsePath(req *http.Request) ([]wot.EventType, error) { // Parse event type to be subscribed to params := mux.Vars(req) event := params[QueryParamType] if event == "" { return []wot.EventType{wot.EventTypeCreate, wot.EventTypeUpdate, wot.EventTypeDelete}, nil } eventType := wot.EventType(event) if !eventType.IsValid() { return nil, fmt.Errorf("invalid type in path") } return []wot.EventType{eventType}, nil } <file_sep>/main.go // Copyright 2014-2016 Fraunhofer Institute for Applied Information Technology FIT package main import ( "flag" "fmt" "log" "net" "net/http" "os" "os/signal" "syscall" "github.com/codegangsta/negroni" "github.com/gorilla/context" "github.com/justinas/alice" _ "github.com/linksmart/go-sec/auth/keycloak/obtainer" _ "github.com/linksmart/go-sec/auth/keycloak/validator" "github.com/linksmart/go-sec/auth/validator" "github.com/linksmart/thing-directory/catalog" "github.com/linksmart/thing-directory/notification" "github.com/linksmart/thing-directory/wot" "github.com/rs/cors" uuid "github.com/satori/go.uuid" ) const LINKSMART = ` ╦ ╦ ╔╗╔ ╦╔═ ╔═╗ ╔╦╗ ╔═╗ ╦═╗ ╔╦╗ ║ ║ ║║║ ╠╩╗ ╚═╗ ║║║ ╠═╣ ╠╦╝ ║ ╩═╝ ╩ ╝╚╝ ╩ ╩ ╚═╝ ╩ ╩ ╩ ╩ ╩╚═ ╩ ` const ( SwaggerUISchemeLess = "linksmart.github.io/swagger-ui/dist" Spec = "https://raw.githubusercontent.com/linksmart/thing-directory/{version}/apidoc/openapi-spec.yml" SourceCodeRepo = "https://github.com/linksmart/thing-directory" ) var ( confPath = flag.String("conf", "conf/thing-directory.json", "Configuration file path") version = flag.Bool("version", false, "Print the API version") Version string // set with build flags BuildNumber string // set with build flags ) func main() { flag.Parse() if *version { fmt.Println(Version) return } fmt.Print(LINKSMART) log.Printf("Starting Thing Directory") defer log.Println("Stopped.") if Version != "" { log.Printf("Version: %s", Version) } if BuildNumber != "" { log.Printf("Build Number: %s", BuildNumber) } config, err := loadConfig(*confPath) if err != nil { panic("Error reading config file:" + err.Error()) } log.Printf("Loaded config file: %s", *confPath) if config.ServiceID == "" { config.ServiceID = uuid.NewV4().String() log.Printf("Service ID not set. Generated new UUID: %s", config.ServiceID) } if len(config.Validation.JSONSchemas) > 0 { err = wot.LoadJSONSchemas(config.Validation.JSONSchemas) if err != nil { panic("error loading validation JSON Schemas: " + err.Error()) } log.Printf("Loaded JSON Schemas: %v", config.Validation.JSONSchemas) } else { log.Printf("Warning: No configuration for JSON Schemas. TDs will not be validated.") } // Setup API storage var storage catalog.Storage switch config.Storage.Type { case catalog.BackendLevelDB: storage, err = catalog.NewLevelDBStorage(config.Storage.DSN, nil) if err != nil { panic("Failed to start LevelDB storage:" + err.Error()) } defer storage.Close() default: panic("Could not create catalog API storage. Unsupported type:" + config.Storage.Type) } controller, err := catalog.NewController(storage) if err != nil { panic("Failed to start the controller:" + err.Error()) } defer controller.Stop() // Create catalog API object api := catalog.NewHTTPAPI(controller, Version) // Start notification var eventQueue notification.EventQueue switch config.Storage.Type { case catalog.BackendLevelDB: eventQueue, err = notification.NewLevelDBEventQueue(config.Storage.DSN+"/sse", nil, 1000) if err != nil { panic("Failed to start LevelDB storage for SSE events:" + err.Error()) } defer eventQueue.Close() default: panic("Could not create SSE storage. Unsupported type:" + config.Storage.Type) } notificationController := notification.NewController(eventQueue) notifAPI := notification.NewSSEAPI(notificationController, Version) defer notificationController.Stop() controller.AddSubscriber(notificationController) nRouter, err := setupHTTPRouter(&config.HTTP, api, notifAPI) if err != nil { panic(err) } // Start listener addr := fmt.Sprintf("%s:%d", config.HTTP.BindAddr, config.HTTP.BindPort) listener, err := net.Listen("tcp", addr) if err != nil { panic(err) } go func() { if config.HTTP.TLSConfig.Enabled { log.Printf("HTTP/TLS server listening on %v", addr) log.Fatalf("Error starting HTTP/TLS Server: %s", http.ServeTLS(listener, nRouter, config.HTTP.TLSConfig.CertFile, config.HTTP.TLSConfig.KeyFile)) } else { log.Printf("HTTP server listening on %v", addr) log.Fatalf("Error starting HTTP Server: %s", http.Serve(listener, nRouter)) } }() // Publish service using DNS-SD if config.DNSSD.Publish.Enabled { shutdown, err := registerDNSSDService(config) if err != nil { log.Printf("Failed to register DNS-SD service: %s", err) } defer shutdown() } // Register in the LinkSmart Service Catalog if config.ServiceCatalog.Enabled { unregisterService, err := registerInServiceCatalog(config) if err != nil { panic("Error registering service:" + err.Error()) } // Unregister from the Service Catalog defer func() { err := unregisterService() if err != nil { log.Printf("Error unregistering service from catalog: %s", err) } }() } log.Println("Ready!") // Ctrl+C / Kill handling handler := make(chan os.Signal, 1) signal.Notify(handler, syscall.SIGINT, syscall.SIGTERM) <-handler log.Println("Shutting down...") } func setupHTTPRouter(config *HTTPConfig, api *catalog.HTTPAPI, notifAPI *notification.SSEAPI) (*negroni.Negroni, error) { corsHandler := cors.New(cors.Options{ AllowedOrigins: []string{"*"}, AllowedMethods: []string{ http.MethodHead, http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, }, AllowedHeaders: []string{"*"}, AllowCredentials: false, ExposedHeaders: []string{"*"}, }) commonHandlers := alice.New( context.ClearHandler, corsHandler.Handler, ) // Append auth handler if enabled if config.Auth.Enabled { // Setup ticket validator v, err := validator.Setup( config.Auth.Provider, config.Auth.ProviderURL, config.Auth.ClientID, config.Auth.BasicEnabled, &config.Auth.Authz) if err != nil { return nil, err } commonHandlers = commonHandlers.Append(v.Handler) } // Configure http api router r := newRouter() r.get("/", commonHandlers.ThenFunc(indexHandler)) r.options("/{path:.*}", commonHandlers.ThenFunc(optionsHandler)) // OpenAPI Proxy for Swagger "try it out" feature r.get("/openapi-spec-proxy", commonHandlers.ThenFunc(apiSpecProxy)) r.get("/openapi-spec-proxy/{basepath:.+}", commonHandlers.ThenFunc(apiSpecProxy)) // Deprecated: use /things and /search instead // TD CRUD, listing, filtering r.get("/td", commonHandlers.ThenFunc(api.GetMany)) r.get("/td-chunked", commonHandlers.ThenFunc(api.GetAll)) r.post("/td", commonHandlers.ThenFunc(api.Post)) r.get("/td/{id:.+}", commonHandlers.ThenFunc(api.Get)) r.put("/td/{id:.+}", commonHandlers.ThenFunc(api.Put)) r.patch("/td/{id:.+}", commonHandlers.ThenFunc(api.Patch)) r.delete("/td/{id:.+}", commonHandlers.ThenFunc(api.Delete)) // CRUDL r.post("/things", commonHandlers.ThenFunc(api.Post)) // create anonymous r.put("/things/{id:.+}", commonHandlers.ThenFunc(api.Put)) // create or update r.get("/things/{id:.+}", commonHandlers.ThenFunc(api.Get)) // retrieve r.patch("/things/{id:.+}", commonHandlers.ThenFunc(api.Patch)) // partially update r.delete("/things/{id:.+}", commonHandlers.ThenFunc(api.Delete)) // delete r.get("/things", commonHandlers.ThenFunc(api.GetAll)) // listing // search r.get("/search/jsonpath", commonHandlers.ThenFunc(api.SearchJSONPath)) r.get("/search/xpath", commonHandlers.ThenFunc(api.SearchXPath)) // TD validation r.get("/validation", commonHandlers.ThenFunc(api.GetValidation)) //TD notification r.get("/events", commonHandlers.ThenFunc(notifAPI.SubscribeEvent)) r.get("/events/{type}", commonHandlers.ThenFunc(notifAPI.SubscribeEvent)) logger := negroni.NewLogger() logFlags := log.LstdFlags if evalEnv(EnvDisableLogTime) { logFlags = 0 } logger.ALogger = log.New(os.Stdout, "", logFlags) logger.SetFormat("{{.Method}} {{.Request.URL}} {{.Request.Proto}} {{.Status}} {{.Duration}}") // Configure the middleware n := negroni.New( negroni.NewRecovery(), logger, ) // Mount router n.UseHandler(r) return n, nil } <file_sep>/discovery.go // Copyright 2014-2016 Fraunhofer Institute for Applied Information Technology FIT package main import ( "fmt" "log" "net" "strings" "github.com/grandcat/zeroconf" "github.com/linksmart/go-sec/auth/obtainer" sc "github.com/linksmart/service-catalog/v3/catalog" "github.com/linksmart/service-catalog/v3/client" "github.com/linksmart/thing-directory/wot" ) // escape special characters as recommended by https://tools.ietf.org/html/rfc6763#section-4.3 func escapeDNSSDServiceInstance(instance string) (escaped string) { // replace \ by \\ escaped = strings.ReplaceAll(instance, "\\", "\\\\") // replace . by \. escaped = strings.ReplaceAll(escaped, ".", "\\.") return escaped } // register as a DNS-SD Service func registerDNSSDService(conf *Config) (func(), error) { instance := escapeDNSSDServiceInstance(conf.DNSSD.Publish.Instance) log.Printf("DNS-SD: registering as \"%s.%s.%s\", subtype: %s", instance, wot.DNSSDServiceType, conf.DNSSD.Publish.Domain, wot.DNSSDServiceSubtypeDirectory) var ifs []net.Interface for _, name := range conf.DNSSD.Publish.Interfaces { iface, err := net.InterfaceByName(name) if err != nil { return nil, fmt.Errorf("error finding interface %s: %s", name, err) } if (iface.Flags & net.FlagMulticast) > 0 { ifs = append(ifs, *iface) } else { return nil, fmt.Errorf("interface %s does not support multicast", name) } log.Printf("DNS-SD: will register to interface: %s", name) } if len(ifs) == 0 { log.Println("DNS-SD: publish interfaces not set. Will register to all interfaces with multicast support.") } sd, err := zeroconf.Register( instance, wot.DNSSDServiceType+","+wot.DNSSDServiceSubtypeDirectory, conf.DNSSD.Publish.Domain, conf.HTTP.BindPort, []string{"td=/td", "version=" + Version}, ifs, ) if err != nil { return sd.Shutdown, err } return sd.Shutdown, nil } // register in LinkSmart Service Catalog func registerInServiceCatalog(conf *Config) (func() error, error) { cat := conf.ServiceCatalog service := sc.Service{ ID: conf.ServiceID, Type: "_linksmart-td._tcp", Title: "LinkSmart Thing Directory", Description: conf.Description, APIs: []sc.API{{ ID: "things", Title: "Thing Directory API", //Description: "API description", Protocol: "HTTP", URL: conf.HTTP.PublicEndpoint, Spec: sc.Spec{ MediaType: "application/vnd.oai.swagger;version=3.0.0", URL: "https://raw.githubusercontent.com/linksmart/thing-directory/master/apidoc/openapi-spec.yml", //Schema: map[string]interface{}{}, }, Meta: map[string]interface{}{ "apiVersion": Version, }, }}, Doc: "https://github.com/linksmart/thing-directory", //Meta: map[string]interface{}{}, TTL: uint32(conf.ServiceCatalog.TTL), } var ticket *obtainer.Client var err error if cat.Auth.Enabled { // Setup ticket client ticket, err = obtainer.NewClient(cat.Auth.Provider, cat.Auth.ProviderURL, cat.Auth.Username, cat.Auth.Password, cat.Auth.ClientID) if err != nil { return nil, fmt.Errorf("error creating auth client: %s", err) } } stopRegistrator, _, err := client.RegisterServiceAndKeepalive(cat.Endpoint, service, ticket) if err != nil { return nil, fmt.Errorf("error registering service: %s", err) } return stopRegistrator, nil } <file_sep>/wot/error.go package wot // RFC7807 Problem Details (https://tools.ietf.org/html/rfc7807) type ProblemDetails struct { // Type A URI reference (RFC3986) that identifies the problem type. This specification encourages that, when // dereferenced, it provide human-readable documentation for the problem type (e.g., using HTML). When // this member is not present, its value is assumed to be "about:blank". Type string `json:"type,omitempty"` // Title - A short, human-readable summary of the problem type. It SHOULD NOT change from occurrence to occurrence of the // problem, except for purposes of localization (e.g., using proactive content negotiation); see RFC7231, Section 3.4. Title string `json:"title"` // Status - The HTTP status code (RFC7231, Section 6) generated by the origin server for this occurrence of the problem. Status int `json:"status"` // Detail - A human-readable explanation specific to this occurrence of the problem. Detail string `json:"detail"` // Instance - A URI reference that identifies the specific occurrence of the problem. It may or may not yield further information if dereferenced. Instance string `json:"instance,omitempty"` // ValidationErrors - Extension for detailed validation results ValidationErrors []ValidationError `json:"validationErrors,omitempty"` } type ValidationError struct { Field string `json:"field"` Descr string `json:"description"` } <file_sep>/wot/validation_test.go package wot import ( "io/ioutil" "os" "testing" "github.com/xeipuuv/gojsonschema" ) const ( envTestSchemaPath = "TEST_SCHEMA_PATH" defaultSchemaPath = "../wot/wot_td_schema.json" ) func TestLoadSchemas(t *testing.T) { if !LoadedJSONSchemas() { path := os.Getenv(envTestSchemaPath) if path == "" { path = defaultSchemaPath } err := LoadJSONSchemas([]string{path}) if err != nil { t.Fatalf("error loading WoT Thing Description schema: %s", err) } } if len(loadedJSONSchemas) == 0 { t.Fatalf("JSON Schema was not loaded into memory") } } func TestValidateAgainstSchema(t *testing.T) { path := os.Getenv(envTestSchemaPath) if path == "" { path = defaultSchemaPath } // load the schema file, err := ioutil.ReadFile(path) if err != nil { t.Fatalf("error reading file: %s", err) } schema, err := gojsonschema.NewSchema(gojsonschema.NewBytesLoader(file)) if err != nil { t.Fatalf("error loading schema: %s", err) } t.Run("non-URI ID", func(t *testing.T) { var td = map[string]any{ "@context": "https://www.w3.org/2019/wot/td/v1", "id": "not-a-uri", "title": "example thing", "security": []string{"basic_sc"}, "securityDefinitions": map[string]any{ "basic_sc": map[string]string{ "in": "header", "scheme": "basic", }, }, } results, err := validateAgainstSchema(&td, schema) if err != nil { t.Fatalf("internal validation error: %s", err) } if len(results) == 0 { t.Fatalf("Didn't return error on non-URI ID: %s", td["id"]) } }) t.Run("missing mandatory title", func(t *testing.T) { var td = map[string]any{ "@context": "https://www.w3.org/2019/wot/td/v1", "id": "not-a-uri", //"title": "example thing", "security": []string{"basic_sc"}, "securityDefinitions": map[string]any{ "basic_sc": map[string]string{ "in": "header", "scheme": "basic", }, }, } results, err := validateAgainstSchema(&td, schema) if err != nil { t.Fatalf("internal validation error: %s", err) } if len(results) == 0 { t.Fatalf("Didn't return error on missing mandatory title.") } }) // TODO test discovery validations //t.Run("non-float TTL", func(t *testing.T) { // var td = map[string]any{ // "@context": "https://www.w3.org/2019/wot/td/v1", // "id": "urn:example:test/thing1", // "title": "example thing", // "security": []string{"basic_sc"}, // "securityDefinitions": map[string]any{ // "basic_sc": map[string]string{ // "in": "header", // "scheme": "basic", // }, // }, // "registration": map[string]any{ // "ttl": "60", // }, // } // results, err := validateAgainstSchema(&td, schema) // if err != nil { // t.Fatalf("internal validation error: %s", err) // } // if len(results) == 0 { // t.Fatalf("Didn't return error on string TTL.") // } //}) } <file_sep>/notification/controller.go package notification import ( "encoding/json" "fmt" "log" jsonpatch "github.com/evanphx/json-patch/v5" "github.com/linksmart/thing-directory/catalog" "github.com/linksmart/thing-directory/wot" ) type Controller struct { s EventQueue // Events are pushed to this channel by the main events-gathering routine Notifier chan Event // New client connections subscribingClients chan subscriber // Closed client connections unsubscribingClients chan chan Event // Client connections registry activeClients map[chan Event]subscriber // shutdown shutdown chan bool } type subscriber struct { client chan Event eventTypes []wot.EventType diff bool lastEventID string } func NewController(s EventQueue) *Controller { c := &Controller{ s: s, Notifier: make(chan Event, 1), subscribingClients: make(chan subscriber), unsubscribingClients: make(chan chan Event), activeClients: make(map[chan Event]subscriber), shutdown: make(chan bool), } go c.handler() return c } func (c *Controller) subscribe(client chan Event, eventTypes []wot.EventType, diff bool, lastEventID string) error { s := subscriber{client: client, eventTypes: eventTypes, diff: diff, lastEventID: lastEventID, } c.subscribingClients <- s return nil } func (c *Controller) unsubscribe(client chan Event) error { c.unsubscribingClients <- client return nil } func (c *Controller) storeAndNotify(event Event) error { var err error event.ID, err = c.s.getNewID() if err != nil { return fmt.Errorf("error generating ID : %v", err) } // Notify c.Notifier <- event // Store err = c.s.addRotate(event) if err != nil { return fmt.Errorf("error storing the notification : %v", err) } return nil } func (c *Controller) Stop() { c.shutdown <- true } func (c *Controller) CreateHandler(new catalog.ThingDescription) error { event := Event{ Type: wot.EventTypeCreate, Data: new, } err := c.storeAndNotify(event) return err } func (c *Controller) UpdateHandler(old catalog.ThingDescription, new catalog.ThingDescription) error { oldJson, err := json.Marshal(old) if err != nil { return fmt.Errorf("error marshalling old TD") } newJson, err := json.Marshal(new) if err != nil { return fmt.Errorf("error marshalling new TD") } patch, err := jsonpatch.CreateMergePatch(oldJson, newJson) if err != nil { return fmt.Errorf("error merging new TD") } var td catalog.ThingDescription if err := json.Unmarshal(patch, &td); err != nil { return fmt.Errorf("error unmarshalling the patch TD") } td[wot.KeyThingID] = old[wot.KeyThingID] event := Event{ Type: wot.EventTypeUpdate, Data: td, } err = c.storeAndNotify(event) return err } func (c *Controller) DeleteHandler(old catalog.ThingDescription) error { deleted := catalog.ThingDescription{ wot.KeyThingID: old[wot.KeyThingID], } event := Event{ Type: wot.EventTypeDelete, Data: deleted, } err := c.storeAndNotify(event) return err } func (c *Controller) handler() { loop: for { select { case s := <-c.subscribingClients: c.activeClients[s.client] = s log.Printf("New subscription. %d active clients", len(c.activeClients)) // Send the missed events if s.lastEventID != "" { missedEvents, err := c.s.getAllAfter(s.lastEventID) if err != nil { log.Printf("error getting the events after ID %s: %s", s.lastEventID, err) continue loop } for _, event := range missedEvents { sendToSubscriber(s, event) } } case clientChan := <-c.unsubscribingClients: delete(c.activeClients, clientChan) close(clientChan) log.Printf("Unsubscribed. %d active clients", len(c.activeClients)) case event := <-c.Notifier: for _, s := range c.activeClients { sendToSubscriber(s, event) } case <-c.shutdown: log.Println("Shutting down notification controller") break loop } } } func sendToSubscriber(s subscriber, event Event) { for _, eventType := range s.eventTypes { // Send the notification if the type matches if eventType == event.Type { toSend := event if !s.diff { toSend.Data = catalog.ThingDescription{wot.KeyThingID: toSend.Data[wot.KeyThingID]} } s.client <- toSend break } } } <file_sep>/paper/joss/paper.md --- title: 'Thing Directory: Simple and lightweight registry of IoT device metadata' tags: - internet of things - web of things - wireless sensor networks - discovery - catalog authors: - name: <NAME> affiliation: 1 - name: <NAME> affiliation: 1 affiliations: - name: Fraunhofer Institute for Applied Information Technology, Sankt Augustin, Germany index: 1 date: 16 December 2020 bibliography: paper.bib --- # Statement of Need <!-- A clear Statement of Need that illustrates the research purpose of the software. --> The fast emergence of IoT (Internet of Things) technologies has influenced scientific communities to embrace novel sources of information and their potential use in various domains. While the vast amount of sensory data is beneficial, the lack of uniform access interfaces hinders researchers from efficient exploitation. A structured, yet flexible registry is needed to model device metadata and allow exploration and interaction with such devices. In the IoT context, the Things are physical devices (e.g., sensors, actuators, gateways) or virtual ones (e.g., digital twins, proxies, aggregated data sources). An ideal metadata registry for such Things should have a flat learning curve and be easily deployable. This would allow researchers to focus less on interoperability and more on fast prototyping and data application. Registries that are based on established standards are preferred since they can incorporate metadata with many existing Things out-of-the-box. Moreover, the registry software should be lightweight, easily deployable, and free of rigid requirements to support fast prototyping across a wide range of use cases from the edge to the cloud. # Thing Directory <!-- A summary describing the high-level functionality and purpose of the software for a diverse, non-specialist audience. --> Thing Directory is a searchable registry of metadata for Things. The API is based on W3C Web of Things (WoT) Discovery [@WoTDiscovery], a specification for secure discovery of Things. The registry uses JSON-LD (JSON for Linked Data) encoding by default. The JSON format is human-readable and portable; the linked data support makes the data machine-interpretable. The architecture of the registry is modular with a pluggable storage backend, allowing connection to various database systems using drivers. The current implementation, backed by an embedded LevelDB storage, can be deployed on highly constrained single-board computers such as the Raspberry Pi Zero series. It has very minimal idle processing and memory footprints and can scale on demand to utilize all locally available resources. More powerful storage backends can be added to create a horizontally scalable directory in cloud environments. The application is packaged as binary distributions, Debian packages, as well as Docker images for easy deployment on a variety of platforms. The data model of the metadata is based on W3C WoT Thing Description (TD) [@WoTTD] which is extensible by design. Thing Directory validates all inputs using a JSON-Schema, describing the data model. This makes it possible to extend the server’s structured data model and validation mechanism with no programming. The various modules of the system are provided as re-usable Go libraries which can be imported by other applications to build functionalities around Thing Descriptions. <!-- Mention (if applicable) a representative set of past or ongoing research projects using the software and recent scholarly publications enabled by it. --> ## Use case: Assessment of Building Energy Efficiency Construction companies often deal with the challenge of delivering target energy-efficient buildings, given specific budget and time constraints. Energy efficiency, as one of the key factors for renovation investments, depends on the availability of various data sources to support the renovation design and planning. These include climate data and building material along with residential comfort and energy consumption patterns. As part of the pre-renovation activities, the construction planners deploy various sensors to collect relevant data over a period. Such sensors become part of a wireless sensor network (WSN) and expose data endpoints with the help of one or more gateways. Depending on the protocols, the endpoints require different interaction flows to securely deliver current and historical measurements. The renovation applications need to discover the sensors, their endpoints, and how to interact with them based on search criteria such as the physical location, mapping to the building model, or measurement type. The Thing Directory supports engineers in the assessment of building energy efficiency by providing the means to collect and discover the metadata of deployed sensors in an easy and standardized way. Instances of Thing Directory have been deployed in four renovation sites (two apartments, two buildings) across Europe as registries of wireless sensors which are locally accessible over Z-Wave or WiFi. The API has been integrated into applications for profiling of resident usage of building systems, building information modeling, and process modeling and automation. Such applications query sensor metadata based on zoning and sensor types. Once discovered, the metadata provides these applications with necessary details on how to authenticate and query data. Since the Thing Directory is based on an open standard, being integrated with it adds interoperability with WSNs beyond the scope of this use case. The applications will be able to interact with the growing number of compliant WoT devices. # Related Work <!-- A list of key references, including to other software addressing related needs. --> There are multiple attempts to modeling and discovering the connected Things and their interfaces. OGC SensorThings API [@sensorthingsSensing;@sensorthingsTasking] has been a successful model for the representation of Things. Sensorthings API consists of two parts: sensing and tasking. The popular implementations of the OGC SensorThings are FROST [@frost] and GOST [@gost] which support mainly the sensing part. FROST has preliminary tasking support. These solutions focus on centralized deployments and are not suitable for a federated scenario and gateways with limited computational power. On top of that, the specification which they are based upon, enforces both metadata and observation modeling. That is not practical in IoT scenarios with heterogenous data formats and interfaces. The survey articles by @DiscoveryCategorization2016 and @DiscoveryReview2020 discuss and categorize several other technologies related to discovery in the IoT field and evaluate them. The WoT TD [@WoTTD] covers a wide range of Things by providing the semantics to describe the textual metadata, interaction affordances, data schemas, and relations. Thingweb Directory [@Thingweb] has implemented the discovery of WoT TDs using a proprietary API which does not comply with W3C WoT Discovery [@WoTDiscovery] standard. The Thing Directory complies with both W3C WoT Discovery and W3C WoT TD. # Acknowledgement <!-- Acknowledgement of any financial support. --> This work was conducted as part of the BIMERR project, a European Commission’s Horizon 2020 research and innovation program under grant agreement No 820621. The resulting software is released as part of LinkSmart, an open-source IoT prototyping platform. # References <file_sep>/README.md # LinkSmart Thing Directory [![Docker Pulls](https://img.shields.io/docker/pulls/linksmart/td.svg)](https://hub.docker.com/r/linksmart/td/tags) [![GitHub tag (latest pre-release)](https://img.shields.io/github/tag-pre/linksmart/thing-directory.svg?label=pre-release)](https://github.com/linksmart/thing-directory/tags) [![CICD](https://github.com/linksmart/thing-directory/workflows/CICD/badge.svg)](https://github.com/linksmart/thing-directory/actions?query=workflow:CICD) [![DOI](https://joss.theoj.org/papers/10.21105/joss.03075/status.svg)](https://doi.org/10.21105/joss.03075) This is an implementation of the [W3C WoT Thing Description Directory (TDD)](https://w3c.github.io/wot-discovery/), a registry of [Thing Descriptions](https://www.w3.org/TR/wot-thing-description/). ## Getting Started Visit the following pages to get started: * [Deployment](https://github.com/linksmart/thing-directory/wiki/Deployment): How to deploy the software, as Docker container, Debian package, or platform-specific binary distributions * [Configuration](https://github.com/linksmart/thing-directory/wiki/Configuration): How to configure the server software with JSON files and environment variables * [API Documentation](https://linksmart.github.io/swagger-ui/dist/?url=https://raw.githubusercontent.com/linksmart/thing-directory/master/apidoc/openapi-spec.yml): How to interact with the networking APIs **Further documentation are available in the [wiki](https://github.com/linksmart/thing-directory/wiki)**. ## Features * Service Discovery * [DNS-SD registration](https://github.com/linksmart/thing-directory/wiki/Discovery-with-DNS-SD) * [LinkSmart Service Catalog](https://github.com/linksmart/service-catalog) registration * RESTful API * [HTTP API](https://linksmart.github.io/swagger-ui/dist/?url=https://raw.githubusercontent.com/linksmart/thing-directory/master/apidoc/openapi-spec.yml) * Thing Description (TD) CRUD, catalog, and validation * XPath 3.0 and JSONPath [query languages](https://github.com/linksmart/thing-directory/wiki/Query-Language) * TD validation with JSON Schema ([default](https://github.com/linksmart/thing-directory/blob/master/wot/wot_td_schema.json)) * Request [authentication](https://github.com/linksmart/go-sec/wiki/Authentication) and [authorization](https://github.com/linksmart/go-sec/wiki/Authorization) * JSON-LD response format * Persistent Storage * LevelDB * CI/CD ([Github Actions](https://github.com/linksmart/thing-directory/actions?query=workflow:CICD)) * Automated testing * Automated builds and releases ([Docker images](https://hub.docker.com/r/linksmart/td/tags?page=1&ordering=last_updated), [binaries](https://github.com/linksmart/thing-directory/releases)) ## Development The dependencies of this package are managed by [Go Modules](https://github.com/golang/go/wiki/Modules). Clone this repo: ```bash git clone https://github.com/linksmart/thing-directory.git cd thing-directory ``` Compile from source: ```bash go build ``` This will result in an executable named `thing-directory` (linux/macOS) or `thing-directory.exe` (windows). Get the CLI arguments help (linux/macOS): ```bash $ ./thing-directory -help Usage of ./thing-directory: -conf string Configuration file path (default "conf/thing-directory.json") -version Print the API version ``` Run (linux/macOS): ```bash $ ./thing-directory --conf=sample_conf/thing-directory.json ``` To build and run together: ```bash go run . --conf=sample_conf/thing-directory.json ``` Test all packages (add `-v` flag for verbose results): ```bash go test ./... ``` ## Contributing Contributions are welcome. Please fork, make your changes, and submit a pull request. For major changes, please open an issue first and discuss it with the other authors. <file_sep>/router.go // Copyright 2016 Fraunhofer Institute for Applied Information Technology FIT package main import ( "fmt" "html/template" "io" "log" "net/http" "strings" "github.com/gorilla/mux" ) type router struct { *mux.Router } func newRouter() *router { return &router{mux.NewRouter().StrictSlash(false).SkipClean(true)} } func (r *router) get(path string, handler http.Handler) { r.Methods("GET").Path(path).Handler(handler) r.Methods("GET").Path(fmt.Sprintf("%s/", path)).Handler(handler) } func (r *router) post(path string, handler http.Handler) { r.Methods("POST").Path(path).Handler(handler) r.Methods("POST").Path(fmt.Sprintf("%s/", path)).Handler(handler) } func (r *router) put(path string, handler http.Handler) { r.Methods("PUT").Path(path).Handler(handler) r.Methods("PUT").Path(fmt.Sprintf("%s/", path)).Handler(handler) } func (r *router) delete(path string, handler http.Handler) { r.Methods("DELETE").Path(path).Handler(handler) r.Methods("DELETE").Path(fmt.Sprintf("%s/", path)).Handler(handler) } func (r *router) patch(path string, handler http.Handler) { r.Methods("PATCH").Path(path).Handler(handler) r.Methods("PATCH").Path(fmt.Sprintf("%s/", path)).Handler(handler) } func (r *router) head(path string, handler http.Handler) { r.Methods("HEAD").Path(path).Handler(handler) r.Methods("HEAD").Path(fmt.Sprintf("%s/", path)).Handler(handler) } func (r *router) options(path string, handler http.Handler) { r.Methods("OPTIONS").Path(path).Handler(handler) r.Methods("OPTIONS").Path(fmt.Sprintf("%s/", path)).Handler(handler) } func optionsHandler(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) } func indexHandler(w http.ResponseWriter, _ *http.Request) { version := "master" if Version != "" { version = Version } spec := strings.NewReplacer("{version}", version).Replace(Spec) swaggerUIRelativeScheme := "//" + SwaggerUISchemeLess swaggerUISecure := "https:" + swaggerUIRelativeScheme w.Header().Set("Content-Type", "text/html") data := struct { Logo, Version, SourceRepo, Spec, SwaggerUIRelativeScheme, SwaggerUISecure string }{LINKSMART, version, SourceCodeRepo, spec, swaggerUIRelativeScheme, swaggerUISecure} tmpl := ` <meta charset="UTF-8"> <pre>{{.Logo}}</pre> <h1>Thing Directory</h1> <p>Version: {{.Version}}</p> <p><a href="{{.SourceRepo}}">{{.SourceRepo}}</a></p> <p>API Documentation: <a href="{{.SwaggerUISecure}}/?url={{.Spec}}">Swagger UI</a></p> <p><a href="" id="swagger">Try it out!</a> (experimental; requires internet connection on both server and client sides)</p> <script type="text/javascript"> window.onload = function(){ document.getElementById("swagger").href = "{{.SwaggerUIRelativeScheme}}/?url=" + window.location.toString() + "openapi-spec-proxy" + window.location.pathname; } </script>` t, err := template.New("body").Parse(tmpl) if err != nil { log.Fatalf("Error parsing template: %s", err) } err = t.Execute(w, data) if err != nil { log.Fatalf("Error applying template to response: %s", err) } } func apiSpecProxy(w http.ResponseWriter, req *http.Request) { version := "master" if Version != "" { version = Version } spec := strings.NewReplacer("{version}", version).Replace(Spec) // get the spec res, err := http.Get(spec) if err != nil { w.WriteHeader(http.StatusInternalServerError) _, err := fmt.Fprintf(w, "Error querying Open API specs: %s", err) if err != nil { log.Printf("ERROR writing HTTP response: %s", err) } return } defer res.Body.Close() if res.StatusCode != http.StatusOK { w.WriteHeader(res.StatusCode) _, err := fmt.Fprintf(w, "GET %s: %s", spec, res.Status) if err != nil { log.Printf("ERROR writing HTTP response: %s", err) } return } // write the spec as response _, err = io.Copy(w, res.Body) if err != nil { w.WriteHeader(http.StatusInternalServerError) _, err := fmt.Fprintf(w, "Error responding Open API specs: %s", err) if err != nil { log.Printf("ERROR writing HTTP response: %s", err) } return } // append basename as server URL to api specs params := mux.Vars(req) if params["basepath"] != "" { basePath := strings.TrimSuffix(params["basepath"], "/") if !strings.HasPrefix(basePath, "/") { basePath = "/" + basePath } _, err := w.Write([]byte("\nservers: [url: " + basePath + "]")) if err != nil { log.Printf("ERROR writing HTTP response: %s", err) } } } <file_sep>/catalog/main_test.go // Copyright 2014-2016 Fraunhofer Institute for Applied Information Technology FIT package catalog import ( "encoding/json" "os" "reflect" "testing" "github.com/linksmart/thing-directory/wot" ) const ( envTestSchemaPath = "TEST_SCHEMA_PATH" defaultSchemaPath = "../wot/wot_td_schema.json" ) type any = interface{} var ( TestSupportedBackends = map[string]bool{ BackendMemory: false, BackendLevelDB: true, } TestStorageType string ) func loadSchema() error { if wot.LoadedJSONSchemas() { return nil } path := os.Getenv(envTestSchemaPath) if path == "" { path = defaultSchemaPath } return wot.LoadJSONSchemas([]string{path}) } func serializedEqual(td1 ThingDescription, td2 ThingDescription) bool { // serialize to ease comparison of interfaces and concrete types tdBytes, _ := json.Marshal(td1) storedTDBytes, _ := json.Marshal(td2) return reflect.DeepEqual(tdBytes, storedTDBytes) } func TestMain(m *testing.M) { // run tests for each storage backend for b, supported := range TestSupportedBackends { if supported { TestStorageType = b if m.Run() == 1 { os.Exit(1) } } } os.Exit(0) } <file_sep>/discovery_test.go package main import "testing" func TestEscapeDNSSDServiceInstance(t *testing.T) { t.Run("no escaping", func(t *testing.T) { instance := "thing-directory" escaped := escapeDNSSDServiceInstance(instance) if escaped != instance { t.Fatalf("Unexpected escaping of %s to %s", instance, escaped) } }) t.Run("escape dot", func(t *testing.T) { instance := "thing.directory" // from thing.directory expected := "thing\\.directory" // to thing\.directory escaped := escapeDNSSDServiceInstance(instance) if escaped != expected { t.Fatalf("Escaped value for %s is %s. Expected %s", instance, escaped, expected) } }) t.Run("escape backslash", func(t *testing.T) { instance := "thing\\directory" // from thing\directory expected := "thing\\\\directory" // to thing\\directory escaped := escapeDNSSDServiceInstance(instance) if escaped != expected { t.Fatalf("Escaped value for %s is %s. Expected %s", instance, escaped, expected) } }) } <file_sep>/notification/ldb_eventqueue.go package notification import ( "encoding/binary" "encoding/json" "flag" "fmt" "log" "net/url" "strconv" "sync" "github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb/opt" "github.com/syndtr/goleveldb/leveldb/util" ) // LevelDB storage type LevelDBEventQueue struct { db *leveldb.DB wg sync.WaitGroup latestID uint64 capacity uint64 } func NewLevelDBEventQueue(dsn string, opts *opt.Options, capacity uint64) (EventQueue, error) { url, err := url.Parse(dsn) if err != nil { return nil, err } // Open the database file db, err := leveldb.OpenFile(url.Path, opts) if err != nil { return nil, err } ldbEventQueue := &LevelDBEventQueue{db: db, capacity: capacity} ldbEventQueue.latestID, err = ldbEventQueue.fetchLatestID() if err != nil { return nil, fmt.Errorf("error fetching the latest ID from storage: %w", err) } return ldbEventQueue, nil } func (s *LevelDBEventQueue) addRotate(event Event) error { s.wg.Add(1) defer s.wg.Done() // add new data bytes, err := json.Marshal(event) if err != nil { return fmt.Errorf("error marshalling event: %w", err) } uintID, err := strconv.ParseUint(event.ID, 16, 64) if err != nil { return fmt.Errorf("error parsing event ID: %w", err) } batch := new(leveldb.Batch) batch.Put(uint64ToByte(uintID), bytes) // cleanup the older data if s.latestID > s.capacity { cleanBefore := s.latestID - s.capacity + 1 // adding 1 as Range is is not inclusive the limit. iter := s.db.NewIterator(&util.Range{Limit: uint64ToByte(cleanBefore)}, nil) for iter.Next() { // log.Println("deleting older entry: ", byteToUint64(iter.Key())) batch.Delete(iter.Key()) } iter.Release() err = iter.Error() if err != nil { return err } } err = s.db.Write(batch, nil) if err != nil { return fmt.Errorf("error cleaning up: %w", err) } return nil } func (s *LevelDBEventQueue) getAllAfter(id string) ([]Event, error) { intID, err := strconv.ParseUint(id, 16, 64) if err != nil { return nil, fmt.Errorf("error parsing latest ID: %w", err) } // start from the last missing event. // If the leveldb does not have the requested ID, // then the iterator starts with oldest available entry iter := s.db.NewIterator(&util.Range{Start: uint64ToByte(intID + 1)}, nil) var events []Event for iter.Next() { var event Event err = json.Unmarshal(iter.Value(), &event) if err != nil { iter.Release() return nil, fmt.Errorf("error unmarshalling event: %w", err) } events = append(events, event) } iter.Release() err = iter.Error() if err != nil { return nil, err } return events, nil } func (s *LevelDBEventQueue) getNewID() (string, error) { s.latestID += 1 return strconv.FormatUint(s.latestID, 16), nil } func (s *LevelDBEventQueue) Close() { s.wg.Wait() err := s.db.Close() if err != nil { log.Printf("Error closing SSE storage: %s", err) } if flag.Lookup("test.v") == nil { log.Println("Closed SSE leveldb.") } } func (s *LevelDBEventQueue) fetchLatestID() (uint64, error) { var latestID uint64 s.wg.Add(1) defer s.wg.Done() iter := s.db.NewIterator(nil, nil) exists := iter.Last() if exists { latestID = byteToUint64(iter.Key()) } else { // Start from 0 latestID = 0 } iter.Release() err := iter.Error() if err != nil { return 0, err } return latestID, nil } //byte to unint64 conversion functions and vice versa func byteToUint64(input []byte) uint64 { return binary.BigEndian.Uint64(input) } func uint64ToByte(input uint64) []byte { output := make([]byte, 8) binary.BigEndian.PutUint64(output, input) return output } <file_sep>/wot/validation.go package wot import ( "fmt" "io/ioutil" "github.com/xeipuuv/gojsonschema" ) type jsonSchema = *gojsonschema.Schema var loadedJSONSchemas []jsonSchema // ReadJSONSchema reads the a JSONSchema from a file func readJSONSchema(path string) (jsonSchema, error) { file, err := ioutil.ReadFile(path) if err != nil { return nil, fmt.Errorf("error reading file: %s", err) } schema, err := gojsonschema.NewSchema(gojsonschema.NewBytesLoader(file)) if err != nil { return nil, fmt.Errorf("error loading schema: %s", err) } return schema, nil } // LoadJSONSchemas loads one or more JSON Schemas into memory func LoadJSONSchemas(paths []string) error { if len(loadedJSONSchemas) != 0 { panic("Unexpected re-loading of JSON Schemas.") } var schemas []jsonSchema for _, path := range paths { schema, err := readJSONSchema(path) if err != nil { return err } schemas = append(schemas, schema) } loadedJSONSchemas = schemas return nil } // LoadedJSONSchemas checks whether any JSON Schema has been loaded into memory func LoadedJSONSchemas() bool { return len(loadedJSONSchemas) > 0 } func validateAgainstSchema(td *map[string]interface{}, schema jsonSchema) ([]ValidationError, error) { result, err := schema.Validate(gojsonschema.NewGoLoader(td)) if err != nil { return nil, err } if !result.Valid() { var issues []ValidationError for _, re := range result.Errors() { issues = append(issues, ValidationError{Field: re.Field(), Descr: re.Description()}) } return issues, nil } return nil, nil } func validateAgainstSchemas(td *map[string]interface{}, schemas ...jsonSchema) ([]ValidationError, error) { var validationErrors []ValidationError for _, schema := range schemas { result, err := validateAgainstSchema(td, schema) if err != nil { return nil, err } validationErrors = append(validationErrors, result...) } return validationErrors, nil } // ValidateTD performs input validation using one or more pre-loaded JSON Schemas // If no schema has been pre-loaded, the function returns as if there are no validation errors func ValidateTD(td *map[string]interface{}) ([]ValidationError, error) { return validateAgainstSchemas(td, loadedJSONSchemas...) } <file_sep>/catalog/controller_test.go // Copyright 2014-2016 Fraunhofer Institute for Applied Information Technology FIT package catalog import ( "fmt" "os" "reflect" "strconv" "strings" "testing" "time" uuid "github.com/satori/go.uuid" ) func setup(t *testing.T) CatalogController { var ( storage Storage tempDir = fmt.Sprintf("%s/thing-directory/test-%s-ldb", strings.Replace(os.TempDir(), "\\", "/", -1), uuid.NewV4()) ) err := loadSchema() if err != nil { t.Fatalf("error loading WoT Thing Description schema: %s", err) } switch TestStorageType { case BackendLevelDB: storage, err = NewLevelDBStorage(tempDir, nil) if err != nil { t.Fatalf("error creating leveldb storage: %s", err) } } controller, err := NewController(storage) if err != nil { storage.Close() t.Fatalf("error creating controller: %s", err) } t.Cleanup(func() { //t.Logf("Cleaning up...") controller.Stop() storage.Close() err = os.RemoveAll(tempDir) // Remove temp files if err != nil { t.Fatalf("error removing test files: %s", err) } }) return controller } func TestControllerAdd(t *testing.T) { controller := setup(t) t.Run("user-defined ID", func(t *testing.T) { var td = map[string]any{ "@context": "https://www.w3.org/2019/wot/td/v1", "id": "urn:example:test/thing1", "title": "example thing", "security": []string{"basic_sc"}, "securityDefinitions": map[string]any{ "basic_sc": map[string]string{ "in": "header", "scheme": "basic", }, }, } id, err := controller.add(td) if err != nil { t.Fatalf("Unexpected error on add: %s", err) } if id != td["id"] { t.Fatalf("User defined ID is not returned. Getting %s instead of %s\n", id, td["id"]) } // add it again _, err = controller.add(td) if err == nil { t.Error("Didn't get any error when adding a service with non-unique id.") } }) t.Run("system-generated ID", func(t *testing.T) { // System-generated id var td = map[string]any{ "@context": "https://www.w3.org/2019/wot/td/v1", "title": "example thing", "security": []string{"basic_sc"}, "securityDefinitions": map[string]any{ "basic_sc": map[string]string{ "in": "header", "scheme": "basic", }, }, } id, err := controller.add(td) if err != nil { t.Fatalf("Unexpected error on add: %s", err) } if !strings.HasPrefix(id, "urn:") { t.Fatalf("System-generated ID is not a URN. Got: %s\n", id) } _, err = uuid.FromString(strings.TrimPrefix(id, "urn:")) if err == nil { t.Fatalf("System-generated ID is not a uuid. Got: %s\n", id) } }) } func TestControllerGet(t *testing.T) { controller := setup(t) var td = map[string]any{ "@context": "https://www.w3.org/2019/wot/td/v1", "id": "urn:example:test/thing1", "title": "example thing", "security": []string{"basic_sc"}, "securityDefinitions": map[string]any{ "basic_sc": map[string]string{ "in": "header", "scheme": "basic", }, }, } id, err := controller.add(td) if err != nil { t.Fatalf("Unexpected error on add: %s", err) } t.Run("retrieve", func(t *testing.T) { storedTD, err := controller.get(id) if err != nil { t.Fatalf("Error retrieving: %s", err) } // set system-generated attributes storedTD["registration"] = td["registration"] if !serializedEqual(td, storedTD) { t.Fatalf("Added and retrieved TDs are not equal:\n Added:\n%v\n Retrieved:\n%v\n", td, storedTD) } }) t.Run("retrieve non-existed", func(t *testing.T) { _, err := controller.get("some_id") if err != nil { switch err.(type) { case *NotFoundError: // good default: t.Fatalf("TD doesn't exist. Expected NotFoundError but got %s", err) } } else { t.Fatal("No error when retrieving a non-existed TD.") } }) } func TestControllerUpdate(t *testing.T) { controller := setup(t) var td = map[string]any{ "@context": "https://www.w3.org/2019/wot/td/v1", "id": "urn:example:test/thing1", "title": "example thing", "security": []string{"basic_sc"}, "securityDefinitions": map[string]any{ "basic_sc": map[string]string{ "in": "header", "scheme": "basic", }, }, } id, err := controller.add(td) if err != nil { t.Fatalf("Unexpected error on add: %s", err) } t.Run("update attributes", func(t *testing.T) { // Change td["title"] = "new title" td["description"] = "description of the thing" err = controller.update(id, td) if err != nil { t.Fatal("Error updating TD:", err.Error()) } storedTD, err := controller.get(id) if err != nil { t.Fatal("Error retrieving TD:", err.Error()) } // set system-generated attributes storedTD["registration"] = td["registration"] if !serializedEqual(td, storedTD) { t.Fatalf("Updates were not applied or returned:\n Expected:\n%v\n Retrieved:\n%v\n", td, storedTD) } }) } func TestControllerDelete(t *testing.T) { controller := setup(t) var td = map[string]any{ "@context": "https://www.w3.org/2019/wot/td/v1", "id": "urn:example:test/thing1", "title": "example thing", "security": []string{"basic_sc"}, "securityDefinitions": map[string]any{ "basic_sc": map[string]string{ "in": "header", "scheme": "basic", }, }, } id, err := controller.add(td) if err != nil { t.Fatalf("Error adding a TD: %s", err) } t.Run("delete", func(t *testing.T) { err = controller.delete(id) if err != nil { t.Fatalf("Error deleting TD: %s", err) } }) t.Run("delete a deleted TD", func(t *testing.T) { err = controller.delete(id) if err != nil { switch err.(type) { case *NotFoundError: // good default: t.Fatalf("TD was deleted. Expected NotFoundError but got %s", err) } } else { t.Fatalf("No error when deleting a deleted TD: %s", err) } }) t.Run("retrieve a deleted TD", func(t *testing.T) { _, err = controller.get(id) if err != nil { switch err.(type) { case *NotFoundError: // good default: t.Fatalf("TD was deleted. Expected NotFoundError but got %s", err) } } else { t.Fatal("No error when retrieving a deleted TD") } }) } func TestControllerList(t *testing.T) { controller := setup(t) // add several entries var addedTDs []ThingDescription for i := 0; i < 5; i++ { var td = map[string]any{ "@context": "https://www.w3.org/2019/wot/td/v1", "id": "urn:example:test/thing_" + strconv.Itoa(i), "title": "example thing", "security": []string{"basic_sc"}, "securityDefinitions": map[string]any{ "basic_sc": map[string]string{ "in": "header", "scheme": "basic", }, }, } id, err := controller.add(td) if err != nil { t.Fatal("Error adding a TD:", err.Error()) } sd, err := controller.get(id) if err != nil { t.Fatal("Error retrieving TD:", err.Error()) } addedTDs = append(addedTDs, sd) } // query all pages var collection []ThingDescription perPage := 3 for page := 1; ; page++ { collectionPage, total, err := controller.list(page, perPage) if err != nil { t.Fatal("Error getting list of TDs:", err.Error()) } if page == 1 && len(collectionPage) != 3 { t.Fatalf("Page 1 has %d entries instead of 3", len(collectionPage)) } if page == 2 && len(collectionPage) != 2 { t.Fatalf("Page 2 has %d entries instead of 2", len(collectionPage)) } if page == 3 && len(collectionPage) != 0 { t.Fatalf("Page 3 has %d entries instead of being blank", len(collectionPage)) } collection = append(collection, collectionPage...) if page*perPage >= total { break } } if len(collection) != 5 { t.Fatalf("Catalog contains %d entries instead of 5", len(collection)) } // compare added and collection for i, sd := range collection { if !reflect.DeepEqual(addedTDs[i], sd) { t.Fatalf("TDs listed in catalog is different with the one stored:\n Stored:\n%v\n Listed\n%v\n", addedTDs[i], sd) } } } func TestControllerFilter(t *testing.T) { controller := setup(t) for i := 0; i < 5; i++ { var td = map[string]any{ "@context": "https://www.w3.org/2019/wot/td/v1", "id": "urn:example:test/thing_" + strconv.Itoa(i), "title": "example thing", "security": []string{"basic_sc"}, "securityDefinitions": map[string]any{ "basic_sc": map[string]string{ "in": "header", "scheme": "basic", }, }, } _, err := controller.add(td) if err != nil { t.Fatal("Error adding a TD:", err.Error()) } } _, err := controller.add(map[string]any{ "@context": "https://www.w3.org/2019/wot/td/v1", "id": "urn:example:test/thing_x", "title": "interesting thing", "security": []string{"basic_sc"}, "securityDefinitions": map[string]any{ "basic_sc": map[string]string{ "in": "header", "scheme": "basic", }, }, }) if err != nil { t.Fatal("Error adding a TD:", err.Error()) } _, err = controller.add(map[string]any{ "@context": "https://www.w3.org/2019/wot/td/v1", "id": "urn:example:test/thing_y", "title": "interesting thing", "security": []string{"basic_sc"}, "securityDefinitions": map[string]any{ "basic_sc": map[string]string{ "in": "header", "scheme": "basic", }, }, }) if err != nil { t.Fatal("Error adding a TD:", err.Error()) } t.Run("filter with JSONPath", func(t *testing.T) { TDs, total, err := controller.filterJSONPath("$[?(@.title=='interesting thing')]", 1, 10) if err != nil { t.Fatal("Error filtering:", err.Error()) } if total != 2 { t.Fatalf("Returned %d instead of 2 TDs when filtering based on title: \n%v", total, TDs) } for _, td := range TDs { if td.(map[string]any)["title"] != "interesting thing" { t.Fatal("Wrong results when filtering based on title:\n", td) } } }) t.Run("filter with XPath", func(t *testing.T) { TDs, total, err := controller.filterXPath("*[title='interesting thing']", 1, 10) if err != nil { t.Fatal("Error filtering:", err.Error()) } if total != 2 { t.Fatalf("Returned %d instead of 2 TDs when filtering based on title: \n%v", total, TDs) } for _, td := range TDs { if td.(map[string]any)["title"] != "interesting thing" { t.Fatal("Wrong results when filtering based on title:\n", td) } } }) } func TestControllerTotal(t *testing.T) { controller := setup(t) const createTotal = 5 for i := 0; i < createTotal; i++ { var td = ThingDescription{ "@context": "https://www.w3.org/2019/wot/td/v1", "id": "urn:example:test/thing_" + strconv.Itoa(i), "title": "example thing", "security": []string{"basic_sc"}, "securityDefinitions": map[string]any{ "basic_sc": map[string]string{ "in": "header", "scheme": "basic", }, }, } _, err := controller.add(td) if err != nil { t.Fatalf("Error adding a TD: %s", err) } } total, err := controller.total() if err != nil { t.Fatalf("Error getting total of TD: %s", err) } if total != createTotal { t.Fatalf("Expected total %d but got %d", createTotal, total) } } func TestControllerCleanExpired(t *testing.T) { // shorten controller's cleanup interval to test quickly controllerExpiryCleanupInterval = 1 * time.Second const wait = 3 * time.Second controller := setup(t) var td = ThingDescription{ "@context": "https://www.w3.org/2019/wot/td/v1", "id": "urn:example:test/thing1", "title": "example thing", "security": []string{"basic_sc"}, "securityDefinitions": map[string]any{ "basic_sc": map[string]string{ "in": "header", "scheme": "basic", }, }, "registration": map[string]any{ "ttl": 0.1, }, } id, err := controller.add(td) if err != nil { t.Fatal("Error adding a TD:", err.Error()) } time.Sleep(wait) _, err = controller.get(id) if err != nil { switch err.(type) { case *NotFoundError: // good default: t.Fatalf("Got an error other than NotFoundError when getting an expired TD: %s\n", err) } } else { t.Fatalf("Expired TD was not removed") } } <file_sep>/catalog/controller.go // Copyright 2014-2016 Fraunhofer Institute for Applied Information Technology FIT package catalog import ( "bytes" "context" "encoding/json" "fmt" "log" "runtime/debug" "strconv" "time" xpath "github.com/antchfx/jsonquery" jsonpath "github.com/bhmj/jsonslice" jsonpatch "github.com/evanphx/json-patch/v5" "github.com/linksmart/service-catalog/v3/utils" "github.com/linksmart/thing-directory/wot" uuid "github.com/satori/go.uuid" ) var controllerExpiryCleanupInterval = 60 * time.Second // to be modified in unit tests type Controller struct { storage Storage listeners eventHandler } func NewController(storage Storage) (CatalogController, error) { c := Controller{ storage: storage, } go c.cleanExpired() return &c, nil } func (c *Controller) AddSubscriber(listener EventListener) { c.listeners = append(c.listeners, listener) } func (c *Controller) add(td ThingDescription) (string, error) { id, ok := td[wot.KeyThingID].(string) if !ok || id == "" { // System generated id id = c.newURN() td[wot.KeyThingID] = id } results, err := validateThingDescription(td) if err != nil { return "", err } if len(results) != 0 { return "", &ValidationError{results} } now := time.Now().UTC() tr := ThingRegistration(td) td[wot.KeyThingRegistration] = wot.ThingRegistration{ Created: &now, Modified: &now, Expires: computeExpiry(tr, now), TTL: ThingTTL(tr), } err = c.storage.add(id, td) if err != nil { return "", err } go c.listeners.created(td) return id, nil } func (c *Controller) get(id string) (ThingDescription, error) { td, err := c.storage.get(id) if err != nil { return nil, err } //tr := ThingRegistration(td) //now := time.Now() //tr.Retrieved = &now //td[wot.KeyThingRegistration] = tr return td, nil } func (c *Controller) update(id string, td ThingDescription) error { oldTD, err := c.storage.get(id) if err != nil { return err } results, err := validateThingDescription(td) if err != nil { return err } if len(results) != 0 { return &ValidationError{ValidationErrors: results} } now := time.Now().UTC() oldTR := ThingRegistration(oldTD) tr := ThingRegistration(td) td[wot.KeyThingRegistration] = wot.ThingRegistration{ Created: oldTR.Created, Modified: &now, Expires: computeExpiry(tr, now), TTL: ThingTTL(tr), } err = c.storage.update(id, td) if err != nil { return err } go c.listeners.updated(oldTD, td) return nil } // TODO: Improve patch by reducing the number of (de-)serializations func (c *Controller) patch(id string, td ThingDescription) error { oldTD, err := c.storage.get(id) if err != nil { return err } // serialize to json for mergepatch input oldBytes, err := json.Marshal(oldTD) if err != nil { return err } patchBytes, err := json.Marshal(td) if err != nil { return err } //fmt.Printf("%s", patchBytes) newBytes, err := jsonpatch.MergePatch(oldBytes, patchBytes) if err != nil { return err } oldBytes, patchBytes = nil, nil td = ThingDescription{} err = json.Unmarshal(newBytes, &td) if err != nil { return err } results, err := validateThingDescription(td) if err != nil { return err } if len(results) != 0 { return &ValidationError{results} } //td[wot.KeyThingRegistrationModified] = time.Now().UTC() now := time.Now().UTC() oldTR := ThingRegistration(oldTD) tr := ThingRegistration(td) td[wot.KeyThingRegistration] = wot.ThingRegistration{ Created: oldTR.Created, Modified: &now, Expires: computeExpiry(tr, now), TTL: ThingTTL(tr), } err = c.storage.update(id, td) if err != nil { return err } go c.listeners.updated(oldTD, td) return nil } func (c *Controller) delete(id string) error { oldTD, err := c.storage.get(id) if err != nil { return err } err = c.storage.delete(id) if err != nil { return err } go c.listeners.deleted(oldTD) return nil } func (c *Controller) list(page, perPage int) ([]ThingDescription, int, error) { tds, total, err := c.storage.list(page, perPage) if err != nil { return nil, 0, err } return tds, total, nil } func (c *Controller) listAll() ([]ThingDescription, int, error) { var items []ThingDescription pp := MaxPerPage for p := 1; ; p++ { slice, total, err := c.storage.list(p, pp) if err != nil { return nil, 0, err } items = append(items, slice...) if p*pp >= total { return items, total, nil } } } func (c *Controller) listAllBytes() ([]byte, error) { return c.storage.listAllBytes() } // Deprecated // Note: filterJSONPath performs several (de-)serializations // Use filterJSONPathBytes to query bytes directly func (c *Controller) filterJSONPath(path string, page, perPage int) ([]interface{}, int, error) { var results []interface{} // query all items items, total, err := c.listAll() if err != nil { return nil, 0, err } if total == 0 { return results, 0, nil } // serialize to json b, err := json.Marshal(items) if err != nil { return nil, 0, fmt.Errorf("error serializing for jsonpath: %s", err) } items = nil // filter results with jsonpath b, err = jsonpath.Get(b, path) if err != nil { return nil, 0, &BadRequestError{S: fmt.Sprintf("error evaluating jsonpath: %s", err)} } // de-serialize the filtered results err = json.Unmarshal(b, &results) if err != nil { return nil, 0, fmt.Errorf("error de-serializing jsonpath evaluation results: %s", err) } b = nil // paginate offset, limit, err := utils.GetPagingAttr(len(results), page, perPage, MaxPerPage) if err != nil { return nil, 0, &BadRequestError{S: fmt.Sprintf("unable to paginate: %s", err)} } // return the requested page return results[offset : offset+limit], len(results), nil } func (c *Controller) filterJSONPathBytes(query string) ([]byte, error) { // query all items b, err := c.listAllBytes() if err != nil { return nil, err } // filter results with jsonpath b, err = jsonpath.Get(b, query) if err != nil { return nil, &BadRequestError{fmt.Sprintf("error evaluating jsonpath: %s", err)} } return b, nil } // Deprecated // Note: filterXPath performs several (de-)serializations // Use filterXPathBytes to query bytes directly func (c *Controller) filterXPath(path string, page, perPage int) ([]interface{}, int, error) { var results []interface{} // query all items items, total, err := c.listAll() if err != nil { return nil, 0, err } if total == 0 { return results, 0, nil } // serialize to json b, err := json.Marshal(items) if err != nil { return nil, 0, fmt.Errorf("error serializing entries for xpath filtering: %s", err) } items = nil // parse the json document doc, err := xpath.Parse(bytes.NewReader(b)) if err != nil { return nil, 0, fmt.Errorf("error parsing serialized input for xpath filtering: %s", err) } b = nil // filter with xpath nodes, err := xpath.QueryAll(doc, path) if err != nil { return nil, 0, &BadRequestError{S: fmt.Sprintf("error filtering input with xpath: %s", err)} } for _, n := range nodes { results = append(results, getObjectFromXPathNode(n)) } // paginate offset, limit, err := utils.GetPagingAttr(len(results), page, perPage, MaxPerPage) if err != nil { return nil, 0, &BadRequestError{S: fmt.Sprintf("unable to paginate: %s", err)} } // return the requested page return results[offset : offset+limit], len(results), nil } func (c *Controller) filterXPathBytes(path string) ([]byte, error) { // query all items b, err := c.listAllBytes() if err != nil { return nil, err } // parse the json document doc, err := xpath.Parse(bytes.NewReader(b)) if err != nil { return nil, fmt.Errorf("error parsing serialized input for xpath filtering: %s", err) } // filter with xpath nodes, err := xpath.QueryAll(doc, path) if err != nil { return nil, &BadRequestError{S: fmt.Sprintf("error filtering input with xpath: %s", err)} } results := make([]interface{}, len(nodes)) for i := range nodes { results[i] = getObjectFromXPathNode(nodes[i]) } // serialize b, err = json.Marshal(results) if err != nil { return nil, fmt.Errorf("error serliazing results of xpath filtering: %s", err) } return b, nil } func (c *Controller) iterateBytes(ctx context.Context) <-chan []byte { return c.storage.iterateBytes(ctx) } // UTILITY FUNCTIONS func ThingRegistration(td ThingDescription) *wot.ThingRegistration { _, found := td[wot.KeyThingRegistration] if found && td[wot.KeyThingRegistration] != nil { if trMap, ok := td[wot.KeyThingRegistration].(map[string]interface{}); ok { var tr wot.ThingRegistration parsedTime := func(t string) *time.Time { parsed, err := time.Parse(time.RFC3339, t) if err != nil { panic(err) } return &parsed } if created, ok := trMap[wot.KeyThingRegistrationCreated].(string); ok { tr.Created = parsedTime(created) } if modified, ok := trMap[wot.KeyThingRegistrationModified].(string); ok { tr.Modified = parsedTime(modified) } if expires, ok := trMap[wot.KeyThingRegistrationExpires].(string); ok { tr.Expires = parsedTime(expires) } if ttl, ok := trMap[wot.KeyThingRegistrationTTL].(float64); ok { tr.TTL = &ttl } return &tr } } // not found return nil } func computeExpiry(tr *wot.ThingRegistration, now time.Time) *time.Time { if tr != nil { if tr.TTL != nil { // calculate expiry as now+ttl expires := now.Add(time.Duration(*tr.TTL * 1e9)) return &expires } else if tr.Expires != nil { return tr.Expires } } // no expiry return nil } func ThingExpires(tr *wot.ThingRegistration) *time.Time { if tr != nil { return tr.Expires } // no expiry return nil } func ThingTTL(tr *wot.ThingRegistration) *float64 { if tr != nil { return tr.TTL } // no TTL return nil } // basicTypeFromXPathStr is a hack to get the actual data type from xpath.TextNode // Note: This might cause unexpected behaviour e.g. if user explicitly set string value to "true" or "false" func basicTypeFromXPathStr(strVal string) interface{} { floatVal, err := strconv.ParseFloat(strVal, 64) if err == nil { return floatVal } // string value is set to "true" or "false" by the library for boolean values. boolVal, err := strconv.ParseBool(strVal) // bit value is set to true or false by the library. if err == nil { return boolVal } return strVal } // getObjectFromXPathNode gets the concrete object from node by parsing the node recursively. // Ideally this function needs to be part of the library itself func getObjectFromXPathNode(n *xpath.Node) interface{} { if n.Type == xpath.TextNode { // if top most element is of type textnode, then just return the value return basicTypeFromXPathStr(n.Data) } if n.FirstChild != nil && n.FirstChild.Data == "" { // in case of array, there will be no wot.Key retArray := make([]interface{}, 0) for child := n.FirstChild; child != nil; child = child.NextSibling { retArray = append(retArray, getObjectFromXPathNode(child)) } return retArray } else { // normal map retMap := make(map[string]interface{}) for child := n.FirstChild; child != nil; child = child.NextSibling { if child.Type != xpath.TextNode { retMap[child.Data] = getObjectFromXPathNode(child) } else { return basicTypeFromXPathStr(child.Data) } } return retMap } } func (c *Controller) total() (int, error) { return c.storage.total() } func (c *Controller) cleanExpired() { defer func() { if r := recover(); r != nil { log.Printf("panic: %v\n%s\n", r, debug.Stack()) go c.cleanExpired() } }() for t := range time.Tick(controllerExpiryCleanupInterval) { var expiredServices []ThingDescription for td := range c.storage.iterator() { if expires := ThingExpires(ThingRegistration(td)); expires != nil { if t.After(*expires) { expiredServices = append(expiredServices, td) } } } for i := range expiredServices { id := expiredServices[i][wot.KeyThingID].(string) log.Printf("cleanExpired() Removing expired registration: %s", id) err := c.storage.delete(id) if err != nil { log.Printf("cleanExpired() Error removing expired registration: %s: %s", id, err) continue } } } } // Stop the controller func (c *Controller) Stop() { //log.Println("Stopped the controller.") } // Generate a unique URN func (c *Controller) newURN() string { return fmt.Sprintf("urn:uuid:%s", uuid.NewV4().String()) } <file_sep>/go.mod module github.com/linksmart/thing-directory go 1.14 require ( github.com/antchfx/jsonquery v1.1.4 github.com/bhmj/jsonslice v0.0.0-20200507101114-bc37219df21b github.com/codegangsta/negroni v1.0.0 github.com/davecgh/go-spew v1.1.1 // indirect github.com/evanphx/json-patch/v5 v5.1.0 github.com/gorilla/context v1.1.1 github.com/gorilla/mux v1.7.3 github.com/grandcat/zeroconf v1.0.1-0.20200528163356-cfc8183341d9 github.com/justinas/alice v0.0.0-20160512134231-052b8b6c18ed github.com/kelseyhightower/envconfig v1.4.0 github.com/linksmart/go-sec v1.4.2 github.com/linksmart/service-catalog/v3 v3.0.0-beta.1.0.20200302143206-92739dd2a511 github.com/miekg/dns v1.1.29 // indirect github.com/onsi/ginkgo v1.12.0 // indirect github.com/onsi/gomega v1.9.0 // indirect github.com/rs/cors v1.7.0 github.com/satori/go.uuid v1.2.0 github.com/syndtr/goleveldb v1.0.0 github.com/xeipuuv/gojsonschema v1.2.0 golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37 // indirect golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2 // indirect golang.org/x/sys v0.0.0-20200519105757-fe76b779f299 // indirect ) <file_sep>/catalog/http.go // Copyright 2014-2016 Fraunhofer Institute for Applied Information Technology FIT package catalog import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "github.com/gorilla/mux" "github.com/linksmart/service-catalog/v3/utils" "github.com/linksmart/thing-directory/wot" ) const ( MaxPerPage = 100 // query parameters QueryParamPage = "page" QueryParamPerPage = "per_page" QueryParamJSONPath = "jsonpath" QueryParamXPath = "xpath" QueryParamSearchQuery = "query" // Deprecated QueryParamFetchPath = "fetch" ) type ThingDescriptionPage struct { Context string `json:"@context"` Type string `json:"@type"` Items interface{} `json:"items"` Page int `json:"page"` PerPage int `json:"perPage"` Total int `json:"total"` } type ValidationResult struct { Valid bool `json:"valid"` Errors []string `json:"errors"` } type HTTPAPI struct { controller CatalogController } func NewHTTPAPI(controller CatalogController, version string) *HTTPAPI { return &HTTPAPI{ controller: controller, } } // Post handler creates one item func (a *HTTPAPI) Post(w http.ResponseWriter, req *http.Request) { body, err := ioutil.ReadAll(req.Body) req.Body.Close() if err != nil { ErrorResponse(w, http.StatusBadRequest, err.Error()) return } var td ThingDescription if err := json.Unmarshal(body, &td); err != nil { ErrorResponse(w, http.StatusBadRequest, "Error processing the request:", err.Error()) return } if td[wot.KeyThingID] != nil { id, ok := td[wot.KeyThingID].(string) if !ok || id != "" { ErrorResponse(w, http.StatusBadRequest, "Registering with user-defined id is not possible using a POST request.") return } } id, err := a.controller.add(td) if err != nil { switch err.(type) { case *ConflictError: ErrorResponse(w, http.StatusConflict, "Error creating the resource:", err.Error()) return case *BadRequestError: ErrorResponse(w, http.StatusBadRequest, "Invalid registration:", err.Error()) return case *ValidationError: ValidationErrorResponse(w, err.(*ValidationError).ValidationErrors) return default: ErrorResponse(w, http.StatusInternalServerError, "Error creating the registration:", err.Error()) return } } w.Header().Set("Location", id) w.WriteHeader(http.StatusCreated) } // Put handler updates an existing item (Response: StatusOK) // If the item does not exist, a new one will be created with the given id (Response: StatusCreated) func (a *HTTPAPI) Put(w http.ResponseWriter, req *http.Request) { params := mux.Vars(req) body, err := ioutil.ReadAll(req.Body) req.Body.Close() if err != nil { ErrorResponse(w, http.StatusBadRequest, err.Error()) return } var td ThingDescription if err := json.Unmarshal(body, &td); err != nil { ErrorResponse(w, http.StatusBadRequest, "Error processing the request:", err.Error()) return } if id, ok := td[wot.KeyThingID].(string); !ok || id == "" { ErrorResponse(w, http.StatusBadRequest, "Registration without id is not possible using a PUT request.") return } if params["id"] != td[wot.KeyThingID] { ErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("Resource id in path (%s) does not match the id in body (%s)", params["id"], td[wot.KeyThingID])) return } err = a.controller.update(params["id"], td) if err != nil { switch err.(type) { case *NotFoundError: // Create a new device with the given id id, err := a.controller.add(td) if err != nil { switch err.(type) { case *ConflictError: ErrorResponse(w, http.StatusConflict, "Error creating the registration:", err.Error()) return case *BadRequestError: ErrorResponse(w, http.StatusBadRequest, "Invalid registration:", err.Error()) return case *ValidationError: ValidationErrorResponse(w, err.(*ValidationError).ValidationErrors) return default: ErrorResponse(w, http.StatusInternalServerError, "Error creating the registration:", err.Error()) return } } w.Header().Set("Location", id) w.WriteHeader(http.StatusCreated) return case *BadRequestError: ErrorResponse(w, http.StatusBadRequest, "Invalid registration:", err.Error()) return case *ValidationError: ValidationErrorResponse(w, err.(*ValidationError).ValidationErrors) return default: ErrorResponse(w, http.StatusInternalServerError, "Error updating the registration:", err.Error()) return } } w.WriteHeader(http.StatusNoContent) } // Patch updates parts or all of an existing item (Response: StatusOK) func (a *HTTPAPI) Patch(w http.ResponseWriter, req *http.Request) { params := mux.Vars(req) body, err := ioutil.ReadAll(req.Body) req.Body.Close() if err != nil { ErrorResponse(w, http.StatusBadRequest, err.Error()) return } var td ThingDescription if err := json.Unmarshal(body, &td); err != nil { ErrorResponse(w, http.StatusBadRequest, "Error processing the request:", err.Error()) return } if id, ok := td[wot.KeyThingID].(string); ok && id == "" { if params["id"] != td[wot.KeyThingID] { ErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("Resource id in path (%s) does not match the id in body (%s)", params["id"], td[wot.KeyThingID])) return } } err = a.controller.patch(params["id"], td) if err != nil { switch err.(type) { case *NotFoundError: ErrorResponse(w, http.StatusNotFound, "Invalid registration:", err.Error()) return case *BadRequestError: ErrorResponse(w, http.StatusBadRequest, "Invalid registration:", err.Error()) return case *ValidationError: ValidationErrorResponse(w, err.(*ValidationError).ValidationErrors) return default: ErrorResponse(w, http.StatusInternalServerError, "Error updating the registration:", err.Error()) return } } w.WriteHeader(http.StatusNoContent) } // Get handler get one item func (a *HTTPAPI) Get(w http.ResponseWriter, req *http.Request) { params := mux.Vars(req) td, err := a.controller.get(params["id"]) if err != nil { switch err.(type) { case *NotFoundError: ErrorResponse(w, http.StatusNotFound, err.Error()) return default: ErrorResponse(w, http.StatusInternalServerError, "Error retrieving the registration: ", err.Error()) return } } b, err := json.Marshal(td) if err != nil { ErrorResponse(w, http.StatusInternalServerError, err.Error()) return } w.Header().Set("Content-Type", wot.MediaTypeThingDescription) _, err = w.Write(b) if err != nil { log.Printf("ERROR writing HTTP response: %s", err) } } // Delete removes one item func (a *HTTPAPI) Delete(w http.ResponseWriter, req *http.Request) { params := mux.Vars(req) err := a.controller.delete(params["id"]) if err != nil { switch err.(type) { case *NotFoundError: ErrorResponse(w, http.StatusNotFound, err.Error()) return default: ErrorResponse(w, http.StatusInternalServerError, "Error deleting the registration:", err.Error()) return } } w.WriteHeader(http.StatusNoContent) } // GetMany lists entries in a paginated catalog format func (a *HTTPAPI) GetMany(w http.ResponseWriter, req *http.Request) { err := req.ParseForm() if err != nil { ErrorResponse(w, http.StatusBadRequest, "Error parsing the query:", err.Error()) return } page, perPage, err := utils.ParsePagingParams( req.Form.Get(QueryParamPage), req.Form.Get(QueryParamPerPage), MaxPerPage) if err != nil { ErrorResponse(w, http.StatusBadRequest, "Error parsing query parameters:", err.Error()) return } var items interface{} var total int if jsonPath := req.Form.Get(QueryParamJSONPath); jsonPath != "" { if req.Form.Get(QueryParamXPath) != "" { ErrorResponse(w, http.StatusBadRequest, "query with jsonpath should not be mixed with xpath") return } w.Header().Add("X-Request-Jsonpath", jsonPath) items, total, err = a.controller.filterJSONPath(jsonPath, page, perPage) if err != nil { switch err.(type) { case *BadRequestError: ErrorResponse(w, http.StatusBadRequest, err.Error()) return default: ErrorResponse(w, http.StatusInternalServerError, err.Error()) return } } } else if xPath := req.Form.Get(QueryParamXPath); xPath != "" { w.Header().Add("X-Request-Xpath", xPath) items, total, err = a.controller.filterXPath(xPath, page, perPage) if err != nil { switch err.(type) { case *BadRequestError: ErrorResponse(w, http.StatusBadRequest, err.Error()) return default: ErrorResponse(w, http.StatusInternalServerError, err.Error()) return } } } else if req.Form.Get(QueryParamFetchPath) != "" { ErrorResponse(w, http.StatusBadRequest, "fetch query parameter is deprecated. Use jsonpath or xpath") return } else { items, total, err = a.controller.list(page, perPage) if err != nil { switch err.(type) { case *BadRequestError: ErrorResponse(w, http.StatusBadRequest, err.Error()) return default: ErrorResponse(w, http.StatusInternalServerError, err.Error()) return } } } coll := &ThingDescriptionPage{ Context: ResponseContextURL, Type: ResponseType, Items: items, Page: page, PerPage: perPage, Total: total, } b, err := json.Marshal(coll) if err != nil { ErrorResponse(w, http.StatusInternalServerError, err.Error()) return } w.Header().Set("Content-Type", wot.MediaTypeJSONLD) w.Header().Set("X-Request-URL", req.RequestURI) _, err = w.Write(b) if err != nil { log.Printf("ERROR writing HTTP response: %s", err) } } // GetAll lists entries in a paginated catalog format func (a *HTTPAPI) GetAll(w http.ResponseWriter, req *http.Request) { //flusher, ok := w.(http.Flusher) //if !ok { // panic("expected http.ResponseWriter to be an http.Flusher") //} w.Header().Set("Content-Type", wot.MediaTypeJSONLD) w.Header().Set("X-Content-Type-Options", "nosniff") // tell clients not to infer content type from partial body _, err := fmt.Fprintf(w, "[") if err != nil { log.Printf("ERROR writing HTTP response: %s", err) } first := true for item := range a.controller.iterateBytes(req.Context()) { select { case <-req.Context().Done(): log.Println("Cancelled by client.") if err := req.Context().Err(); err != nil { log.Printf("Client err: %s", err) return } default: if first { first = false } else { _, err := fmt.Fprint(w, ",") if err != nil { log.Printf("ERROR writing HTTP response: %s", err) } } _, err := w.Write(item) if err != nil { log.Printf("ERROR writing HTTP response: %s", err) } //time.Sleep(500 * time.Millisecond) //flusher.Flush() } } _, err = fmt.Fprintf(w, "]") if err != nil { log.Printf("ERROR writing HTTP response: %s", err) } } // SearchJSONPath returns the JSONPath query result func (a *HTTPAPI) SearchJSONPath(w http.ResponseWriter, req *http.Request) { err := req.ParseForm() if err != nil { ErrorResponse(w, http.StatusBadRequest, "Error parsing the query: ", err.Error()) return } query := req.Form.Get(QueryParamSearchQuery) if query == "" { ErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("No value for %s argument", QueryParamSearchQuery)) return } w.Header().Add("X-Request-Query", query) b, err := a.controller.filterJSONPathBytes(query) if err != nil { switch err.(type) { case *BadRequestError: ErrorResponse(w, http.StatusBadRequest, err.Error()) return default: ErrorResponse(w, http.StatusInternalServerError, err.Error()) return } } w.Header().Set("Content-Type", wot.MediaTypeJSON) w.Header().Set("X-Request-URL", req.RequestURI) _, err = w.Write(b) if err != nil { log.Printf("ERROR writing HTTP response: %s", err) return } } // SearchXPath returns the XPath query result func (a *HTTPAPI) SearchXPath(w http.ResponseWriter, req *http.Request) { err := req.ParseForm() if err != nil { ErrorResponse(w, http.StatusBadRequest, "Error parsing the query: ", err.Error()) return } query := req.Form.Get(QueryParamSearchQuery) if query == "" { ErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("No value for %s argument", QueryParamSearchQuery)) return } w.Header().Add("X-Request-Query", query) b, err := a.controller.filterXPathBytes(query) if err != nil { switch err.(type) { case *BadRequestError: ErrorResponse(w, http.StatusBadRequest, err.Error()) return default: ErrorResponse(w, http.StatusInternalServerError, err.Error()) return } } w.Header().Set("Content-Type", wot.MediaTypeJSON) w.Header().Set("X-Request-URL", req.RequestURI) _, err = w.Write(b) if err != nil { log.Printf("ERROR writing HTTP response: %s", err) return } } // GetValidation handler gets validation for the request body func (a *HTTPAPI) GetValidation(w http.ResponseWriter, req *http.Request) { body, err := ioutil.ReadAll(req.Body) req.Body.Close() if err != nil { ErrorResponse(w, http.StatusBadRequest, err.Error()) return } if len(body) == 0 { ErrorResponse(w, http.StatusBadRequest, "Empty request body") return } var td ThingDescription if err := json.Unmarshal(body, &td); err != nil { ErrorResponse(w, http.StatusBadRequest, "Error processing the request: ", err.Error()) return } var response ValidationResult results, err := validateThingDescription(td) if err != nil { ErrorResponse(w, http.StatusInternalServerError, err.Error()) return } if len(results) != 0 { for _, result := range results { response.Errors = append(response.Errors, fmt.Sprintf("%s: %s", result.Field, result.Descr)) } } else { response.Valid = true } b, err := json.Marshal(response) if err != nil { ErrorResponse(w, http.StatusInternalServerError, err.Error()) return } w.Header().Set("Content-Type", wot.MediaTypeJSON) w.WriteHeader(http.StatusOK) _, err = w.Write(b) if err != nil { log.Printf("ERROR writing HTTP response: %s", err) } } <file_sep>/notification/notification.go package notification import ( "github.com/linksmart/thing-directory/catalog" "github.com/linksmart/thing-directory/wot" ) type Event struct { ID string `json:"id"` Type wot.EventType `json:"event"` Data catalog.ThingDescription `json:"data"` } // NotificationController interface type NotificationController interface { // subscribe to the events. the caller will get events through the channel 'client' starting from 'lastEventID' subscribe(client chan Event, eventTypes []wot.EventType, diff bool, lastEventID string) error // unsubscribe and close the channel 'client' unsubscribe(client chan Event) error // Stop the controller Stop() catalog.EventListener } // EventQueue interface type EventQueue interface { //addRotate adds new and delete the old event if the event queue is full addRotate(event Event) error // getAllAfter gets the events after the event ID getAllAfter(id string) ([]Event, error) // getNewID creates a new ID for the event getNewID() (string, error) // Close all the resources acquired by the queue implementation Close() } <file_sep>/wot/discovery.go package wot import ( "time" ) const ( // DNS-SD Types DNSSDServiceType = "_wot._tcp" DNSSDServiceSubtypeThing = "_thing" // _thing._sub._wot._tcp DNSSDServiceSubtypeDirectory = "_directory" // _directory._sub._wot._tcp // Media Types MediaTypeJSONLD = "application/ld+json" MediaTypeJSON = "application/json" // TD keys used by directory KeyThingID = "id" KeyThingRegistration = "registration" KeyThingRegistrationCreated = "created" KeyThingRegistrationModified = "modified" KeyThingRegistrationExpires = "expires" KeyThingRegistrationTTL = "ttl" // TD event types EventTypeCreate = "create" EventTypeUpdate = "update" EventTypeDelete = "delete" ) type EnrichedTD struct { *ThingDescription Registration *ThingRegistration `json:"registration,omitempty"` } // ThingRegistration contains the registration information // alphabetically sorted to match the TD map serialization type ThingRegistration struct { Created *time.Time `json:"created,omitempty"` Expires *time.Time `json:"expires,omitempty"` Modified *time.Time `json:"modified,omitempty"` Retrieved *time.Time `json:"retrieved,omitempty"` TTL *float64 `json:"ttl,omitempty"` } type EventType string func (e EventType) IsValid() bool { switch e { case EventTypeCreate, EventTypeUpdate, EventTypeDelete: return true default: return false } } <file_sep>/config.go // Copyright 2014-2016 Fraunhofer Institute for Applied Information Technology FIT package main import ( "encoding/json" "fmt" "io/ioutil" "net/url" "github.com/kelseyhightower/envconfig" "github.com/linksmart/go-sec/auth/obtainer" "github.com/linksmart/go-sec/auth/validator" "github.com/linksmart/thing-directory/catalog" ) type Config struct { ServiceID string `json:"serviceID"` Description string `json:"description"` Validation Validation `json:"validation"` HTTP HTTPConfig `json:"http"` DNSSD DNSSDConfig `json:"dnssd"` Storage StorageConfig `json:"storage"` ServiceCatalog ServiceCatalog `json:"serviceCatalog"` } type Validation struct { JSONSchemas []string `json:"jsonSchemas"` } type HTTPConfig struct { PublicEndpoint string `json:"publicEndpoint"` BindAddr string `json:"bindAddr"` BindPort int `json:"bindPort"` TLSConfig *TLSConfig `json:"tls"` Auth validator.Conf `json:"auth"` } type TLSConfig struct { Enabled bool `json:"enabled"` KeyFile string `json:"keyFile"` CertFile string `json:"certFile"` } type ServiceCatalog struct { Enabled bool `json:"enabled"` Discover bool `json:"discover"` Endpoint string `json:"endpoint"` TTL int `json:"ttl"` Auth obtainer.Conf `json:"auth"` } type DNSSDConfig struct { Publish struct { Enabled bool `json:"enabled"` Instance string `json:"instance"` Domain string `json:"domain"` Interfaces []string `json:"interfaces"` } } type StorageConfig struct { Type string `json:"type"` DSN string `json:"dsn"` } var supportedBackends = map[string]bool{ catalog.BackendMemory: false, catalog.BackendLevelDB: true, } func (c *Config) Validate() error { if c.HTTP.BindAddr == "" || c.HTTP.BindPort == 0 || c.HTTP.PublicEndpoint == "" { return fmt.Errorf("BindAddr, BindPort, and PublicEndpoint have to be defined") } _, err := url.Parse(c.HTTP.PublicEndpoint) if err != nil { return fmt.Errorf("PublicEndpoint should be a valid URL") } if c.HTTP.Auth.Enabled { // Validate ticket validator config err = c.HTTP.Auth.Validate() if err != nil { return fmt.Errorf("invalid auth: %s", err) } } _, err = url.Parse(c.Storage.DSN) if err != nil { return fmt.Errorf("storage DSN should be a valid URL") } if !supportedBackends[c.Storage.Type] { return fmt.Errorf("unsupported storage backend") } if c.ServiceCatalog.Enabled { if c.ServiceCatalog.Endpoint == "" && c.ServiceCatalog.Discover { return fmt.Errorf("Service Catalog must have either endpoint or set discovery flag") } if c.ServiceCatalog.TTL <= 0 { return fmt.Errorf("Service Catalog must have TTL >= 0") } if c.ServiceCatalog.Auth.Enabled { // Validate ticket obtainer config err = c.ServiceCatalog.Auth.Validate() if err != nil { return fmt.Errorf("invalid Service Catalog auth: %s", err) } } } return err } func loadConfig(path string) (*Config, error) { file, err := ioutil.ReadFile(path) if err != nil { return nil, err } var config Config err = json.Unmarshal(file, &config) if err != nil { return nil, err } // Override loaded values with environment variables err = envconfig.Process("td", &config) if err != nil { return nil, err } if err = config.Validate(); err != nil { return nil, fmt.Errorf("invalid configuration: %s", err) } return &config, nil } <file_sep>/catalog/errors.go // Copyright 2014-2016 Fraunhofer Institute for Applied Information Technology FIT package catalog import ( "encoding/json" "fmt" "log" "net/http" "github.com/linksmart/thing-directory/wot" uuid "github.com/satori/go.uuid" ) // Not Found type NotFoundError struct{ S string } func (e *NotFoundError) Error() string { return e.S } // Conflict (non-unique id, assignment to read-only data) type ConflictError struct{ S string } func (e *ConflictError) Error() string { return e.S } // Bad Request type BadRequestError struct{ S string } func (e *BadRequestError) Error() string { return e.S } // Validation error (HTTP Bad Request) type ValidationError struct { ValidationErrors []wot.ValidationError } func (e *ValidationError) Error() string { return "validation errors" } // ErrorResponse writes error to HTTP ResponseWriter func ErrorResponse(w http.ResponseWriter, code int, msg ...interface{}) { ProblemDetailsResponse(w, wot.ProblemDetails{ Status: code, Detail: fmt.Sprint(msg...), }) } func ValidationErrorResponse(w http.ResponseWriter, validationIssues []wot.ValidationError) { ProblemDetailsResponse(w, wot.ProblemDetails{ Status: http.StatusBadRequest, Detail: "The input did not pass the JSON Schema validation", ValidationErrors: validationIssues, }) } // ErrorResponse writes error to HTTP ResponseWriter func ProblemDetailsResponse(w http.ResponseWriter, pd wot.ProblemDetails) { if pd.Title == "" { pd.Title = http.StatusText(pd.Status) if pd.Title == "" { panic(fmt.Sprint("Invalid HTTP status code: ", pd.Status)) } } pd.Instance = "/errors/" + uuid.NewV4().String() log.Println("Problem Details instance:", pd.Instance) if pd.Status >= 500 { log.Println("ERROR:", pd.Detail) } b, err := json.Marshal(pd) if err != nil { log.Printf("ERROR serializing error object: %s", err) } w.Header().Set("Content-Type", "application/problem+json") w.WriteHeader(pd.Status) _, err = w.Write(b) if err != nil { log.Printf("ERROR writing HTTP response: %s", err) } } <file_sep>/catalog/catalog.go // Copyright 2014-2016 Fraunhofer Institute for Applied Information Technology FIT package catalog import ( "context" "fmt" "github.com/linksmart/thing-directory/wot" ) type ThingDescription = map[string]interface{} const ( ResponseContextURL = "https://linksmart.eu/thing-directory/context.jsonld" ResponseType = "Catalog" // Storage backend types BackendMemory = "memory" BackendLevelDB = "leveldb" ) func validateThingDescription(td map[string]interface{}) ([]wot.ValidationError, error) { result, err := wot.ValidateTD(&td) if err != nil { return nil, fmt.Errorf("error validating with JSON Schemas: %s", err) } return result, nil } // Controller interface type CatalogController interface { add(d ThingDescription) (string, error) get(id string) (ThingDescription, error) update(id string, d ThingDescription) error patch(id string, d ThingDescription) error delete(id string) error list(page, perPage int) ([]ThingDescription, int, error) listAllBytes() ([]byte, error) // Deprecated filterJSONPath(path string, page, perPage int) ([]interface{}, int, error) filterJSONPathBytes(query string) ([]byte, error) // Deprecated filterXPath(path string, page, perPage int) ([]interface{}, int, error) filterXPathBytes(query string) ([]byte, error) //filterXPathBytes(query string) ([]byte, error) total() (int, error) iterateBytes(ctx context.Context) <-chan []byte cleanExpired() Stop() AddSubscriber(listener EventListener) } // Storage interface type Storage interface { add(id string, td ThingDescription) error update(id string, td ThingDescription) error delete(id string) error get(id string) (ThingDescription, error) list(page, perPage int) ([]ThingDescription, int, error) listAllBytes() ([]byte, error) total() (int, error) iterator() <-chan ThingDescription iterateBytes(ctx context.Context) <-chan []byte Close() } <file_sep>/wot/thing_description.go package wot import ( "time" ) const MediaTypeThingDescription = "application/td+json" /* This file has go models for Web Of Things (WoT) Things Description following : https://www.w3.org/TR/2019/CR-wot-thing-description-20191106/ (W3C Candidate Recommendation 6 November 2019) */ type any = interface{} // ThingDescription is the structured data describing a Thing type ThingDescription struct { // JSON-LD keyword to define short-hand names called terms that are used throughout a TD document. Context any `json:"@context"` // JSON-LD keyword to label the object with semantic tags (or types). Type any `json:"@type,omitempty"` // Identifier of the Thing in form of a URI [RFC3986] (e.g., stable URI, temporary and mutable URI, URI with local IP address, URN, etc.). ID AnyURI `json:"id,omitempty"` // Provides a human-readable title (e.g., display a text for UI representation) based on a default language. Title string `json:"title"` // Provides multi-language human-readable titles (e.g., display a text for UI representation in different languages). Titles map[string]string `json:"titles,omitempty"` // Provides additional (human-readable) information based on a default language Description string `json:"description,omitempty"` // Can be used to support (human-readable) information in different languages. Descriptions map[string]string `json:"descriptions,omitempty"` // Provides version information. Version *VersionInfo `json:"version,omitempty"` // Provides information when the TD instance was created. Created time.Time `json:"created,omitempty"` // Provides information when the TD instance was last modified. Modified time.Time `json:"modified,omitempty"` // Provides information about the TD maintainer as URI scheme (e.g., mailto [RFC6068], tel [RFC3966], https). Support AnyURI `json:"support,omitempty"` /* Define the base URI that is used for all relative URI references throughout a TD document. In TD instances, all relative URIs are resolved relative to the base URI using the algorithm defined in [RFC3986]. base does not affect the URIs used in @context and the IRIs used within Linked Data [LINKED-DATA] graphs that are relevant when semantic processing is applied to TD instances. */ Base string `json:"base,omitempty"` // All Property-based Interaction Affordances of the Thing. Properties map[string]PropertyAffordance `json:"properties,omitempty"` // All Action-based Interaction Affordances of the Thing. Actions map[string]ActionAffordance `json:"actions,omitempty"` // All Event-based Interaction Affordances of the Thing. Events map[string]EventAffordance `json:"events,omitempty"` // Provides Web links to arbitrary resources that relate to the specified Thing Description. Links []Link `json:"links,omitempty"` // Set of form hypermedia controls that describe how an operation can be performed. Forms are serializations of Protocol Bindings. In this version of TD, all operations that can be described at the Thing level are concerning how to interact with the Thing's Properties collectively at once. Forms []Form `json:"forms,omitempty"` // Set of security definition names, chosen from those defined in securityDefinitions. These must all be satisfied for access to resources Security any `json:"security"` // Set of named security configurations (definitions only). Not actually applied unless names are used in a security name-value pair. SecurityDefinitions map[string]SecurityScheme `json:"securityDefinitions"` } /*Metadata of a Thing that shows the possible choices to Consumers, thereby suggesting how Consumers may interact with the Thing. There are many types of potential affordances, but W3C WoT defines three types of Interaction Affordances: Properties, Actions, and Events.*/ type InteractionAffordance struct { // JSON-LD keyword to label the object with semantic tags (or types). Type any `json:"@type,omitempty"` // Provides a human-readable title (e.g., display a text for UI representation) based on a default language. Title string `json:"title,omitempty"` // Provides multi-language human-readable titles (e.g., display a text for UI representation in different languages). Titles map[string]string `json:"titles,omitempty"` // Provides additional (human-readable) information based on a default language Description string `json:"description,omitempty"` // Can be used to support (human-readable) information in different languages. Descriptions map[string]string `json:"descriptions,omitempty"` /* Set of form hypermedia controls that describe how an operation can be performed. Forms are serializations of Protocol Bindings. When a Form instance is within an ActionAffordance instance, the value assigned to op MUST be invokeaction. When a Form instance is within an EventAffordance instance, the value assigned to op MUST be either subscribeevent, unsubscribeevent, or both terms within an Array. When a Form instance is within a PropertyAffordance instance, the value assigned to op MUST be one of readproperty, writeproperty, observeproperty, unobserveproperty or an Array containing a combination of these terms. */ Forms []Form `json:"forms"` // Define URI template variables as collection based on DataSchema declarations. UriVariables map[string]DataSchema `json:"uriVariables,omitempty"` } /* An Interaction Affordance that exposes state of the Thing. This state can then be retrieved (read) and optionally updated (write). Things can also choose to make Properties observable by pushing the new state after a change. */ type PropertyAffordance struct { InteractionAffordance DataSchema Observable bool `json:"observable,omitempty"` } /* An Interaction Affordance that allows to invoke a function of the Thing, which manipulates state (e.g., toggling a lamp on or off) or triggers a process on the Thing (e.g., dim a lamp over time). */ type ActionAffordance struct { InteractionAffordance // Used to define the input data schema of the Action. Input DataSchema `json:"input,omitempty"` // Used to define the output data schema of the Action. Output DataSchema `json:"output,omitempty"` // Signals if the Action is safe (=true) or not. Used to signal if there is no internal state (cf. resource state) is changed when invoking an Action. In that case responses can be cached as example. Safe bool `json:"safe"` //default: false // Indicates whether the Action is idempotent (=true) or not. Informs whether the Action can be called repeatedly with the same result, if present, based on the same input. Idempotent bool `json:"idempotent"` //default: false } /* An Interaction Affordance that describes an event source, which asynchronously pushes event data to Consumers (e.g., overheating alerts). */ type EventAffordance struct { InteractionAffordance // Defines data that needs to be passed upon subscription, e.g., filters or message format for setting up Webhooks. Subscription DataSchema `json:"subscription,omitempty"` // Defines the data schema of the Event instance messages pushed by the Thing. Data DataSchema `json:"data,omitempty"` // Defines any data that needs to be passed to cancel a subscription, e.g., a specific message to remove a Webhook. Cancellation DataSchema `json:"optional,omitempty"` } /* A form can be viewed as a statement of "To perform an operation type operation on form context, make a request method request to submission target" where the optional form fields may further describe the required request. In Thing Descriptions, the form context is the surrounding Object, such as Properties, Actions, and Events or the Thing itself for meta-interactions. */ type Form struct { /* Indicates the semantic intention of performing the operation(s) described by the form. For example, the Property interaction allows get and set operations. The protocol binding may contain a form for the get operation and a different form for the set operation. The op attribute indicates which form is for which and allows the client to select the correct form for the operation required. op can be assigned one or more interaction verb(s) each representing a semantic intention of an operation. It can be one of: readproperty, writeproperty, observeproperty, unobserveproperty, invokeaction, subscribeevent, unsubscribeevent, readallproperties, writeallproperties, readmultipleproperties, or writemultipleproperties a. When a Form instance is within an ActionAffordance instance, the value assigned to op MUST be invokeaction. b. When a Form instance is within an EventAffordance instance, the value assigned to op MUST be either subscribeevent, unsubscribeevent, or both terms within an Array. c. When a Form instance is within a PropertyAffordance instance, the value assigned to op MUST be one of readproperty, writeproperty, observeproperty, unobserveproperty or an Array containing a combination of these terms. */ Op any `json:"op"` // Target IRI of a link or submission target of a form. Href AnyURI `json:"href"` // Assign a content type based on a media type (e.g., text/plain) and potential parameters (e.g., charset=utf-8) for the media type [RFC2046]. ContentType string `json:"contentType"` //default: "application/json" // Content coding values indicate an encoding transformation that has been or can be applied to a representation. Content codings are primarily used to allow a representation to be compressed or otherwise usefully transformed without losing the identity of its underlying media type and without loss of information. Examples of content coding include "gzip", "deflate", etc. . // Possible values for the contentCoding property can be found, e.g., in thttps://www.iana.org/assignments/http-parameters/http-parameters.xhtml#content-coding ContentCoding string `json:"contentCoding,omitempty"` // Indicates the exact mechanism by which an interaction will be accomplished for a given protocol when there are multiple options. // For example, for HTTP and Events, it indicates which of several available mechanisms should be used for asynchronous notifications such as long polling (longpoll), WebSub [websub] (websub), Server-Sent Events [eventsource] (sse). Please note that there is no restriction on the subprotocol selection and other mechanisms can also be announced by this subprotocol term. SubProtocol string `json:"subprotocol,omitempty"` // Set of security definition names, chosen from those defined in securityDefinitions. These must all be satisfied for access to resources. Security any `json:"security,omitempty"` // Set of authorization scope identifiers provided as an array. These are provided in tokens returned by an authorization server and associated with forms in order to identify what resources a client may access and how. The values associated with a form should be chosen from those defined in an OAuth2SecurityScheme active on that form. Scopes any `json:"scopes,omitempty"` // This optional term can be used if, e.g., the output communication metadata differ from input metadata (e.g., output contentType differ from the input contentType). The response name contains metadata that is only valid for the response messages. Response *ExpectedResponse `json:"response,omitempty"` } /* A link can be viewed as a statement of the form "link context has a relation type resource at link target", where the optional target attributes may further describe the resource. */ type Link struct { // Target IRI of a link or submission target of a form. Href AnyURI `json:"href"` // Target attribute providing a hint indicating what the media type (RFC2046) of the result of dereferencing the link should be. Type string `json:"type,omitempty"` // A link relation type identifies the semantics of a link. Rel string `json:"rel,omitempty"` // Overrides the link context (by default the Thing itself identified by its id) with the given URI or IRI. Anchor AnyURI `json:"anchor,omitempty"` } type SecurityScheme struct { // JSON-LD keyword to label the object with semantic tags (or types). Type any `json:"@type,omitempty"` // Identification of the security mechanism being configured. e.g. nosec, basic, cert, digest, bearer, pop, psk, public, oauth2, or apike Scheme string `json:"scheme"` // Provides additional (human-readable) information based on a default language Description string `json:"description,omitempty"` // Can be used to support (human-readable) information in different languages. Descriptions map[string]string `json:"descriptions,omitempty"` // URI of the proxy server this security configuration provides access to. If not given, the corresponding security configuration is for the endpoint. Proxy AnyURI `json:"proxy,omitempty"` *BasicSecurityScheme *DigestSecurityScheme *APIKeySecurityScheme *BearerSecurityScheme *CertSecurityScheme *PSKSecurityScheme *PublicSecurityScheme *PoPSecurityScheme *OAuth2SecurityScheme } type DataSchema struct { // JSON-LD keyword to label the object with semantic tags (or types) Type any `json:"@type,omitempty"` // Const corresponds to the JSON schema field "const". Const any `json:"const,omitempty"` // Provides multi-language human-readable titles (e.g., display a text for UI representation in different languages). Description string `json:"description,omitempty"` // Can be used to support (human-readable) information in different languages Descriptions string `json:"descriptions,omitempty"` // Restricted set of values provided as an array. Enum []any `json:"enum,omitempty"` // Allows validation based on a format pattern such as "date-time", "email", "uri", etc. (Also see below.) Format string `json:"format,omitempty"` // OneOf corresponds to the JSON schema field "oneOf". OneOf []DataSchema `json:"oneOf,omitempty"` // ReadOnly corresponds to the JSON schema field "readOnly". ReadOnly bool `json:"readOnly,omitempty"` // Provides a human-readable title (e.g., display a text for UI representation) based on a default language. Title string `json:"title,omitempty"` // Provides multi-language human-readable titles (e.g., display a text for UI representation in different languages). Titles []string `json:"titles,omitempty"` // Assignment of JSON-based data types compatible with JSON Schema (one of boolean, integer, number, string, object, array, or null). // DataType corresponds to the JSON schema field "type". DataType string `json:"type,omitempty"` // Unit corresponds to the JSON schema field "unit". Unit string `json:"unit,omitempty"` // Boolean value that is a hint to indicate whether a property interaction / value is write only (=true) or not (=false). WriteOnly bool `json:"writeOnly,omitempty"` // Metadata describing data of type Array. This Subclass is indicated by the value array assigned to type in DataSchema instances. *ArraySchema // Metadata describing data of type number. This Subclass is indicated by the value number assigned to type in DataSchema instances. *NumberSchema // Metadata describing data of type object. This Subclass is indicated by the value object assigned to type in DataSchema instances. *ObjectSchema } // DataSchemaTypeEnumValues are the allowed values allowed for DataSchema.DataType var DataSchemaDataTypeEnumValues = []string{ "boolean", "integer", "number", "string", "object", "array", "null", } type ArraySchema struct { // Used to define the characteristics of an array. Items any `json:"items,omitempty"` // Defines the maximum number of items that have to be in the array. MaxItems *int `json:"maxItems,omitempty"` // Defines the minimum number of items that have to be in the array. MinItems *int `json:"minItems,omitempty"` } //Specifies both float and double type NumberSchema struct { // Specifies a maximum numeric value. Only applicable for associated number or integer types. Maximum *any `json:"maximum,omitempty"` // Specifies a minimum numeric value. Only applicable for associated number or integer types. Minimum *any `json:"minimum,omitempty"` } type ObjectSchema struct { // Data schema nested definitions. Properties map[string]DataSchema `json:"properties,omitempty"` // Required corresponds to the JSON schema field "required". Required []string `json:"required,omitempty"` } type AnyURI = string /* Communication metadata describing the expected response message. */ type ExpectedResponse struct { ContentType string `json:"contentType,omitempty"` } /* Metadata of a Thing that provides version information about the TD document. If required, additional version information such as firmware and hardware version (term definitions outside of the TD namespace) can be extended via the TD Context Extension mechanism. It is recommended that the values within instances of the VersionInfo Class follow the semantic versioning pattern (https://semver.org/), where a sequence of three numbers separated by a dot indicates the major version, minor version, and patch version, respectively. */ type VersionInfo struct { // Provides a version indicator of this TD instance. Instance string `json:"instance"` } /* Basic Authentication [RFC7617] security configuration identified by the Vocabulary Term basic (i.e., "scheme": "basic"), using an unencrypted username and password. This scheme should be used with some other security mechanism providing confidentiality, for example, TLS. */ type BasicSecurityScheme struct { // Specifies the location of security authentication information. In string `json:"in"` // default: header // Name for query, header, or cookie parameters. Name string `json:"name,omitempty"` } /* Digest Access Authentication [RFC7616] security configuration identified by the Vocabulary Term digest (i.e., "scheme": "digest"). This scheme is similar to basic authentication but with added features to avoid man-in-the-middle attacks. */ type DigestSecurityScheme struct { // Specifies the location of security authentication information. In string `json:"in"` // default: header // Name for query, header, or cookie parameters. Name string `json:"name,omitempty"` //Quality of protection. Qop string `json:"qop,omitempty"` //default: auth } /* API key authentication security configuration identified by the Vocabulary Term apikey (i.e., "scheme": "apikey"). This is for the case where the access token is opaque and is not using a standard token format. */ type APIKeySecurityScheme struct { // Specifies the location of security authentication information. In string `json:"in"` // default: header // Name for query, header, or cookie parameters. Name string `json:"name,omitempty"` } /* Bearer Token [RFC6750] security configuration identified by the Vocabulary Term bearer (i.e., "scheme": "bearer") for situations where bearer tokens are used independently of OAuth2. If the oauth2 scheme is specified it is not generally necessary to specify this scheme as well as it is implied. For format, the value jwt indicates conformance with [RFC7519], jws indicates conformance with [RFC7797], cwt indicates conformance with [RFC8392], and jwe indicates conformance with [RFC7516], with values for alg interpreted consistently with those standards. Other formats and algorithms for bearer tokens MAY be specified in vocabulary extensions */ type BearerSecurityScheme struct { // Specifies the location of security authentication information. In string `json:"in"` // default: header // Name for query, header, or cookie parameters. Name string `json:"name,omitempty"` // URI of the authorization server. Authorization AnyURI `json:"authorization,omitempty"` // Encoding, encryption, or digest algorithm. Alg string `json:"alg"` // default:ES256 // Specifies format of security authentication information. Format string `json:"format"` // default: jwt } /* Certificate-based asymmetric key security configuration conformant with [X509V3] identified by the Vocabulary Term cert (i.e., "scheme": "cert"). */ type CertSecurityScheme struct { // Identifier providing information which can be used for selection or confirmation. Identity string `json:"identity,omitempty"` } /* Pre-shared key authentication security configuration identified by the Vocabulary Term psk (i.e., "scheme": "psk"). */ type PSKSecurityScheme struct { // Identifier providing information which can be used for selection or confirmation. Identity string `json:"identity,omitempty"` } /* Raw public key asymmetric key security configuration identified by the Vocabulary Term public (i.e., "scheme": "public"). */ type PublicSecurityScheme struct { // Identifier providing information which can be used for selection or confirmation. Identity string `json:"identity,omitempty"` } /* Proof-of-possession (PoP) token authentication security configuration identified by the Vocabulary Term pop (i.e., "scheme": "pop"). Here jwt indicates conformance with [RFC7519], jws indicates conformance with [RFC7797], cwt indicates conformance with [RFC8392], and jwe indicates conformance with [RFC7516], with values for alg interpreted consistently with those standards. Other formats and algorithms for PoP tokens MAY be specified in vocabulary extensions.. */ type PoPSecurityScheme struct { // Specifies the location of security authentication information. In string `json:"in"` // default: header // Name for query, header, or cookie parameters. Name string `json:"name,omitempty"` // Encoding, encryption, or digest algorithm. Alg string `json:"alg"` // default:ES256 // Specifies format of security authentication information. Format string `json:"format"` // default: jwt // URI of the authorization server. Authorization AnyURI `json:"authorization,omitempty"` } /* OAuth2 authentication security configuration for systems conformant with [RFC6749] and [RFC8252], identified by the Vocabulary Term oauth2 (i.e., "scheme": "oauth2"). For the implicit flow authorization MUST be included. For the password and client flows token MUST be included. For the code flow both authorization and token MUST be included. If no scopes are defined in the SecurityScheme then they are considered to be empty. */ type OAuth2SecurityScheme struct { // URI of the authorization server. Authorization AnyURI `json:"authorization,omitempty"` //URI of the token server. Token AnyURI `json:"token,omitempty"` //URI of the refresh server. Refresh AnyURI `json:"refresh,omitempty"` //Set of authorization scope identifiers provided as an array. These are provided in tokens returned by an authorization server and associated with forms in order to identify what resources a client may access and how. The values associated with a form should be chosen from those defined in an OAuth2SecurityScheme active on that form. Scopes any `json:"scopes,omitempty"` //Authorization flow. Flow string `json:"flow"` }
97f93ef4bad666857552ca405a7edbf91563269f
[ "Markdown", "Go Module", "Go", "Dockerfile" ]
27
Dockerfile
linksmart/thing-directory
dfc6bbf6de4857a4dfdc15d279deb84ab9472144
d1de133788925937fade86004645456fce6884a2
refs/heads/master
<repo_name>khurramfarooq/GrammarPower<file_sep>/src/com/android/grammarpower/activity/QuizActivity_NounPlural.java /** * */ package com.android.grammarpower.activity; import java.util.List; import java.util.Random; import android.app.AlertDialog; import android.content.DialogInterface; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.TextView; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener; import com.android.grammarpower.service.QuizData; import com.android.grammarpower.service.TextParser; /** * @author <NAME> * */ public class QuizActivity_NounPlural extends SherlockFragmentActivity { RadioButton option1 = null;//(RadioButton)findViewById(R.quizActivity.option1); RadioButton option2 = null;//(RadioButton)findViewById(R.quizActivity.option2); RadioButton option3 = null;//(RadioButton)findViewById(R.quizActivity.option3); String timeText = ""; TextView questionText = null; TextView questionNumberText = null; List<String> fileText = null; QuizData quizData = null; Random random = new Random(); TextView hintText = null; //ProgressDialog progressDialog = null; ImageView optionResultImage = null; int questionNumber = 1; boolean isFirstGame = true; int randomIndex = 0; int intialIndex = 0; int checkIndex = 0; int countHours = 0; private long startTime = 0L; long timeInMilliseconds = 0L; long timeSwapBuff = 0L; long updatedTime = 0L; boolean isIncrementRandomIndex = false; private Handler customHandler = new Handler(); @Override protected void onCreate(Bundle arg0) { // TODO Auto-generated method stub super.onCreate(arg0); setContentView(R.layout.activity_grammar_power_quiz); option1 = (RadioButton)findViewById(R.id.quizActivity_option1); option2 = (RadioButton)findViewById(R.id.quizActivity_option2); option3 = (RadioButton)findViewById(R.id.quizActivity_option3); questionText = (TextView)findViewById(R.id.quizActivity_questionTextInWhite); optionResultImage = (ImageView)findViewById(R.id.quizActivity_optionResultImage); Button stopBtn = (Button)findViewById(R.id.quizActivity_stopButton); TextView yellowQuestionText = null; yellowQuestionText = (TextView)findViewById(R.id.quizActivity_questionTextInYellow); hintText = (TextView)this.findViewById(R.id.quizActivity_hintText); yellowQuestionText.setText(R.string.nounplural_question); hintText.setText(R.string.hint_specialist); final Runnable updateTimerThread = new Runnable() { public void run() { timeInMilliseconds = SystemClock.uptimeMillis() - startTime; updatedTime = timeSwapBuff + timeInMilliseconds; int secs = (int) (updatedTime / 1000); int mins = secs / 60; secs = secs % 60; //int milliseconds = (int) (updatedTime % 1000); if(mins == 60){ ++countHours; timeText = "" + String.format("%02d", countHours) + ":" + String.format("%02d", mins) + ":" + String.format("%02d", secs); } timeText = "" + String.format("%02d", mins) + ":" + String.format("%02d", secs); customHandler.postDelayed(this, 0); } }; startTime = SystemClock.uptimeMillis(); customHandler.postDelayed(updateTimerThread, 0); stopBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub String time = timeText; //time.replace("Time", ""); String []timeArr = time.split(":"); String hours = "0"; String minutes = "00"; String seconds = "00"; if(timeArr.length > 3) { hours = timeArr[0].trim(); minutes = timeArr[1].trim(); seconds = timeArr[2].trim(); // this is the text we'll be operating on SpannableString text = new SpannableString("You did within " + hours + " hours, "+ minutes +" minutes, "+ seconds +" seconds: "+ (questionNumber - 2)); // make "Lorem" (characters 0 to 5) red int index = text.toString().indexOf(": "); index = index + 2; text.setSpan(new ForegroundColorSpan(Color.RED), index, text.toString().length() - 1, 0); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(QuizActivity_NounPlural.this); // set dialog message alertDialogBuilder .setMessage(text) .setCancelable(false) .setPositiveButton("continue", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // if this button is clicked, close // current activity finish(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } else { minutes = timeArr[0].trim(); seconds = timeArr[1].trim(); SpannableString text = new SpannableString("You did within "+ minutes +" minutes, "+ seconds +" seconds: "+ (questionNumber - 2)); int index = text.toString().indexOf(": "); index = index + 2; text.setSpan(new ForegroundColorSpan(Color.RED), index, text.toString().length(), 0); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(QuizActivity_NounPlural.this); // set dialog message alertDialogBuilder .setMessage(text) .setCancelable(false) .setPositiveButton("continue", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // if this button is clicked, close // current activity finish(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } customHandler.removeCallbacks(updateTimerThread); } }); loadFileText(); setFirstQuizQuestion(); } public void loadFileText() { fileText = TextParser.readFile(getAssets(),"DLT3_fin.txt"); } public void refreshFileTextArray() { try { loadFileText(); setFirstQuizQuestion(); } catch(Exception ex) { } } public void setFirstQuizQuestion() { if(fileText.size() > 0) { checkIndex = fileText.size() - 1; if(fileText.size() == 0) { randomIndex = 0; } else { randomIndex = random.nextInt(fileText.size() - 1) - 0 + 0; } intialIndex = randomIndex; quizData = TextParser.splitData(fileText.get(randomIndex)); //questionNumberText.setText("Q." + Integer.toString(questionNumber++)); questionText.setText(quizData.name); option1.setText(quizData.option1); option2.setText(quizData.option2); option3.setText(quizData.option3); fileText.remove(randomIndex); isIncrementRandomIndex = false; questionNumber++; } } public void setNextQuizQuestion() { if(fileText.size() > 0) { if(fileText.size() == 1) { randomIndex = 0; quizData = TextParser.splitData(fileText.get(randomIndex)); fileText.remove(randomIndex); //questionNumberText.setText("Q." + Integer.toString(questionNumber++)); questionText.setText(quizData.name); option1.setText(quizData.option1); option2.setText(quizData.option2); option3.setText(quizData.option3); questionNumber++; return; } else if(checkIndex == intialIndex) { randomIndex = 0; isIncrementRandomIndex = true; } else { intialIndex++; } quizData = TextParser.splitData(fileText.get(randomIndex)); fileText.remove(randomIndex); //questionNumberText.setText("Q." + Integer.toString(questionNumber++)); questionText.setText(quizData.name); option1.setText(quizData.option1); option2.setText(quizData.option2); option3.setText(quizData.option3); if(isIncrementRandomIndex) { randomIndex += 1; } questionNumber++; } else { refreshFileTextArray(); } } public void ToggleRadioButton(View view) { boolean isNextQuestion = false; RadioButton radioButton = null; String selectedOption = ""; switch (view.getId()) { case R.id.quizActivity_option1: checkRadioButton(option1); uncheckRadioButton(option2); uncheckRadioButton(option3); radioButton = (RadioButton) findViewById(view.getId()); selectedOption = radioButton.getText().toString(); if (selectedOption.equals(quizData.correctOption)) { optionResultImage.setImageResource(R.drawable.option_checkmark); //showDialogBox(); disableOption(); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { clearOption(); setNextQuizQuestion(); } }, 1000); } break; case R.id.quizActivity_option2: checkRadioButton(option2); uncheckRadioButton(option1); uncheckRadioButton(option3); radioButton = (RadioButton) findViewById(view.getId()); selectedOption = radioButton.getText().toString(); if (selectedOption.equals(quizData.correctOption)) { optionResultImage.setImageResource(R.drawable.option_checkmark); //showDialogBox(); disableOption(); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub clearOption(); setNextQuizQuestion(); } }, 1000); } break; case R.id.quizActivity_option3: checkRadioButton(option3); uncheckRadioButton(option2); uncheckRadioButton(option1); radioButton = (RadioButton) findViewById(view.getId()); selectedOption = radioButton.getText().toString(); if (selectedOption.equals(quizData.correctOption)) { optionResultImage.setImageResource(R.drawable.option_checkmark); //showDialogBox(); disableOption(); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub clearOption(); setNextQuizQuestion(); } }, 1000); } break; } if(isNextQuestion){ clearOption(); } } public void clearOption() { uncheckRadioButton(option1); uncheckRadioButton(option2); uncheckRadioButton(option3); option1.setEnabled(true); option2.setEnabled(true); option3.setEnabled(true); optionResultImage.setImageResource(0); //progressDialog.dismiss(); } public void disableOption(){ option1.setEnabled(false); option2.setEnabled(false); option3.setEnabled(false); } public void uncheckRadioButton(RadioButton btn) { btn.setChecked(false); btn.setTextColor(Color.BLACK); btn.setTypeface(null, Typeface.NORMAL); } public void checkRadioButton(RadioButton btn) { btn.setTextColor(Color.BLUE); btn.setTypeface(null, Typeface.BOLD); } @Override public boolean onCreateOptionsMenu(Menu menu) { // First Menu Button menu.add("MENU") .setOnMenuItemClickListener(this.MenuButtonHandler) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); return super.onCreateOptionsMenu(menu); } OnMenuItemClickListener MenuButtonHandler = new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { finish(); // Do something else return false; } }; } <file_sep>/src/com/android/grammarpower/service/QuizData.java /** * */ package com.android.grammarpower.service; /** * @author <NAME> * */ public class QuizData { public int quizId; public String name; public String correctOption; public String option1; public String option2; public String option3; } <file_sep>/src/com/android/grammarpower/activity/Grammar_Power_MainActivity.java package com.android.grammarpower.activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.actionbarsherlock.app.SherlockFragmentActivity; public class Grammar_Power_MainActivity extends SherlockFragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_grammar__power__main); Button btnStart = (Button)this.findViewById(R.id.grammarAcitivty_strtBtn); btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Grammar_Power_MainActivity.this, Grammar_Power_SelectActivity.class); startActivity(intent); } }); } // @Override // public boolean onCreateOptionsMenu(Menu menu) { // // Inflate the menu; this adds items to the action bar if it is present. // getMenuInflater().inflate(R.menu.grammar__power__main, menu); // return true; // } }
e14db6a3d9681fcd7505af018a9469806d38b83b
[ "Java" ]
3
Java
khurramfarooq/GrammarPower
4e301abd00ec3a82393c3c506eb546d4da97192e
2e6bfd78d8d8dfbe6fabca8b34bf2b573af33da3
refs/heads/master
<file_sep>from setuptools import setup setup( name='pre-commit-hooks', version='0.2', url='https://github.com/Fedalto/pre-commit-hooks', license='MIT', author='<NAME>', author_email='<EMAIL>', description='pre-commit hooks', install_requires=[ 'mypy' ], classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
f13f6a1b830cec74d1f22039282c4cab6285b5b8
[ "Python" ]
1
Python
Fedalto/pre-commit-hooks
92443f807ff486348e14dcda993017c81c966b7b
f1fc03193dffaee272042599f3173574cbb3a079
refs/heads/master
<repo_name>gowrusreevathsa/flask-Diary<file_sep>/main.py from flask import Flask, render_template,request,redirect,url_for # For flask implementation from bson import ObjectId # For ObjectId to work from pymongo import MongoClient import os import datetime as dt app = Flask(__name__) title = 'Diary' heading = 'Your Diary' day = None month = None year = None monthName = None id = None @app.route('/showPrevNotes/', methods=['POST']) def showPrevNotes(dateidP = None): if dateidP != None: print(dateidP) return redirect(url_for('showNotes', dateid = dateidP)) if request.method == 'POST': dateidT = request.form dateidT = dateidT['dateInput'] return showPrevNotes(dateidT) @app.route('/<dateid>') @app.route('/showNotes/<dateid>') def showNotes(dateid): client = MongoClient("mongodb://127.0.0.1:27017") db = client['dbDiary'] coll = db['diaryNotes'] showId = str(dateid) if len(dateid) != 8: return redirect(url_for('index')) i = coll.find_one({"_id":showId}) dayT, monthT, yearT = detailsFromDateId(dateid) if i == None: preText = "Oops! You don't have any notes for this day :(" return render_template('index.html', day = dayT, month = dt.date(2020, int(monthT), 1).strftime('%B'), year = yearT, preText = preText) else: return render_template('index.html', day = dayT, month = dt.date(2020, int(monthT), 1).strftime('%B'), year = yearT, preText = i['notes']) @app.route('/addNotes/', methods = ['POST']) def addNotes(): notes = '' if request.method == 'POST': notes = request.form notes = notes['notes'] client = MongoClient("mongodb://127.0.0.1:27017") db = client['dbDiary'] coll = db['diaryNotes'] data = [ { "_id":id, "notes": notes } ] if coll.count_documents({"_id":id}, limit = 1): res = coll.update_one({"_id":id}, {"$set":{"notes":notes}}) else: res = coll.insert(data) print(res) for i in coll.find(): print(i) return redirect(url_for('showNotes', dateid = id)) @app.route('/') @app.route('/index/') def index(): client = MongoClient("mongodb://127.0.0.1:27017") db = client['dbDiary'] print("Created or Connected to the database: dbDiary") coll = db['diaryNotes'] preText = '' if coll.count_documents({"_id":id}, limit = 1): i = coll.find_one({'_id':id}) print(i['notes']) preText = i["notes"] return render_template('index.html', day = day ,month = monthName, year = year, preText = preText) def getID(): today = dt.datetime.now() day = today.day month = today.month if day < 10: day = '0' + str(day) if month < 10: month = '0' + str(month) year = str(today.year) return day, month, year, day + month + year def detailsFromDateId(dateid): day = dateid[:2] month = dateid[2:4] year = dateid[4:] return day, month, year if __name__ == "__main__": day, month, year, id = getID() monthName = dt.datetime.now().strftime("%B") app.run(debug = True)<file_sep>/README.md # flask-Diary A small python-flask and MongoDB based diary.
e390ab1478691b668e4f1742d7b52122e7d274e8
[ "Markdown", "Python" ]
2
Python
gowrusreevathsa/flask-Diary
31bae3a4129e23915471abb1af7833dce9abf52a
793f5db2cb35294372dcdf4669d05dd2107f48f8
refs/heads/master
<repo_name>dkasyan/TibiaJS<file_sep>/start.js "use strict"; const open = require("open"); const nodemon = require("nodemon"); nodemon({ cwd: "./out", ext: ".js, .css, .html", script: "Server.js", }).on("restart", () => console.log("Restarted")); open("http://localhost:2137"); <file_sep>/client/Game.ts import {Componenets} from "./BasicComponents"; import {World} from "./World"; export interface IComponent { Name: Componenets; } export interface ISystem { Process(world: World); }<file_sep>/server/Server.ts /// <reference path="../resources/index.d.ts" /> import {OnConnection} from "./OnConnect"; import express from "express"; import socketio from "socket.io"; import serveStatic from "serve-static"; import * as ServerLoop from "./ServerLoop"; var app = express(); var server = app.listen(2137); export var socketServer = socketio(server); ServerLoop.Start(); app.use(serveStatic("./static", { index: ["index.html"] })); socketServer.on('connection', OnConnection);<file_sep>/resources/index.d.ts declare module "*.png" { const image: string; export default image; } declare module "*.json" { const resources: any; export default resources; } <file_sep>/client/Init.ts /// <reference path="../resources/index.d.ts"/> import {Config} from "../Interchange/DataStructures"; import {RenderingSystem} from "./Systems/RenderingSystem"; import {AnimationSystem} from "./Systems/AnimationSystem"; import {NetworkSystem} from "./Systems/NetworkSystem"; import {UserInterfaceSytem} from "./Systems/UserInterfaceSystem"; import {MovementSystem} from "./Systems/MovementSystem"; import {InputSystem} from "./Systems/InputSystem"; import {CameraSystem} from "./Systems/CameraSystem"; import {GameObj} from "./GameObj"; import {PositionComponent, RenderMapComponent} from "./BasicComponents"; import {World} from "./World"; import {GetFPS, loadImage} from "./Misc"; import SpritesURL from "../resources/sprites.png"; export var config: Config; window.onload = function () { var renderingSystem: RenderingSystem; var cameraSystem = new CameraSystem(); var inputSystem = new InputSystem(); var movemnetSystem = new MovementSystem(); var userInterfaceSystem = new UserInterfaceSytem(); var networkSystem = new NetworkSystem(); var characterAnimationSystem = new AnimationSystem(); var world = new World(); const configPromise = import("../resources/data.json"); const spritePromise = loadImage(SpritesURL); Promise.all([configPromise, spritePromise]) .then(([configData, sprites]) => { config = configData.default as Config; const canvas = <HTMLCanvasElement>document.getElementById("GameCanvas"); renderingSystem = new RenderingSystem(canvas, sprites); var map = new GameObj(); map.ID = 1541515125; map.AddComponent(new PositionComponent(0, 0)); map.AddComponent(new RenderMapComponent(config.Data, config.MapWidth, config.MapHeight)); world.Add(map); networkSystem.connect(); requestAnimationFrame(Loop); }); function Loop() { world.FPS = GetFPS(); inputSystem.Process(world); //collisionSystem.Process(world); characterAnimationSystem.Process(world); movemnetSystem.Process(world); cameraSystem.Process(world); networkSystem.Process(world); userInterfaceSystem.Process(world); renderingSystem.Process(world); renderingSystem.RenderAll(cameraSystem.GetCamerasList()); world.ClearEvets(); requestAnimationFrame(Loop); } } <file_sep>/server/OnConnect.ts import {Player} from "./classes/Player"; import {characterList} from "./GameState"; import {socketServer} from "./Server"; import {MoveData} from "../Interchange/DataStructures"; export function OnConnection(socket: SocketIO.Socket) { var plr = new Player(socket); plr.Sync(); socket.emit("NewCharacters", characterList.GetAllSyncData()); plr.SelfAnnouce(); socket.on("PlayerMove", function (data: MoveData) { plr.Move(data); }); socket.on("PlayerMessage", function (data: { Msg: string }) { console.log(data.Msg); socketServer.sockets.emit("CharacterMessage", { Msg: data.Msg, ID: socket.id }); }); socket.on("PlayerTarget", function (data: { ID; IsTargeting: boolean }) { var plr = characterList.GetByID(socket.id); if (plr) { if (data.IsTargeting) { var targetChar = characterList.GetByID(data.ID); if (!targetChar) return; plr.Target(targetChar); } else { plr.Untarget(); } } }); socket.on("disconnect", () => { var char = characterList.RemoveByID(socket.id); if (char) { char.Dispose(); console.log("DISPOSED", socket.id); } }); characterList.AddNewPlayer(plr); } <file_sep>/README.md # TibiaJS ### Requirements * Node 8+ ### How to run * `git clone https://github.com/RemoveIt/TibiaJS.git` * `cd TibiaJS` * `npm install` * `npm run build` * `npm run run` or `cd out/` & `node Server.js` <file_sep>/server/classes/Mob.ts import "../../Interchange/DataStructures"; import {Character, CharacterDataToSync} from "./Character"; import {config, ground} from "../GameState"; import {socketServer} from "../Server"; import {GetDistance} from "../Geometry"; import {Vector2D, MoveData, Rotation} from "../../Interchange/DataStructures"; var startSprites = ["Orc", "Minotaur", "Troll", "Dwarf"]; export class Mob implements Character { private syncData = new CharacterDataToSync(startSprites[(Math.random() * 4) | 0]); private lastMoveTime = 0; private moveDelay = 35000 / this.syncData.Speed; private LastAttackTime = 0; private AttackDelay = 850; private targetChar: Character; // private IsDead = false; constructor(pos: Vector2D) { this.syncData.Position = pos; } Move(data: MoveData) { if (!this.CanMove()) return; ground.FreeCollision(this.syncData.Position.x, this.syncData.Position.y); this.syncData.Position.x = data.Pos.x; this.syncData.Position.y = data.Pos.y; ground.SetCollision(this.syncData.Position.x, this.syncData.Position.y); socketServer.emit("CharacterMove", { ID: this.syncData.ID, Data: data }); this.lastMoveTime = Date.now(); } MoveDir(rot: Rotation) { var tmpPos = { x: this.syncData.Position.x, y: this.syncData.Position.y }; if (rot === Rotation.Left) { tmpPos.x--; } if (rot === Rotation.Top) { tmpPos.y--; } if (rot === Rotation.Right) { tmpPos.x++; } if (rot === Rotation.Down) { tmpPos.y++; } var data = { Rot: rot, Pos: tmpPos }; this.Move(data); } GetJSON() { return this.syncData.toJSON(); } GetID(): string { return this.syncData.ID; } Dispose() { socketServer.emit("DeleteCharacters", [this.syncData.ID]); ground.FreeCollision(this.syncData.Position.x, this.syncData.Position.y); } SelfAnnouce() { socketServer.emit("NewCharacters", [this.GetJSON()]); ground.SetCollision(this.syncData.Position.x, this.syncData.Position.y); } Target(char: Character) { this.targetChar = char; } Untarget() { this.targetChar = null; } GetHP(): number { return this.syncData.HP; } AttackTarget() { if (!this.targetChar) return; if (this.targetChar.GetHP() < 0) { this.Untarget(); return; } if (!this.CanAttack()) return; var dist = GetDistance(this.syncData.Position, this.targetChar.GetJSON().Position); if (dist > 1.5) return; var dmg = Math.random() * 5 | 0 + 1; this.targetChar.Hit(dmg); this.LastAttackTime = Date.now(); } Hit(dmg: number): { Exp: number } { socketServer.sockets.emit("ApplyDommage", { AttackType: 0, TargetID: this.syncData.ID, HitPoints: dmg }); this.syncData.HP -= dmg; if (this.syncData.HP < 0) { this.Kill(); return { Exp: this.syncData.ExpAtDead }; } } Kill() { this.Dispose(); socketServer.sockets.emit("Animation", { Sprites: config.Mobs[this.GetJSON().Race].DeadSprites, Pos: this.syncData.Position, TicksPerFrame: 100 }); } IsDead() { return this.syncData.HP < 0; } MoveByVector(desiredMoveV: Vector2D) { if (!this.CanMove()) return; var dataArr = new Array<any>(4); var radians = Math.atan2(desiredMoveV.y, desiredMoveV.x); dataArr[Rotation.Left] = ({ can: ground.GetCollision(this.syncData.Position.x - 1, this.syncData.Position.y), desire: Math.cos(radians) }); dataArr[Rotation.Down] = ({ can: ground.GetCollision(this.syncData.Position.x, this.syncData.Position.y + 1), desire: Math.cos(radians + (Math.PI / 2)) }); dataArr[Rotation.Right] = ({ can: ground.GetCollision(this.syncData.Position.x + 1, this.syncData.Position.y), desire: Math.cos(radians + Math.PI) }); dataArr[Rotation.Top] = ({ can: ground.GetCollision(this.syncData.Position.x, this.syncData.Position.y - 1), desire: Math.cos(radians + (Math.PI / 2 * 3)) }); var mostdesire = -1; var result = -1; for (var i = 0; i < 4; i++) { if (!dataArr[i].can && dataArr[i].desire > -0.1) { if (dataArr[i].desire > mostdesire) { result = i; mostdesire = dataArr[i].desire; } } } if (result !== -1) { this.MoveDir(result); } } IdleMoving() { if (!this.CanMove()) return; if (Math.random() > 0.95) { this.MoveByVector({ x: Math.sin(Math.random() * Math.PI * 2), y: Math.sin(Math.random() * Math.PI * 2) }); } } CanMove() { return ((Date.now() - this.lastMoveTime) > this.moveDelay) && !this.IsDead(); } CanAttack() { return ((Date.now() - this.LastAttackTime) > this.AttackDelay) && !this.IsDead(); } } <file_sep>/client/Misc.ts import {Vector2D} from "../Interchange/DataStructures"; export function GET(path: string, fn: (err, res) => void) { var req = new XMLHttpRequest(); req.open("GET", path, true); req.send(); req.onreadystatechange = function () { if (req.readyState == 4 && req.status == 200) { fn(null, req.responseText); } else if (req.readyState == 4) { var err = req.response; fn(err, ""); } } } var _lastmeasure = Date.now(); export function GetFPS(): number { var curmeasure = Date.now(); var delta = curmeasure - _lastmeasure; _lastmeasure = curmeasure; return 1000.0 / delta; } export function GetDistance(p1: Vector2D, p2: Vector2D): number { var vx = p1.x - p2.x; var vy = p1.y - p2.y; return Math.sqrt((vx * vx) + (vy * vy)); } export function loadImage(src): Promise<HTMLImageElement> { return new Promise((resolve) => { const image = new Image(); image.src = src; image.onload = () => resolve(image); }) } <file_sep>/server/classes/Spawn.ts import {Mob} from "./Mob"; import {characterList, config} from "../GameState"; import {Player} from "./Player"; import {GetDistance} from "../Geometry"; import {Vector2D} from "../../Interchange/DataStructures"; export class Spawn { private mobList = new Array<Mob>(); private pos: Vector2D; private desiredMobCount = 0; private newList = new Array<number>(); constructor(posX: number, posY: number) { this.pos = {x: posX, y: posY}; } MaintainMobCount(count: number) { this.desiredMobCount = count; } Process() { if (this.mobList.length + this.newList.length < this.desiredMobCount) { this.newList.push(Date.now()); } if (this.newList.length > 0) { if ((this.newList[0] + config.MobSpawnDelay) < Date.now()) { this.addNew(); this.newList.splice(0, 1); } } for (var i = 0; i < this.mobList.length; i++) { if (this.mobList[i].IsDead()) { characterList.RemoveByID(this.mobList[i].GetID()); this.mobList.splice(i, 1); i--; continue; } var nearestPlr = this.getNearestPlayer(this.mobList[i]); if (!nearestPlr) return; var plrPos = nearestPlr.GetJSON().Position; var mobPos = this.mobList[i].GetJSON().Position; var dist = GetDistance(mobPos, plrPos); this.mobList[i].Target(nearestPlr); this.mobList[i].AttackTarget(); if (dist < 7 && dist > 1.5) { this.mobList[i].MoveByVector({x: mobPos.x - plrPos.x, y: mobPos.y - plrPos.y}); } if (dist >= 7) { this.mobList[i].IdleMoving(); } } } private addNew() { var char = new Mob({ x: ((Math.random() - 0.5) * 4 + this.pos.x) | 0, y: ((Math.random() - 0.5) * 4 + this.pos.y) | 0 }); char.SelfAnnouce(); characterList.AddNewMob(char); this.mobList.push(char); } private getNearestPlayer(mob: Mob) { var lastDist = 1000000; var selectedPlayer: Player; characterList.ForEachPlayer((plr) => { var tmpDist = GetDistance(plr.GetJSON().Position, mob.GetJSON().Position) if (tmpDist < lastDist) { lastDist = tmpDist; selectedPlayer = plr; } }); return selectedPlayer; } } <file_sep>/server/ServerLoop.ts import * as GameState from "./GameState"; import {Spawn} from "./classes/Spawn"; import {characterList} from "./GameState"; var intervalHandle: NodeJS.Timer; var spawnList = new Array<Spawn>(); export function Start() { intervalHandle = setInterval(NewLoop, 50); for (var i = 0; i < GameState.config.MobSpawns.length; i++) { spawnList.push(new Spawn(GameState.config.MobSpawns[i].Position.x, GameState.config.MobSpawns[i].Position.y)); spawnList[i].MaintainMobCount(GameState.config.MobSpawns[i].Count); } } export function Stop() { if (intervalHandle) clearInterval(intervalHandle); } function NewLoop() { characterList.ForEachPlayer((plr) => { plr.AttackTarget(); if (plr.IsDead()) { characterList.RemoveByID(plr.GetID()); } }); for (var i = 0; i < spawnList.length; i++) { spawnList[i].Process(); } } <file_sep>/server/GameState.ts import {CharacterList} from "./classes/CharacterList"; import {Ground} from "./classes/Ground"; import data from "../resources/data.json"; import {Config} from "../Interchange/DataStructures"; export const config: Config = data; export const characterList = new CharacterList(); export const ground = new Ground();
4f95d5e38b1e63a7fc44e87ce04342a77e693e85
[ "JavaScript", "TypeScript", "Markdown" ]
12
JavaScript
dkasyan/TibiaJS
79c82813930cf89a9a65b0d2a216789554c4add0
6052d17ae619d32a57a0bec8d18b782b2b2782e1
refs/heads/master
<repo_name>zhongmingX/sf-api<file_sep>/modules/member/controllers/ExtractsController.php <?php namespace app\modules\member\controllers; use \Yii; use api\controllers\BaseController; use common\components\CommonFun; use common\models\MembersExtracts; use common\models\MembersFinances; use common\models\Members; use common\models\MembersBanks; use common\components\Notice; use api\controllers\MemberBaseController; class ExtractsController extends MemberBaseController{ public function actionList(){ $query = MembersExtracts::find(); $query->where = [ 'member_id' => $this->member_id, ]; $query->orderBy('ctime desc'); $count = $query->count('id'); $query->limit($this->pageSize)->offset($this->offset); $data = $query->asArray()->all(); return CommonFun::returnSuccess(['total' => $count,'list' => $data,'page_size' => $this->pageSize,'page_num' => ++$this->pageNum]); } public function actionWithdraw(){ if($this->isPost){ $userInfo = Members::getFinances($this->member_id); $amount = floatval(Yii::$app->request->post('amount',0)); if($amount <= 0){ return CommonFun::returnFalse("请输入提现金额"); } if($amount < 1){ return CommonFun::returnFalse("提现最少金额为1元"); } if($userInfo['balance'] < $amount){ $userInfo['balance'] = CommonFun::formatMoney($userInfo['balance']); return CommonFun::returnFalse("提现金额:{$amount}不能大于您的余额:{$userInfo['balance']}"); } $today = date('Y-m-d'); $startTime = strtotime($today.' 00:00:00'); $endTime = strtotime($today.' 23:59:59'); $query = MembersExtracts::find()->where(['member_id' => $this->member_id]); $query->andWhere(['>','ctime',$startTime]); $query->andWhere(['<','ctime',$endTime]); // $total = $query->count('id'); // if($total >= 3){ // return CommonFun::returnFalse("您今日提现次数超限。"); // } $password = Yii::$app->request->post('password',''); $info = Members::findOne(['id'=>$this->member_id]); $tmp = CommonFun::md5($password.$info->salt, 'member-txpass'); if($info['txpass'] != $tmp){ return CommonFun::returnFalse("对不起,您的提现密码错误。"); } $bank_id = intval(Yii::$app->request->post('bank_id',0)); $info = MembersBanks::findOne(['id' => $bank_id,'member_id' => $this->member_id]); if(empty($info)){ return CommonFun::returnFalse("银行ID对应的数据获取失败。"); } $userInfo->extract_freeze = CommonFun::doNumber($userInfo->extract_freeze,$amount,'+'); $userInfo->balance = CommonFun::doNumber($userInfo['balance'],$amount,'-'); $res = $userInfo->save(); if($userInfo->balance >= 0 && !$res){ return CommonFun::returnFalse('操作失败,请稍候再试。'. json_encode($userInfo->getErrors(),JSON_UNESCAPED_UNICODE)); } $model = new MembersExtracts(); $model->member_id = $this->member_id; $model->bank_account = $info['account']; $model->bank_name = $info['bank_name']; $model->account_name = $info['account_name']; $model->bank_deposit = $info['bank_deposit']; $model->amount = $amount; $model->member_oper_mobile = $this->member_id; $res = $model->save(); if(!$res){ return CommonFun::returnFalse('操作失败,请稍候再试。'. json_encode($model->getErrors(),JSON_UNESCAPED_UNICODE)); } $model = new MembersExtracts(); $model->afterSubmit($model->id); //给财务发消息 Notice::submitManager('financial', '会员ID:'.$this->member_id.'发起提现申请,请及时处理!'); return CommonFun::returnSuccess(); } } }<file_sep>/modules/activity/controllers/LuckydrawController.php <?php namespace app\modules\activity\controllers; use common\components\CommonFun; Use api\controllers\BaseController; use common\models\LuckydrawProducts; use common\models\MembersCurrency; use common\models\MembersFinances; use common\models\MembersLuckydrawAddress; use common\models\MembersLuckydraws; use common\models\MembersAddress; use common\models\MiniTemplateinfo; use api\controllers\MemberBaseController; /** * Default controller for the `activity` module */ class LuckydrawController extends MemberBaseController { /** * Renders the index view for the module * @return string * * $type 1当期 2下期 3往期 */ public function actionIndex($type = 1) { $orderby = CommonFun::getParams('order', 'coin desc'); if(strripos($orderby, ' desc') === false && strripos($orderby, ' asc') === false){ $orderby = $orderby . ' desc'; } //在当前时间范围内属本期 大于当前时间属下期 $query = LuckydrawProducts::find() ->select('id,product_name,product_desc,product_images,coin,min_people,max_people,start_ctime,end_ctime,status') ->where('active=1'); switch ($type){ case 1: // $query->andWhere(['<=', 'start_ctime', date('Y-m-d H:i:s', time())]); // $query->andWhere(['>=', 'end_ctime', date('Y-m-d H:i:s', time())]); $query->andWhere(['in', 'status', [1,2]]); break; case 2: // $query->andWhere(['>', 'start_ctime', date('Y-m-d H:i:s', time())]); $query->andWhere(['=', 'status', 0]); break; default: // $query->andWhere(['<', 'end_ctime', date('Y-m-d H:i:s', time())]); $query->andWhere(['in', 'status', [8,9]]); break; } $model = $query->orderBy($orderby) ->asArray() ->all(); $data = []; if($model){ foreach($model as $k=>$v){ $data[$k] = $v; //查询当前抽奖人数 $data[$k]['people_num'] = LuckydrawProducts::getNumber($v['id']); $data[$k]['start_ctime'] = date('Y-m-d H:i', strtotime($v['start_ctime'])); $data[$k]['end_ctime'] = date('Y-m-d H:i', strtotime($v['end_ctime'])); $data[$k]['winner'] = ''; if($v['status'] == 9){ //正常结束,找出中奖人 $data[$k]['winner'] = MembersLuckydraws::getWinner($v['id']); } } } CommonFun::returnSuccess($data); } //商品详情 public function actionView($id){ $model = LuckydrawProducts::findOne($id); if(!$model){ return CommonFun::returnFalse('数据错误'); } $data = $model->attributes; // $member = MembersLuckydraws::find() ->where('member_id=:mid and product_id=:pid', [':pid'=>$id, ':mid'=>$this->member_id]) ->one(); unset($data['version']); unset($data['ctime']); unset($data['active']); $data['member'] = ''; if($member){ $data['member'] = $member->attributes; } return CommonFun::returnSuccess($data); } //抽奖参与列表 public function actionGetLists($id){ $data = []; $model = MembersLuckydraws::find() ->where('product_id=:pid',[':pid'=>$id]) ->orderBy('ctime desc') ->all(); if($model){ foreach($model as $k=>$v){ $data[$k]['uid'] = substr_replace($v['member_id'], '****', 2, 3);; $data[$k]['datestr'] = date("Y-m-d H:i:s", $v['ctime']); $data[$k]['statusText'] = MembersLuckydraws::$STATUS[$v['status']]; } } return CommonFun::returnSuccess($data); } //开始抽奖 public function actionDo(){ if($this->isPost){ $pid = \Yii::$app->request->post('pid'); $model = LuckydrawProducts::findOne($pid); $res = []; if(!$model){ return CommonFun::returnFalse('数据错误'); } //判断活动有没有开启 if($model->status == LuckydrawProducts::STATUS_NOSTART){ $res['status'] = 0; $res['msg'] = '该活动还未开始'; }else if($model->status == LuckydrawProducts::STATUS_OPEN){ $res['status'] = 0; $res['msg'] = '抽奖中'; }else if($model->status == LuckydrawProducts::STATUS_END){ $res['status'] = 0; $res['msg'] = '活动已经结束'; }else if($model->status == LuckydrawProducts::STATUS_NOTNUMBER){ $res['status'] = 0; $res['msg'] = '抽奖人数不足, 结束'; }else if($model->status == LuckydrawProducts::STATUS_START){ if($model->max_people > 0){ $num = LuckydrawProducts::getNumber($pid); if($num >= $model->max_people){ $res['status'] = 0; $res['msg'] = '已经达到参与上限'; return CommonFun::returnSuccess($res); } } $data = MembersLuckydraws::find() ->where('member_id=:mid and product_id=:pid', [':pid'=>$pid, ':mid'=>$this->member_id]) ->one(); if($data){ $res['status'] = 0; $res['msg'] = '该活动已经参与'; }else{ //判断省币是否够 $finance = MembersFinances::findOne(['member_id'=>$this->member_id]); $coin = CommonFun::doNumber($finance->coin); if($coin < $model->coin){ return CommonFun::returnFalse('省币不足'); } //冻结省币 MembersFinances::coinFreeze($this->member_id, $model->coin, MembersCurrency::SOURCE_LUCKDRAW_FREEZE); $data = new MembersLuckydraws(); $data->member_id = $this->member_id; $data->product_id = $pid; $data->coin = $model->coin; $data->taxrate = $model->taxrate; $data->ctime = time(); $data->status = 1; if($data->save()){ $res['status'] = 1; $res['msg'] = '参加抽奖活动成功'; } //记录用户提交FORMID if($this->api_source == 'miniprogram'){ $formid = \Yii::$app->request->post('formid'); if($formid){ $mini = new MiniTemplateinfo(); $mini->type = MiniTemplateinfo::TYPE_LUCKYDRAW; $mini->obj_id = 'luckydraw_'.$pid; $mini->member_id = $this->member_id; $mini->form_id = $formid; $mini->ctime = time(); $mini->is_send = 0; $mini->send_time = 0; $mini->openid = $this->openid; $mini->save(); } } } }else{ $res['status'] = 0; $res['msg'] = '活动状态错误'; } return CommonFun::returnSuccess($res); } } //获取我的抽奖记录 public function actionRecord(){ $data = []; $model = MembersLuckydraws::find() ->where('member_id=:mid', [':mid'=>$this->member_id]) ->with(['product', 'address']) ->orderBy('ctime desc') ->asArray() ->all(); if($model){ foreach ($model as $k=>$v){ $data[$k]['id'] = $v['id']; $data[$k]['product_id'] = $v['product_id']; $data[$k]['date'] = date('Y-m-d H:i:s', $v['ctime']); $data[$k]['status'] = $v['status']; $data[$k]['product_name'] = $v['product']['product_name']; $data[$k]['product_image'] = ''; if($v['product']['product_images']){ $tmp = explode(',', $v['product']['product_images']); $data[$k]['product_image'] = $tmp[0]; } $data[$k]['product_coin'] = $v['product']['coin']; $data[$k]['address'] = $v['address']; } } return CommonFun::returnSuccess($data); } //设置收货地址 public function actionSettingAddress(){ if($this->isPost) { $id = \Yii::$app->request->post('id'); //取默认收货地址 $address = MembersAddress::getDefaultAddress($this->member_id); if(!$address){ return CommonFun::returnFalse('未找到默认地址'); } $model = MembersLuckydrawAddress::findOne(['ml_id'=>$id]); if(!$model){ $model = new MembersLuckydrawAddress(); } $model->ml_id = $id; $model->member_id = $this->member_id; $model->name = $address['name']; $model->mobile = $address['mobile']; $model->area = $address['area']; $model->address = $address['address']; $model->status = 1; if($model->save()){ return CommonFun::returnSuccess(); } return CommonFun::returnFalse('系统错误'); } } } <file_sep>/modules/exchange/controllers/CategoryController.php <?php namespace app\modules\exchange\controllers; use api\controllers\BaseController; use common\models\Category; use common\components\CommonFun; use common\models\Brand; /** * Default controller for the `local` module */ class CategoryController extends BaseController { public function actionIndex(){ // $cityid = $this->city_id; $cityid = 0; $model = Category::getCategoryByCity(Category::TYPE_PRODUCT, $cityid); return CommonFun::returnSuccess($model); } public function actionBrand(){ $data = Brand::getAll(); return CommonFun::returnSuccess($data); } } <file_sep>/modules/exchange/controllers/PointController.php <?php namespace app\modules\exchange\controllers; use api\controllers\BaseController; use common\components\enum\OrderEnum; use common\extend\OSS\Common; use common\models\Category; use common\components\CommonFun; use common\components\CommonGeoLocal; use common\models\ExchangePoint; use common\models\CommonModel; use common\models\ExchangePointProduct; use common\models\ExchangePorintSetting; use common\models\ExchangeProduct; use common\models\MembersFavorite; use common\models\OpenCity; use common\models\Orders; /** * Default controller for the `local` module */ class PointController extends BaseController { /** * 获取附近兑换点 * @param number $distance */ public function actionIndex(){ $lat = $this->lat; $lng = $this->lon; if(!$lat || !$lng){ return CommonFun::returnFalse('当前未定位'); } $distance = CommonFun::getParams('distance', 0); //距离 $sql = "SELECT a.id, a.name,a.address, a.lat, a.lon, a.img, ROUND(6378.138*2*ASIN(SQRT(POW(SIN((".$lat."*PI()/180-lat*PI()/180)/2),2)+COS(".$lat."*PI()/180)*COS(lat*PI()/180)*POW(SIN((".$lng."*PI()/180-lon*PI()/180)/2),2)))*1000) AS distance FROM sf_exchange_point a where a.lon <> '' and a.lat <> '' and a.is_online=0 and a.status=1"; if($distance > 0){ $sql .= " having distance <= ".($distance * 1000); } $sql .= " ORDER BY distance asc"; $sql .= " limit ".$this->offset. ','. $this->pageSize; $db = \Yii::$app->db; $query = $db->createCommand($sql); $data = $query->queryAll(); if($data){ foreach($data as $k=>$v){ $data[$k]['product_counts'] = ExchangePointProduct::find()->where(['exchange_point_id'=>$v['id'],'status' => CommonModel::STATUS_ACTIVE])->count('id'); $data[$k]['focus'] = MembersFavorite::getCounts($v['id'],MembersFavorite::TYPE_EXCHANGE); $data[$k]['order_nums'] = Orders::getCount($v['id'], OrderEnum::TYPE_EXCHANGE_OFF); $data[$k]['distance'] = sprintf("%0.2f", $v['distance'] / 1000); } } return CommonFun::returnSuccess([ 'lists' => $data, 'total' => count($data) ]); } /** * 兑换点详情 * @author RTS 2018年4月5日 14:19:41 */ public function actionBasic($id = 0) { $model = ExchangePoint::find()->where(['id' => $id,'status' => CommonModel::STATUS_ACTIVE])->asArray()->one(); if(empty($model)){ return CommonFun::returnFalse('对应的信息不存在'); } $prodcut_counts = ExchangePointProduct::find()->where(['exchange_point_id'=>$id,'status' => CommonModel::STATUS_ACTIVE])->count('id'); $focus = MembersFavorite::getCounts($id,MembersFavorite::TYPE_EXCHANGE); $order_num = Orders::getCount($id, OrderEnum::TYPE_EXCHANGE_OFF); $setting = ExchangePorintSetting::findOne(['id'=>$id]); if($setting){ $setting = $setting->toArray(); } return CommonFun::returnSuccess(['focus' => $focus,'prodcut_counts' => $prodcut_counts, 'order_num'=>$order_num,'info' => $model, 'setting'=>$setting]); } /** * 查询用户在当前兑换点订单情况, 处理限购条件 //TODO 此方法已移至 member 下 CommonController.php * @param $id 兑换点ID */ public function actionMemberLimitOrders($id){ $uid = \Yii::$app->request->headers->get('uid'); $data = ['coin_order'=>0, 'amount_order'=>0]; $setting = ExchangePorintSetting::findOne(['id'=>$id]); if($setting){ $limit_cycle = ($setting['limit_cycle'] != 0)?($setting['limit_cycle']*(60*60*24)):0; if($setting->limit_number != 0){ $order = Orders::find(); $order->where('member_id=:mid and type=:type and order_obj_id=:oid', [':mid' => $uid, ':type'=>OrderEnum::TYPE_EXCHANGE_OFF, ':oid'=>$id]); $order->andWhere(['not in', 'order_status', [8,9]]); // $order->groupBy('product_id'); if($limit_cycle != 0){ $order->andWhere(['>=', 'ctime', time() - $limit_cycle]); } $res = $order->all(); if($res){ foreach($res as $item){ if($item->product_amount == 0){ $data['coin_order'] += 1; }else{ $data['amount_order'] += 1; } } } } return CommonFun::returnSuccess($data); } return CommonFun::returnFalse('系统错误! 请联系客服'); } } <file_sep>/controllers/handler/ErrorHandler.php <?php /** * Created by PhpStorm. * User: zhongming * Date: 2018/2/4 上午10:27 */ namespace api\controllers\handler; use Yii; use yii\base\ErrorHandler as BaseErrorHandler; class ErrorHandler extends BaseErrorHandler { /** * Renders the exception. * @param \Exception $exception the exception to be rendered. */ protected function renderException($exception) { $response = Yii::$app->response; $response->statusText = $exception->getMessage(); if($exception->getCode() == 0){ $response->statusCode = 404; Yii::$app->end(0, $response); }else{ $response->statusCode = 500; Yii::$app->end(0, $response); } } }<file_sep>/modules/member/controllers/FinancesController.php <?php namespace app\modules\member\controllers; /** * Created by PhpStorm. * User: zhongming * Date: 2018/4/7 下午4:15 */ use common\components\CommonValidate; use common\models\MembersBanks; use common\models\MembersCurrency; use common\models\MembersFinances; use common\models\MembersFinancesDetail; use common\models\MerchantsFreezes; use common\models\MoneyAllocateds; use common\models\Orders; use gmars\sms\Sms; use \Yii; use api\controllers\BaseController; use common\components\CommonFun; use common\models\Members; use common\models\Alisms; use common\models\MembersFavorite; use yii\db\Expression; use api\controllers\MemberBaseController; class FinancesController extends MemberBaseController{ //获取用户省币列表 public function actionCurrency(){ $data = []; $query = MembersCurrency::find() ->where(['member_id'=>$this->member_id]); $total = $query->count(); $model = $query->offset($this->offset)->limit($this->pageSize)->orderBy('ctime desc')->all(); if($model){ foreach ($model as $v){ $data[] = [ 'coin' => CommonFun::doNumber($v->coin), 'type' => $v->type, 'date' => date('Y-m-d H:i:s', $v->ctime), 'order_sn' => Orders::getOrderSn($v->order_sn), 'record' => $v->record ]; } } return CommonFun::returnSuccess(['total' => $total, 'page_size'=>$this->pageSize,'page_num' => ++$this->pageNum, 'lists' => $data]); } //获取用户省币 public function actionCurrencyNumber(){ $model = MembersFinances::findOne(['member_id'=>$this->member_id]); $data = [ 'coin'=>CommonFun::doNumber($model->coin), 'coin_freeze'=>CommonFun::doNumber($model->coin_freeze), 'coin_expend'=>CommonFun::doNumber($model->coin_expend) ]; return CommonFun::returnSuccess($data); } //获取用户余额 public function actionBalance(){ $model = MembersFinances::findOne(['member_id'=>$this->member_id]); return CommonFun::returnSuccess(['balance' => CommonFun::doNumber($model->balance),'coin' => CommonFun::doNumber($model->coin)]); } //用户资金明细 public function actionLists(){ $data = []; $category = CommonFun::getParams('category'); $query = MembersFinancesDetail::find()->where(['member_id'=>$this->member_id, 'status'=>MoneyAllocateds::STATUS_ALLOCATED]); if($category){ $tmp = explode(',', $category); $query->andWhere(['in', 'category', $tmp]); } $total = $query->count(); $model = $query->offset($this->offset)->limit($this->pageSize)->orderBy('ctime desc')->all(); if($model){ foreach ($model as $v){ // $record = $v->record; // if($v->category == MembersFinancesDetail::CATEGORY_ORDER){ // $record = $v->item.':'.Orders::getOrderSn($v->category_objid); // } $data[] = [ 'category' => $v->category, 'type' => $v->type, 'amount' => CommonFun::doNumber($v->amount), 'balance' => CommonFun::doNumber($v->balance), 'item' => $v->item, 'order_sn' => ($v->category == MembersFinancesDetail::CATEGORY_ORDER || $v->category == MembersFinancesDetail::CATEGORY_REFUND)?Orders::getOrderSn($v->category_objid):$v->category_objid, // 'record' => , 'date' => date('Y-m-d H:i:s', $v->ctime) ]; } } return CommonFun::returnSuccess(['total' => $total, 'page_size'=>$this->pageSize,'page_num' => ++$this->pageNum, 'lists' => $data]); } }<file_sep>/controllers/ConfigController.php <?php namespace api\controllers; use Yii; use common\components\CommonFun; use yii\web\Controller; use common\models\Config; class ConfigController extends Controller { /** * 基础配置信息 * * @author RTS 2018年4月5日 11:53:02 */ public function actionIndex() { $data = Config::getConfigs('basic'); //配置 return CommonFun::returnSuccess ( [ 'shop_name' => $data ['shop_name'], 'oss_host' => $data ['oss_host'], 'product_warning' => CommonFun::getArrayValue($data,'product_warning',5), 'exchang_warning' => CommonFun::getArrayValue($data,'exchang_warning',5), 'token'=> '<PASSWORD>', 'signin' => Config::getConfigs('signin'), //签到配置 'luckygrid' => Config::getConfigs('luckygrid') //转盘配置 ] ); } } <file_sep>/controllers/DefaultController.php <?php namespace api\controllers; use common\components\CommonFun; use common\models\MembersFinances; use common\models\OssImg; use yii\web\Controller; use common\models\Express; use common\models\OrdersShipping; use abei2017\wx\Application; use common\models\ActivityCard; class DefaultController extends Controller { public function actionIndex(){ $res = ActivityCard::createNumber('33445566'); CommonFun::pp($res); } // public function actionIndex() { // if(isset($_GET['number'])){ // $a = Express::query('中通快递',$_GET['number']); // $res = -1; // if($a !== false){ // $res = OrdersShipping::fill($_GET['number'],$a['data']); // } // CommonFun::pp($res); // /* // $a = Express::poll('中通快递','632758712214'); // CommonFun::pp($a); // */ // // } // // //CommonFun::pp(CommonFun::getTencentLonLatInAddress('104.064566','30.566529')); // // echo CommonFun::url(['/mall/default/index']); // exit; // // return $this->resultData('', 400); // } // public function actionTest(){ // $id = 10492; // $aa = MembersFinances::useRefund($id); // CommonFun::pp($aa); // } // public function actionQrcode(){ // // } public function actionTest() { $reTxt = "感谢您关注: <a href=\"https://weixin.shenglife.cn\" data-miniprogram-appid=\"wxc79ca52b26d4b6d9\" data-miniprogram-path=\"pages/merchant/view/index?id=1003302\">人民食堂</a>"; $reTxt .= "\n如果您需要结账请<a href=\"https://weixin.shenglife.cn\" data-miniprogram-appid=\"wxc79ca52b26d4b6d9\" data-miniprogram-path=\"pages/merchant/payment/index?id=1003302\">点击这里</a>"; $reTxt .= "\n该商家有绑定线下兑换商品服务, 点击后可兑换<a href=\"https://weixin.shenglife.cn\" data-miniprogram-appid=\"wxc79ca52b26d4b6d9\" data-miniprogram-path=\"pages/exchange/offline/index?id=1000007\">精选商品</a>,好货直接带回家!"; \Yii::$app->wechat->sendText('ooS7e0qDCAirKo-HW95-DynB0v_4', $reTxt); exit; $article[] = [ 'title' => '快捷结账: 立即支付得省币'.time(), 'url' => "https://weixin.shenglife.cn/payment/checkOut/11", 'picurl' => 'https://shenglife-shop.oss-cn-hangzhou.aliyuncs.com/2018-10-12/dcdab73d8d1ac6463a6261746c574cae.jpg' ]; $res = \Yii::$app->wechat->sendNews('ooS7e0lpKC7DlszwH1iaB0F2hfLM', $article); CommonFun::pp($res); } } <file_sep>/modules/article/controllers/DefaultController.php <?php namespace app\modules\article\controllers; use api\controllers\BaseController; use common\models\Category; use common\components\CommonFun; use common\models\Article; use common\models\CommonModel; /** * Default controller for the `local` module */ class DefaultController extends BaseController { /** * 分类 * @author RTS 2018年5月18日 10:29:49 */ public function actionCategory(){ $model = Category::getCategoryByCity(Category::TYPE_ARTICLE); return CommonFun::returnSuccess($model); } /** * 列表 * @author RTS 2018年5月18日 10:30:02 */ public function actionList(){ $qurey = Article::find(); $qurey->where(['status'=>CommonModel::STATUS_ACTIVE]); $qurey->filterWhere(['category_id'=>$this->request->get('category_id','')]); $qurey->orderBy('update_time desc'); $count = $qurey->count('id'); $qurey->limit($this->pageSize)->offset($this->offset); $data = $qurey->asArray()->all(); return CommonFun::returnSuccess(['total' => $count,'list' => $data,'page_size' => $this->pageSize,'page_num' => ++$this->pageNum]); } /** * 详情 * @param RTS 2018年5月18日 10:31:00 */ public function actionDetails($id){ $query = Article::find()->where(['id'=>$id]); $model = $query->one(); if(empty($model)){ return CommonFun::returnFalse('获取数据失败。'); } $model->clicks +=1; $model->save(); $data = $query->asArray()->one(); return CommonFun::returnSuccess($data); } } <file_sep>/modules/member/controllers/FavoriteController.php <?php namespace app\modules\member\controllers; /** * Created by PhpStorm. * User: zhongming * Date: 2018/4/3 下午1:42 */ use common\components\CommonValidate; use common\models\MembersBanks; use common\models\MerchantsFreezes; use gmars\sms\Sms; use \Yii; use api\controllers\BaseController; use common\components\CommonFun; use common\models\Members; use common\models\Alisms; use common\models\MembersFavorite; use yii\db\Expression; use api\controllers\MemberBaseController; class FavoriteController extends MemberBaseController{ //用户收藏添加 public function actionCreate(){ if($this->isPost){ $type = Yii::$app->request->post('type'); $obj_id = Yii::$app->request->post('obj_id'); $title = trim(Yii::$app->request->post('title')); if(!in_array($type, MembersFavorite::$TYPE_KEYS)){ CommonFun::returnFalse('type error'); } if($obj_id < 3 || CommonFun::utf8_strlen($title) < 2){ CommonFun::returnFalse('obj_id/title format error'); } //查询是否已经收藏 $m = MembersFavorite::findOne(['member_id'=>$this->member_id, 'obj_id'=>$obj_id, 'type'=>$type]); if($m){ return CommonFun::returnFalse($title.' have favorite'); } $m = new MembersFavorite(); $m->member_id = $this->member_id; $m->type = $type; $m->obj_id = $obj_id; $m->title = $title; $m->ctime = time(); $m->status = 1; $m->save(); if($m->save()){ CommonFun::returnSuccess(); } } CommonFun::returnFalse('favorite create fail'); } //获取收藏LIST public function actionLists($type){ if(!in_array($type, MembersFavorite::$TYPE_KEYS)){ CommonFun::returnFalse('type error'); } $query = $count = MembersFavorite::find() ->select(new Expression("id, type, obj_id, title, from_unixtime(ctime, '%Y-%m-%d') ctime")) ->where('member_id=:mid and type=:type and status = 1', [':mid'=>$this->member_id, ':type'=>$type]); $total = $count->count(); $lists = $query->orderBy('ctime desc')->offset($this->offset)->limit($this->pageSize)->asArray()->all(); return CommonFun::returnSuccess(['total' => $total, 'page_size'=>$this->pageSize,'page_num' => ++$this->pageNum, 'lists' => $lists]); } /** * 删除单条收藏内容 * @throws \Exception * @throws \yii\db\StaleObjectException */ public function actionDelete(){ if($this->isPost){ $id = Yii::$app->request->post('id'); $m = MembersFavorite::findOne(['id'=>$id, 'member_id'=>$this->member_id]); if($m && $m->delete()){ CommonFun::returnSuccess(); } } return CommonFun::returnFalse('favorite delete fail'); } //获取总数 public function actionTotal($type = false){ $m = MembersFavorite::find()->where("member_id=:mid", [':mid'=>$this->member_id]); if($type && in_array($type, MembersFavorite::$TYPE_KEYS)){ $m->andWhere(['=', 'type', $type]); } return CommonFun::returnSuccess(['total'=>$m->count()]); } /** * 查询收藏状 * @author RTS 2018年4月15日 10:39:57 */ public function actionQuery(){ $type = CommonFun::getParams('type',1); $obj_id = CommonFun::getParams('obj_id',1); $res = MembersFavorite::findOne(['type' => $type,'obj_id' => $obj_id,'status' => 1, 'member_id'=>$this->member_id]); $is_favorite = !empty($res); return CommonFun::returnSuccess(['is_favorite' => intval($is_favorite)]); } }<file_sep>/controllers/DocController.php <?php namespace api\controllers; use Yii; use yii\web\Controller; class DocController extends Controller { public $enableCsrfValidation = false; public function init() { } public function actions() { return [ 'index' => [ 'class' => 'light\swagger\RRKDApiAction', 'path' => Yii::getAlias ( '@yml' ) ] ]; } } <file_sep>/modules/local/controllers/CategoryController.php <?php namespace app\modules\local\controllers; use api\controllers\BaseController; use common\models\Category; use common\components\CommonFun; /** * Default controller for the `local` module */ class CategoryController extends BaseController { public function actionIndex($city_id){ $model = Category::getCategoryByCity(Category::TYPE_MERCHANTS_ONOFF, $city_id); return CommonFun::returnSuccess($model); } } <file_sep>/README.md # sf-api 项目接口:给服务号、小程序、后台、商家系统提供接口 <file_sep>/controllers/OauthController.php <?php namespace api\controllers; use common\components\CommonFun; use common\extend\alisdk\AopClient; use common\extend\alisdk\request\AlipaySystemOauthTokenRequest; use common\models\AlipayFans; use common\models\Coupons; use common\models\Members; use common\models\MembersCurrency; use common\models\WeixinFans; use yii\web\Controller; use common\models\MembersFinances; use common\models\Recommends; use common\models\Config; use common\components\CommonValidate; use common\models\Alisms; class OauthController extends Controller { //小程序的授权/ 有验证码登录部分 function actionMiniprogram(){ $mobile = trim(\Yii::$app->request->post('mobile', '')); $vercode = trim(\Yii::$app->request->post('vercode', '')); $code = \Yii::$app->request->post('code'); $data = \Yii::$app->request->post('userdata'); $suid = \Yii::$app->request->post('suid', ''); CommonFun::log(json_encode(\Yii::$app->request->post()), 'mini', 'oauth'); $member = null; if($mobile || $vercode){ if(!CommonValidate::isMobile($mobile)){ return CommonFun::returnFalse('帐号格式错误'); } if(CommonFun::utf8_strlen($vercode) != 6){ return CommonFun::returnFalse('验证码格式错误'); } $cv = new \common\components\SendSms(); if (!$cv->verifyValidate(Alisms::TYPE_LOGIN, (string)$mobile, $vercode)) { return CommonFun::returnFalse('验证码错误'); } //查询帐号是否存在 $member = Members::find() ->where('mobile=:m and status=:s', [':m'=>$mobile, ':s'=>Members::STATUS_NORMAL]) ->one(); } $appid = \Yii::$app->params['wxmini']['app_id']; $appSecret = \Yii::$app->params['wxmini']['secret']; $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code'; $url = str_replace('APPID', $appid, $url); $url = str_replace('SECRET', $appSecret, $url); $url = str_replace('JSCODE', $code, $url); $res = CommonFun::curlGet($url); $res = json_decode($res, true); CommonFun::log($res, 'mini', 'oauth'); if(isset($res['openid'])){ $memberid = 0; //如果是手机号登录成功, if($member){ $memberid = $member->id; } //验证unionid是否存在 if(isset($res['unionid']) && $memberid == 0){ $wxTmp = WeixinFans::getUnionid($res['unionid']); if($wxTmp){ $memberid = $wxTmp->member_id; } } //验证openid是否存在 $wxFans = WeixinFans::getInfo($res['openid']); if($wxFans){ if(!$member){ $memberid = $wxFans->member_id; } if ($wxFans->unionid == ''){ //unionid是否存在 if(isset($res['unionid'])){ $wxFans->unionid = $res['unionid']; $wxFans->save(); } } } //用户不存在时 if(isset($data['nickName'])){ $data['nickname'] = CommonFun::filter_Emoji($data['nickName']); }else{ $data['nickname'] = '微信用户'; } $data['sex'] = isset($data['gender'])?$data['gender']:9; if($memberid == 0){ //看是否有推荐 $is_recommend = false; $recommend_id = 0; if($suid != ''){ $tmp = explode('_', $suid); if((isset($tmp[0]) && in_array($tmp[0], ['member', 'merchants'])) && isset($tmp[1]) && intval($tmp[1]) > 0){ if($tmp[0] == 'member'){ $is_recommend = Recommends::TYPE_MEMBER; }else{ $is_recommend = Recommends::TYPE_MERCHANTS; } $recommend_id = $tmp[1]; } } $memberid = Members::create($data, $is_recommend, $recommend_id); } // else{ // //是否帐号登录 // if($mobile){ // //帐号存在 // $member = Members::findOne($memberid); // if($member->mobile == ''){ // $member->mobile = $mobile; // $member->save(); // } // } // } if(!$wxFans && $memberid > 0){ $data['unionid'] = isset($res['unionid'])?$res['unionid']:''; WeixinFans::create($res['openid'], $memberid, $data, 1); } //当有两个帐号的时候合并 $uid = \Yii::$app->request->headers->get('uid', 0); if($uid > 0 && $uid != $memberid){ $url = \Yii::$app->request->hostInfo.CommonFun::url(['/member/common/account-merge']); $data['from'] = $uid; $data['to'] = $memberid; $data['token'] = CommonFun::md5($uid.$memberid.'<PASSWORD>@'); $ress = CommonFun::curlPost($url, $data, 15, ['uid:'.$uid]); CommonFun::log([$data, $ress], 'merge', 'oauth'); } } unset($res['session_key']); $res['uid'] = $memberid; $res['result'] = Members::getInfo($memberid, 'miniprogram'); return CommonFun::returnSuccess($res); exit; } /** * 支付宝小程序授权 * @param $code */ function actionAlimini(){ $code = \Yii::$app->request->post('code'); // $mobile = trim(\Yii::$app->request->post('mobile', '')); // $vercode = trim(\Yii::$app->request->post('vercode', '')); // // $member = null; // if($mobile || $vercode){ // if(!CommonValidate::isMobile($mobile)){ // return CommonFun::returnFalse('帐号格式错误'); // } // // if(CommonFun::utf8_strlen($vercode) != 6){ // return CommonFun::returnFalse('验证码格式错误'); // } // // $cv = new \common\components\SendSms(); // if (!$cv->verifyValidate(Alisms::TYPE_LOGIN, (string)$mobile, $vercode)) { // return CommonFun::returnFalse('验证码错误'); // } // // //查询帐号是否存在 // $member = Members::find() // ->where('mobile=:m and status=:s', [':m'=>$mobile, ':s'=>Members::STATUS_NORMAL]) // ->one(); // } $c = new AopClient(); $c->rsaPrivateKey = \Yii::$app->params['alimini']['private_key']; $c->alipayrsaPublicKey = \Yii::$app->params['alimini']['public_key']; $c->appId = \Yii::$app->params['alimini']['app_id']; $c->signType = 'RSA2'; $c->format = 'json'; // 获取用户ID $request = new AlipaySystemOauthTokenRequest(); $request->setGrantType('authorization_code'); $request->setCode($code); $res = $c->execute($request); if(isset($res->alipay_system_oauth_token_response->user_id)){ CommonFun::log($res, 'alimini', 'oauth'); $alipay_user_id = $res->alipay_system_oauth_token_response->user_id; $memberid = 0; //查询支付宝帐号 $aliFans = AlipayFans::findOne(['user_id'=>$alipay_user_id]); if($aliFans){ $memberid = $aliFans->member_id; } if($memberid == 0){ $suid = \Yii::$app->request->post('suid', ''); //看是否有推荐 $is_recommend = false; $recommend_id = 0; if($suid != ''){ $tmp = explode('_', $suid); if((isset($tmp[0]) && in_array($tmp[0], ['member', 'merchants'])) && isset($tmp[1]) && intval($tmp[1]) > 0){ if($tmp[0] == 'member'){ $is_recommend = Recommends::TYPE_MEMBER; }else{ $is_recommend = Recommends::TYPE_MERCHANTS; } $recommend_id = $tmp[1]; } } $data['nickname'] = 'alipay'.$alipay_user_id; $memberid = Members::create($data, $is_recommend, $recommend_id); } //查询支付宝帐号 if(!$aliFans){ $aliFans = new AlipayFans(); $aliFans->user_id = $alipay_user_id; $aliFans->member_id = $memberid; $aliFans->ctime = time(); $aliFans->save(); } return CommonFun::returnSuccess(['uid' => $memberid]); }else{ return CommonFun::returnFalse($res->error_response->sub_msg); } } } <file_sep>/controllers/BaseLightController.php <?php namespace api\controllers; use common\components\CommonFun; use common\models\WeixinFans; use Yii; use common\components\CommonValidate; use yii\web\Controller; use common\controllers\RRKDBaseController; //extends \yii\rest\Controller class BaseLightController extends RRKDBaseController { public $layout = false; public $post = null; public $get = null; public $isGet = false; public $isPost = false; public $isAjax = false; public $token = null; public $openid; public $city_id; public $weixin; public $member_id; public $pageSize = 10; public $pageNum = 1; public $offset = 0; public function init() { $this->isAjax = CommonValidate::isAjax(); $this->isPost = CommonValidate::isPost(); $this->isGet = CommonValidate::isGet(); //认证 //$this->token = Yii::$app->request->headers->get('token'); //$this->openid = Yii::$app->request->headers->get('openid'); //认证 $this->token = Yii::$app->request->get('token',''); $this->openid = Yii::$app->request->get('openid',''); if(empty($this->openid) || !$this->weixin = WeixinFans::getInfo($this->openid)){ CommonFun::returnFalse('openid or weixininfo is empty'); } $this->member_id = $this->weixin['member_id']; parent::init(); } } <file_sep>/modules/merchants/controllers/DefaultController.php <?php namespace app\modules\merchants\controllers; use Yii; use api\controllers\BaseController; use common\components\CommonFun; use common\models\Cart; use common\models\MerchantsProduct; use common\models\CommonModel; use common\models\ExchangePointProduct; use common\models\MerchantsProductSku; use common\models\ExchangeProductSku; use common\models\MembersAddress; use common\models\Orders; use common\components\enum\OrderEnum; use callmez\wechat\sdk\mp\Merchant; use common\models\MerchantsAccount; use common\models\ExchangePoint; use common\models\ExchangeProduct; use PetstoreIO\Order; use yii\helpers\ArrayHelper; use common\models\pay\WxPayService; use common\models\Members; use common\models\OrdersPay; use common\models\MembersCurrency; use common\components\FinanceSign; use common\models\OrdersComments; use common\models\MembersFinances; use common\components\SendSms; use common\models\Alisms; use api\controllers\MemberBaseController; class DefaultController extends MemberBaseController { public function beforeAction($action) { parent::beforeAction($action); if ($this->isGet ) { return true; } $outPut = parent::check($action); if ($outPut === true) { return true; } } /** * 发送校验短信 * @author RTS 2018年5月3日 10:27:18 */ public function actionSendSms() { $account = $this->request->post('account',''); $info = MerchantsAccount::findOne(['account' => $account]); if(empty($info)){ return CommonFun::returnFalse('商户帐号:'.$account.'错误,请稍候再试。'); } $sms = new SendSms(true); $res = $sms->verifyCode(Alisms::TYPE_BIND_MERCHANTS, $account); if($res !== true){ return CommonFun::returnFalse('发送失败,请稍候再试。'); } return CommonFun::returnSuccess(); } /** * 绑定操作 * @author RTS 2018年5月3日 10:46:06 */ public function actionBind() { $account = $this->request->post('account',''); $info = MerchantsAccount::findOne(['account' => $account]); if(empty($info)){ return CommonFun::returnFalse('商户帐号:'.$account.'错误,请稍候再试。'); } $verify_code = $this->request->post('verify_code',''); $sms = new SendSms(true); $res = $sms->verifyValidate(Alisms::TYPE_BIND_MERCHANTS, $account, $verify_code); if($res !== true){ return CommonFun::returnFalse('验证码错误,请稍候再试。'); } $user = Members::findOne($this->member_id); $user->merchants_id = $info['id']; $res = $user->save(); if($res){ return CommonFun::returnSuccess(['merchants_id' => $user->merchants_id]); } return CommonFun::returnFalse('操作失败,请稍候再试。'); } } <file_sep>/modules/member/controllers/CardController.php <?php namespace app\modules\member\controllers; use common\components\CommonValidate; use \Yii; use common\components\CommonFun; use common\models\ActivityShare; use api\controllers\BaseController; use common\models\CommonModel; use api\controllers\MemberBaseController; use common\models\ActivityCard; use common\models\Members; use common\models\ActivityShareRecord; use common\models\MembersFinances; use common\models\WeixinFans; use common\models\MembersCurrency; class CardController extends MemberBaseController{ /** * 卡包列表 * @return unknown */ public function actionList($card_status = -1){ $card_status = strval($card_status); $where = ['member_id' => $this->member_id]; if($card_status != -1){ if(strpos($card_status, ',') !== false){ $card_status = explode(',', $card_status); } $where['card_status'] = $card_status; } $lists = ActivityCard::getList($where,$this->pageInfo,'id desc',false,['id','object_id','name','card_status','used_time','expire_time','original_price','code','object_coin']); return CommonFun::returnSuccess(['rows' => $lists['data'],'counts' => $lists['count']]); } /** * 卡包详情 * @return unknown */ public function actionDetails($id = 0){ $res = ActivityCard::getOne(['member_id' => $this->member_id,'id' => $id],true,['records']); if($res){ $res['end_time_seconds'] = 0; if($res['card_status'] == ActivityCard::STATUS_DOING){ $res['end_time_seconds'] = strtotime($res['end_time']) - time(); } } return CommonFun::returnSuccess($res); } /** * 获取助力状态 * @param array $info * @return number[]|string[] */ private function getHelpStatus($info = []){ $status = [ 'status' => 0, 'msg' => '', ]; if($info['member_id'] == $this->member_id){ $status['msg'] = '自己不能给自己助力哟'; return $status; } if($info['card_status'] == ActivityCard::STATUS_WAITING){ $status['msg'] = '已经不需要助力啦,好友省币已经够啦,快去通知好友领取吧'; return $status; } if($info['card_status'] != ActivityCard::STATUS_DOING){ $status['msg'] = '助力状态:'.ActivityCard::getStatusTxt($info['card_status']).'不允许再助力啦'; return $status; } if(time() > strtotime($info['end_time'])){ $status['msg'] = '已经不在助力时间范围内,下次早点来吧'; return $status; } $res = ActivityShareRecord::getOne(['activity_id' => $info['object_id'],'card_id' => $info['id'],'member_id' => $this->member_id]); if(!empty($res)){ $status['msg'] = '您挺热心的,您已经助力过一次啦'; return $status; } $status['status'] = 1; return $status; } /** * 反查卡包详情 * @return unknown */ public function actionDetailsByObjectId($id = 0,$card_id = 0,$member_id = 0){ if(empty($card_id)){//通过活动ID+会员ID反查助力单最后一条手动助力单 $res = ActivityCard::getOne(['object_id' => $id,'member_id' => $member_id, 'type' => 2,'card_status' => ActivityCard::STATUS_AGO],true,['records']); }else{ $res = ActivityCard::getOne(['object_id' => $id,'id' => $card_id],true,['records']); } if(empty($res)){ return CommonFun::returnFalse('数据不存在'); } $tmp = $this->getHelpStatus($res); $res['help_status'] = $tmp; $fans = WeixinFans::findOne(['member_id' => $res['member_id']]); $memberInfo['header_img'] = CommonFun::getArrayValue($fans,'headimgurl',''); $memberInfo['nick_name'] = CommonFun::getArrayValue($fans,'nickname','热心省友'); $tmp = Members::getFinances($res['member_id']); $memberInfo['coin'] = $tmp['coin']; $res['member_info'] = $memberInfo; $tmp = ActivityShare::getOne(['id' => $id]); $res['total_coin'] = $tmp['total_coin']; return CommonFun::returnSuccess($res); } private function getActivity($id = 0){ $res = ActivityShare::status($id,$data); if($res['status'] == 0){ return CommonFun::returnFalse($res['msg']); } return $data; } /** * 兑换 * @return unknown */ public function actionExchange(){ $id = intval($this->request->post('id',0)); $activity = $this->getActivity($id); $total_coin = $activity['total_coin']; $userInfo = Members::getFinances($this->member_id); if($userInfo['coin'] < $total_coin){ return CommonFun::returnFalse('您的省币不足,邀请好友助力吧'); } $now = date('Y-m-d H:i:s'); $model = ActivityCard::getOne(['object_id' => $id,'member_id' => $this->member_id,'type' => 2]); $trans = Yii::$app->db->beginTransaction(); $rd = CommonFun::randStr(6,'NUMBER'); if($model && in_array($model['card_status'], [ActivityCard::STATUS_DOING,ActivityCard::STATUS_WAITING])){//进行中的助力 则直接结束+扣币 try { $model['card_status'] = ActivityCard::STATUS_UNUSE; $model->remark = '助力方式'; $model->receive_time = $now; $model->expire_time = $activity['end_time']; $model->code = ActivityCard::createNumber($id.$rd.$model->id); $activity->receive_counts = $activity->receive_counts + 1; $res = $activity->save() && $model->save(); if($res == false){ throw new \Exception('变更状态失败'); } $res = MembersCurrency::record($this->member_id,MembersCurrency::TYPE_REDUCE,MembersCurrency::SOURCE_SHARE_EXCHANGE,$model->code,$total_coin); CommonFun::log($this->member_id.'兑换:'.$id.'活动,消耗币:'.$total_coin,__FUNCTION__,'MembersFinances'); if($res == false){ throw new \Exception('更新省币失败'); } $trans->commit(); return CommonFun::returnSuccess(); } catch (\Exception $e) { $trans->rollBack(); return CommonFun::returnFalse('兑换失败,请稍后再试:'.$e->getMessage()); } } $res = ActivityCard::buyedCount($id,$this->member_id); if($res >= $activity['limit']){ return CommonFun::returnFalse('活动限购:'.$activity['limit'].'份'); } try {//直接兑换 $model = new ActivityCard(); $model->member_id = $this->member_id; $model->object_id = $id; $model->name = $activity['name']; $model->remark = '直接购买'; $model->card_status = ActivityCard::STATUS_UNUSE; $model->merchant_id = $activity['merchant_id']; $model->receive_time = $now; $model->expire_time = $activity['end_time']; $model->original_price = $activity['original_price']; $model->object_coin = $activity['total_coin']; $activity->receive_counts = $activity->receive_counts + 1; $res = $activity->save() && $model->save(); if($res == false){ throw new \Exception('兑换失败,'.__LINE__.json_encode($activity->getErrors().json_encode($model->getErrors(),JSON_UNESCAPED_UNICODE))); } $model->code = $model::createNumber($id.$rd.$model->id); $model->save(); $res = MembersCurrency::record($this->member_id,MembersCurrency::TYPE_REDUCE,MembersCurrency::SOURCE_SHARE_EXCHANGE,$model->code,$total_coin); if($res !== true){ throw new \Exception('更新省币失败,'.$res); } CommonFun::log($this->member_id.'兑换:'.$id.'活动,消耗币:'.$total_coin,__FUNCTION__,'MembersFinances'); $trans->commit(); return CommonFun::returnSuccess(); } catch (\Exception $e) { $trans->rollBack(); return CommonFun::returnFalse('兑换失败,请稍后再试:'.$e->getMessage()); } } /** * 去助力【点击助力按钮】 * @author RTS 2018-11-9 16:18:18 * @return json */ public function actionToHelp(){ $id = intval($this->request->post('id',0));//活动id $activity = $this->getActivity($id); $card_id = intval($this->request->post('card_id',0));//卡劵id $info = ActivityCard::getOne(['object_id' => $id,'id' => $card_id,'type' => 2]); if(empty($info)){ return CommonFun::returnFalse('数据不存在'); } $senderId = $info['member_id'];//发起人 $tmp = $this->getHelpStatus($info); if($tmp['status'] == 0){ return CommonFun::returnFalse($tmp['msg']); } $sendInfo = Members::getFinances($senderId); if($sendInfo['coin'] >= $activity['total_coin']){//省币够了则直接等待领取 $info['card_status'] = ActivityCard::STATUS_UNUSE; $res = $info->save(); } $res = ActivityShareRecord::getOne(['activity_id' => $id,'card_id' => $card_id,'member_id' => $this->member_id]); if(!empty($res)){ return CommonFun::returnFalse('您挺热心的,您已经助力过一次啦'); } //记录助力记录 更新劵上面累计的币 更新发起人发起人发起人【非当前登录】的币 还看助力后 是否已经够了 够了变更为待领取 推送消息叫起领取 $senderId = $info['member_id'];//发起人 $share_coin = $activity['share_coin'];//助力每次的币 $fans = WeixinFans::findOne(['member_id' => $this->member_id]); $db = Yii::$app->db; $trans = $db->beginTransaction(); try { $model = new ActivityShareRecord(); $model->activity_id = $id; $model->card_id = $card_id; $model->member_id = $this->member_id; $model->header_img = CommonFun::getArrayValue($fans,'headimgurl',''); $model->nick_name = CommonFun::getArrayValue($fans,'nickname','热心省友'); $model->coin = $share_coin; $res = $model->save(); if($res === false){ throw new \Exception('保存助力记录失败,'.json_encode($model->getErrors(),JSON_UNESCAPED_UNICODE)); } $record = MembersCurrency::record($senderId,MembersCurrency::TYPE_INCR,MembersCurrency::SOURCE_SHARE_COIN,strval($model->id),$share_coin); if($record !== true){ throw new \Exception('更新省币失败:'.$record); } CommonFun::log($senderId.'获得:'.$this->member_id.'助力,得币:'.$share_coin,__FUNCTION__,'MembersFinances'); $sendInfo = Members::getFinances($senderId); if($sendInfo['coin'] >= $activity['total_coin']){//省币够了则直接等待领取 $info['card_status'] = ActivityCard::STATUS_WAITING; $res = $info->save(); if($res == false){ throw new \Exception('保存卡劵失败,'.json_encode($info->getErrors(),JSON_UNESCAPED_UNICODE)); } //TODO 发小程序消息 } $trans->commit(); $res = ActivityShareRecord::getList(['activity_id' => $id,'card_id' => $card_id],[],'id desc',false,['header_img','nick_name']); $res['member_coin'] = $sendInfo['coin']; return CommonFun::returnSuccess($res); } catch (\Exception $e) { $trans->rollBack(); return CommonFun::returnFalse('助力失败,请稍后再试:'.$e->getMessage()); } } /** * 生成助力单 一人一活动只能一次助力 * @return unknown */ public function actionCreateHelp(){ $id = intval($this->request->post('id',0));//活动id $activity = $this->getActivity($id); $sendInfo = Members::getFinances($this->member_id); /* if($sendInfo['coin'] >= $activity['total_coin']){//省币够了则直接兑换 return CommonFun::returnFalse('您的省币可以自己兑换啦'); } */ $info = ActivityCard::getOne(['card_status' => ActivityCard::STATUS_DOING,'member_id' => $this->member_id,'object_id' => $id,'type' => 2]); if(!empty($info)){ return CommonFun::returnSuccess(['card_id' => $info->id]); } $model = new ActivityCard(); $model->member_id = $this->member_id; $model->object_id = $id; $model->name = $activity['name']; $model->type = 2; $model->card_status = ActivityCard::STATUS_DOING; $model->merchant_id = $activity['merchant_id']; $model->original_price = $activity['original_price']; $model->object_coin = $activity['total_coin']; $endtime = time() + $activity['days'] * 3600 *24; $tmp = strtotime($activity['end_time']); if($endtime > $tmp){//谁小用谁的时间 $endtime = $tmp; } $model->end_time = date('Y-m-d H:i:s',$endtime); $res = $model->save(); if($res == false){ return CommonFun::returnFalse('操作失败,'.json_encode($model->getErrors(),JSON_UNESCAPED_UNICODE)); } return CommonFun::returnSuccess(['card_id' => $model->id]); } }<file_sep>/controllers/WeixinController.php <?php namespace api\controllers; use common\components\CommonFun; use common\components\Notice; use common\extend\OSS\Common; use common\models\ExchangePoint; use common\models\Members; use common\models\MerchantsAccount; use common\models\MerchantsFinances; use common\models\Recommends; use common\models\WeixinFans; use common\models\WxKeyWords; use common\models\WxKeyWordsItems; use yii\web\Controller; use common\models\Config; use Yii; use common\models\MembersCurrency; use common\models\MembersFinances; use common\models\MerchantsRemind; class WeixinController extends Controller { public $weixin; public $openid; public $unionid; public $msgType; public $content; public $event; public $sysConfig; public $is_new = false; public $memberInfo; public function init() { $this->weixin = \Yii::$app->wechat; $this->sysConfig = Config::getConfigs('basic'); //配置 parent::init(); // TODO: Change the autogenerated stub } //返回JScofnig public function actionJsConfig($url, $date=''){ if($date == ''){ $date = time(); } $res = $this->weixin->jsApiConfig(['url'=>$url, 'timestamp'=>$date]); return json_encode($res); } //接入 public function actionIndex(){ $signature = CommonFun::getParams('signature'); $timestamp = CommonFun::getParams('timestamp'); $nonce = CommonFun::getParams('nonce'); $echostr = CommonFun::getParams('echostr'); if($this->weixin->checkSignature($signature, $timestamp, $nonce)) { echo $echostr; } $data = $this->weixin->parseRequestData(); if(!$data) return false; CommonFun::log($data,'', 'weixin'); // $data = ' {"ToUserName":"gh_0f63ca881741","FromUserName":"ooS7e0lpKC7DlszwH1iaB0F2hfLM","CreateTime":"1539347207","MsgType":"event","Event":"subscribe","EventKey":"qrscene_recommend:merchants_1003302","Ticket":"gQGZ8TwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyMS1aazlNeEtmdWkxMDAwMGcwN1MAAgSYG8BbAwQAAAAA"}'; // $data = json_decode($data, true); // CommonFun::pp($data); $this->msgType = $data['MsgType']; $this->openid = $data['FromUserName']; //查看用户是否存在 $wxFans = WeixinFans::getWeixinFans($this->openid); if(!$wxFans){ //如果不存在 添加新用户 $this->memberInfo = $this->weixin->getMemberInfo($this->openid); // CommonFun::pp($this->memberInfo); $memberid = 0; //验证unionid是否存在 if(isset($this->memberInfo['unionid'])){ $wxTmp = WeixinFans::getUnionid($this->memberInfo['unionid']); if($wxTmp){ $memberid = $wxTmp->member_id; } } //用户不存在时 $this->memberInfo['nickname'] = CommonFun::filter_Emoji($this->memberInfo['nickname']); if($memberid == 0){ $this->is_new = true; //新添加帐号 $member = new Members(); $member->nickname = $this->memberInfo['nickname']; $member->sex = $this->memberInfo['sex']; $member->status = 1; $member->ctime = time(); $member->save(); //用户财务表 $memberFinance = new MembersFinances(); $memberFinance->member_id = $member->id; $memberFinance->save(); $memberid = $member->id; //注册钩子,给用户发送省币 MembersCurrency::memberRegister($member->id); } //更新fans表 //不存在写入 $wxFans = new WeixinFans(); $wxFans->subscribe = 1; $wxFans->openid = $this->memberInfo['openid']; $wxFans->unionid = $this->memberInfo['unionid']; $wxFans->nickname = $this->memberInfo['nickname']; $wxFans->sex = $this->memberInfo['sex']; $wxFans->city = $this->memberInfo['city']; $wxFans->province = $this->memberInfo['province']; $wxFans->language = $this->memberInfo['language']; $wxFans->country = $this->memberInfo['country']; $wxFans->headimgurl = $this->memberInfo['headimgurl']; $wxFans->is_mini = 0; //微信 if($memberid > 0){ $wxFans->member_id = $memberid; } $wxFans->subscribe_time = time(); $wxFans->save(); }else{ //openid过来的用户 记录unionid if ($wxFans->unionid == ''){ $memberInfo = $this->weixin->getMemberInfo($this->openid); $wxFans->unionid = $memberInfo['unionid']; $wxFans->save(); } } // CommonFun::pp($wxFans); //开始事件 if($this->msgType == 'event'){ $this->event = $data['Event']; if($this->event == 'unsubscribe'){ $wxFans->subscribe = 0; $wxFans->update_time = time(); $wxFans->save(); MerchantsRemind::add($wxFans,0,false); exit;//直接返回不处理后面 } $qrscene = false; switch ($this->event){ case 'subscribe': //如果已经取消关注,处理成关注 if($wxFans && $wxFans->subscribe == 0){ $wxFans->subscribe = 1; $wxFans->save(); $this->content = '重新关注'; } if($this->is_new){ $this->content = '关注'; } if(isset($data['EventKey'])){ $qrscene = substr($data['EventKey'], 8, strlen($data['EventKey'])-1); } break; case 'SCAN': $qrscene = $data['EventKey']; if($this->is_new == true){ $this->content = '关注'; }else{ $this->content = '扫码'; } break; case 'TEMPLATESENDJOBFINISH': exit; break; case 'CLICK': $this->content = urldecode($data['EventKey']); break; case 'VIEW': //这里可以打点数据 exit; //直接退出 break; case 'view_miniprogram': exit; break; case 'LOCATION': //上报位置 $redis = Yii::$app->redis; $redis->select(2); //2表 $tmp['latitude'] = $data['Latitude']; $tmp['longitude'] = $data['Longitude']; $tmp['precision'] = $data['Precision']; $redis->set('location:'.$this->openid, json_encode($tmp)); $redis->expire('location:'.$this->openid, 7200); exit; break; default: break; } //有场景过来 if($qrscene){ $qrsceneArray = explode(':', $qrscene); $category = $qrsceneArray[0]; if($category == 'recommend'){ //推荐处理 $recommend = explode('_', $qrsceneArray[1]); $recommend_type = $recommend[0]; $recommend_id = $recommend[1]; //用户不能推荐自己 if($recommend_id == $wxFans->member_id){ $this->weixin->sendText($this->openid, '您不能推荐自己!'); exit; } //异步处理 //查询推荐商家或者用户是否存在 $recommendExist = false; if($recommend_type == 'merchants'){ Notice::submitQrcord($recommend_id, $this->openid); if($this->is_new){ Recommends::record(Recommends::$TYPES_KEY[$recommend_type], $recommend_id, $wxFans->member_id); } exit; // $recommendMerchant = MerchantsAccount::findOne($recommend_id); // if($recommendMerchant){ // $recommendExist = true; // } // //调出商家信息,发送给用户 // if($recommendMerchant){ // $address = ''; // if($recommendMerchant->extends->address){ // $tmp = explode(',', $recommendMerchant->extends->address); // unset($tmp[0]); // unset($tmp[1]); // $address = join('', $tmp); // } // // $article[] = [ // 'title' => $recommendMerchant->name.' - (付款得省币)', // 'description' => $address, // 'url' => "https://weixin.shenglife.cn/payment/checkOut/".$recommendMerchant->id, // 'picurl' => ($recommendMerchant->extends->logo)?$this->sysConfig['oss_host'].$recommendMerchant->extends->logo:'' // ]; //// if(!in_array($recommend_id, ['1003346']) ){ //// $article[] = [ //// 'title' => '快捷结账: 立即支付得省币', //// 'url' => "https://weixin.shenglife.cn/payment/checkOut/".$recommendMerchant->id, //// 'picurl' => $this->sysConfig['oss_host'].'/wxlistpay2.png' //// ]; //// } //// CommonFun::log($article, '', 'test'); //// //查询是否绑定兑换点 //// $expoint = ExchangePoint::findOne(['merchants_id'=>$recommend_id]); //// if($expoint){ //// $point_url = 'https://weixin.shenglife.cn/offline/'.$expoint->id; //// }else{ //// $point_url = 'https://weixin.shenglife.cn/exchangeindex'; //// } //// //// if($this->event == 'SCAN'){ ////// $this->weixin->sendText($this->openid, '欢迎光临:'.$recommendMerchant->name); //// $point_title = '免费好物等你兑回家'; //// }else{ ////// $this->weixin->sendText($this->openid, '您已经关注商家:'.$recommendMerchant->name); //// $point_title = '亲,恭喜您获得20省币,免费兑换'; //// } //// $getCoin = [ //// 'title' => $point_title, //// 'url' => $point_url, //// 'picurl' => $this->sysConfig['oss_host'].'/wxlistcoin.png' //// ]; //// $article[] = $getCoin; // //// CommonFun::pp($article); //// $this->weixin->sendNews($this->openid, $article); // if($this->is_new){ // Recommends::record(Recommends::$TYPES_KEY[$recommend_type], $recommend_id, $wxFans->member_id); // } // exit; // } }else{ $recommendMember = WeixinFans::findOne(['member_id'=>$recommend_id]); if($recommendMember){ if($this->is_new){ $reTxt = "恭喜:{$recommendMember->nickname} ,您已被会员\"{$wxFans['nickname']}\"成功关注 \n省生活,省出品质生活。"; $this->weixin->sendText($recommendMember->openid, $reTxt); Recommends::record(Recommends::$TYPES_KEY[$recommend_type], $recommend_id, $wxFans->member_id); exit; } } } }elseif ($category == 'messages'){//消息通知 'messages:merchants_1234' 格式 $tmp = explode('_', $qrsceneArray[1]); $type = $tmp[0]; $tmpId = $tmp[1]; if($type == 'merchants'){//写入数据 $res = MerchantsRemind::add($wxFans,$tmpId); CommonFun::log('写入消息通知结果:'.$res,'qrcode','Weixin'); if($res){ $reTxt = "您已成功绑定消息通知功能。"; $this->weixin->sendText($wxFans->openid, $reTxt); } exit; } } //其它场景,预留 } } if($this->content == ''){ $this->content = '首页'; } if($this->msgType == 'text' && isset($data['Content'])) { $this->content = $data['Content']; } $s = WxKeyWords::searchKeyword($this->content); if($s){ if($s['type'] == 1){ //文本 $this->weixin->sendText($this->openid, $s['desc']); exit; } if($s['type'] == 2){ //单图文 $article[] = [ 'title' => $s['name'], 'description' => $s['desc'], 'url' => ($s['url'])?$s['url']:'', 'picurl' => ($s['pic'])?$this->sysConfig['oss_host'].$s['pic']:'' ]; $this->weixin->sendNews($this->openid, $article); exit; } if($s['type'] == 3){ $items = WxKeyWordsItems::getItmes($s['id']); if($items){ foreach ($items as $item){ $article[] = [ 'title' => $item['name'], 'description' => $item['desc'], 'url' => ($item['url'])?$item['url']:'', 'picurl' => ($item['pic'])?$this->sysConfig['oss_host'].$item['pic']:'' ]; } $this->weixin->sendNews($this->openid, $article); exit; } } } exit; } } <file_sep>/controllers/BaseController.php <?php namespace api\controllers; use common\components\CommonFun; use common\components\Func; use common\extend\OSS\Common; use common\models\Members; use common\models\WeixinFans; use Yii; use common\models\Config; use common\components\CommonValidate; use yii\helpers\ArrayHelper; use yii\filters\Cors; use yii\web\Controller; use common\controllers\RRKDBaseController; //extends \yii\rest\Controller class BaseController extends RRKDBaseController { public $layout = false; public $post = null; public $get = null; public $isGet = false; public $isPost = false; public $isAjax = false; public $token = null; public $region; public $lat; public $lon; public $openid; public $city_id; public $weixin; public $member_id = 0; public $location; public $api_source = ''; public $pageSize = 10; public $pageNum = 1; public $offset = 0; public $pageInfo = []; public function init() { $this->isAjax = CommonValidate::isAjax(); $this->isPost = CommonValidate::isPost(); $this->isGet = CommonValidate::isGet(); //过滤 Yii::$app->request->setBodyParams(CommonFun::postCleanXss(Yii::$app->request->post())); //验证TOKEN $this->api_source = Yii::$app->request->headers->get('useFlag', ''); if(in_array($this->api_source, ['miniprogram', 'alimini', 'H5'])){ //目前只验证小程序 //验证TOKEN $this->token = Yii::$app->request->headers->get('token'); $time = Yii::$app->request->headers->get('time'); $key = 'www.shenglife.cn.wxapp'; $validToken = md5($time . $key); if($validToken != $this->token){ return CommonFun::returnFalse('TOKEN FAIL!'); } } $this->region = urldecode(Yii::$app->request->headers->get('region')); $this->city_id = Yii::$app->request->headers->get('cityid'); // // $redis = Yii::$app->redis; // $redis->select(2); //2表 // $location = $redis->get('location:'.$this->openid); // if($location){ // $this->location = json_decode($location, true); // } //// CommonFun::pp($this->location); // if($this->location){ // $this->lon = $this->location['longitude']; // $this->lat = $this->location['latitude']; // }else{ // $this->lat = Yii::$app->request->headers->get('lat'); // $this->lon = Yii::$app->request->headers->get('lon'); // } $this->lat = Yii::$app->request->headers->get('lat'); $this->lon = Yii::$app->request->headers->get('lon'); $this->pageNum = Yii::$app->request->get('pageNum',1); --$this->pageNum; $this->pageSize = Yii::$app->request->get('pageSize',10); $this->offset = $this->pageNum * $this->pageSize; $this->pageInfo = ['limit' => $this->pageSize,'page' => $this->pageNum]; parent::init(); } public function beforeAction($action) { parent::beforeAction($action); $this->post = yii::$app->request->post(); $this->get = yii::$app->request->get(); Yii::$app->params['basic'] = Config::getConfigs('basic'); //配置 Yii::$app->params['signin'] = Config::getConfigs('signin'); //签到 return $action; } /** * 返回数据 * @param $data * @param $code * @param $message */ public function resultData($data, $code = 200, $message = ''){ Yii::$app->response->statusCode = $code; Yii::$app->response->statusText = $message; Yii::$app->response->data = $data; // CommonFun::returnSuccess(); //是否考虑 采用这种输出方式 灵活 } } <file_sep>/modules/member/controllers/CommonController.php <?php namespace app\modules\member\controllers; use \Yii; use common\components\CommonFun; use api\controllers\MemberBaseController; use common\models\ExchangePorintSetting; use common\models\Orders; use common\components\CommonValidate; use common\components\SendSms; use common\models\Members; use common\models\CommonModel; use common\models\WeixinFans; use common\models\AlipayFans; use common\models\MembersFinances; /**********************处理其他基类需要用户登录的actions RTS 2018年10月11日16:59:51*****************************/ class CommonController extends MemberBaseController{ /** * 查询用户在当前兑换点订单情况, 处理限购条件 * @param $id 兑换点ID */ public function actionMemberLimitOrders($id){ $data = ['coin_order'=>0, 'amount_order'=>0]; $setting = ExchangePorintSetting::findOne(['id'=>$id]); if($setting){ $limit_cycle = ($setting['limit_cycle'] != 0)?($setting['limit_cycle']*(60*60*24)):0; if($setting->limit_number != 0){ $order = Orders::find(); $order->where('member_id=:mid and order_obj_id=:oid', [':mid' => $this->member_id, ':oid'=>$id]); $order->andWhere(['not in', 'order_status', [8,9]]); $order->groupBy('product_id'); if($limit_cycle != 0){ $order->andWhere(['>=', 'ctime', time() - $limit_cycle]); } $res = $order->all(); if($res){ foreach($res as $item){ if($item->product_amount == 0){ $data['coin_order'] += 1; }else{ $data['amount_order'] += 1; } } } } return CommonFun::returnSuccess($data); } return CommonFun::returnFalse('系统错误! 请联系客服'); } public function actionBindMobile(){ if($this->isPost){ $mobile = $this->request->post('mobile',''); $code = $this->request->post('code',''); $type = $this->request->post('type',10); if(empty($mobile) || empty($code)){ return CommonFun::returnFalse('缺少必要参数:'.__LINE__); } if(!CommonValidate::isMobile($mobile)){ return CommonFun::returnFalse('手机号错误:'.__LINE__); } $obj = new SendSms(true); $res = $obj->verifyValidate($type, $mobile, $code); if(!$res){ return CommonFun::returnFalse('验证码错误'); } $info = Members::findOne($this->member_id); $info->mobile = $mobile; $res = $info->save(); if($res !== true){ return CommonFun::returnFalse('操作失败'); } $info = Members::find()->where(['mobile' => $mobile,'status' => CommonModel::STATUS_ACTIVE])->all(); $counts = count($info); if($counts == 1){ return CommonFun::returnSuccess(); } if($counts != 2){ CommonFun::log([$info,$this->member_id,'mobile' => $mobile],'',__FUNCTION__); return CommonFun::returnFalse('账户异常,请联系我们'); } //eq. member table source_type|openplatform_type 2018年10月26日16:20:37 $ids = ''; foreach ($info as $item){ if($item->id == $this->member_id && $this->api_source == 'alipay'){ $data['alipay']['member_id'] = $item->id; $ids .= $item->id; }else{ $data['weixin']['member_id'] = $item->id; $ids .= $item->id; } } $data['token'] = CommonFun::md5($ids.'<PASSWORD>@'); return CommonFun::returnSuccess($data); } } public function actionAccountMerge(){ if($this->isPost){ $from_source = $this->request->post('from_source', 'weixin'); $token = $this->request->post('token',''); $from = $this->request->post('from', ''); $to = $this->request->post('to', ''); if(empty($from) || empty($to)){ return CommonFun::returnFalse('请选择保留账号'); } $tmpToken = CommonFun::md5($from.$to.'shenglife@'); if($token != $tmpToken){ $tmpToken = CommonFun::md5($to.$from.'shenglife@'); if($token != $tmpToken){ return CommonFun::returnFalse('数据错误!'); } } if($from_source == 'weixin'){ // $model = WeixinFans::findOne(['member_id' => $from]); try{ WeixinFans::updateAll(['member_id' => $to], 'member_id=:id', [':id'=>$from]); }catch (\Exception $e){ CommonFun::log($e, __FUNCTION__, 'merge'); return CommonFun::returnFalse('操作失败,请稍后再试。'); } } else { $model = AlipayFans::findOne(['member_id' => $from]); if(!$model){ return CommonFun::returnFalse('获取粉丝信息失败。'); } //TODO 修改被合并的用户id到新的id上面 $model->member_id = $to; $res = $model->save(); if($res !== true){ return CommonFun::returnFalse('操作失败,请稍后再试。'); } } $fromFinancesModel = MembersFinances::findOne(['member_id' => $from]); $toFinancesModel = MembersFinances::findOne(['member_id' => $to]); CommonFun::log([$fromFinancesModel,$toFinancesModel],__FUNCTION__,'merge'); if($fromFinancesModel){ if($fromFinancesModel->balance > 0){//转钱 $toFinancesModel->balance = CommonFun::doNumber($toFinancesModel->balance,$fromFinancesModel->balance,'+'); $fromFinancesModel->balance = 0; } if($fromFinancesModel->coin > 0){//转币 $toFinancesModel->coin = CommonFun::doNumber($toFinancesModel->coin,$fromFinancesModel->coin,'+'); $fromFinancesModel->coin = 0; } $res = $toFinancesModel->save() && $fromFinancesModel->save(); if($res !== true){ return CommonFun::returnFalse('操作失败,请稍后再试。'); } CommonFun::log([$fromFinancesModel,$toFinancesModel],__FUNCTION__,'merge'); } $model = Members::findOne($from); $model->status = Members::STATUS_DISABLE; $model->save(); return CommonFun::returnSuccess(); } } }<file_sep>/modules/activity/controllers/WxshareController.php <?php namespace app\modules\activity\controllers; use common\components\CommonValidate; use common\models\MembersAddress; use \Yii; use common\components\CommonFun; use common\models\ActivityShare; use api\controllers\BaseController; use common\models\CommonModel; use common\models\MerchantsAccount; use common\models\ActivityCard; class WxshareController extends BaseController{ /** * 获取活动列表 * @return unknown */ public function actionList(){ $lists = ActivityShare::getList(['put_status' => CommonModel::STATUS_ACTIVE],$this->pageInfo,'sort desc',false,['id','name','img','desc','end_time','total_coin','original_price']); return CommonFun::returnSuccess(['rows' => $lists['data'],'counts' => $lists['count']]); } /** * 获取活动详情 * @return unknown */ public function actionDetails($id = 0){ //TODO 增加活动状态 $id = intval($id); $res = ActivityShare::getOne(['id' => $id],true); if($res){ $res['activityStatus'] = ActivityShare::status($id); $member_id = Yii::$app->request->headers->get('uid'); if(empty($member_id)){ return CommonFun::returnFalse('Not login'); } $counts = ActivityCard::buyedCount($id,$member_id); if($res['put_status'] == CommonModel::STATUS_DELETE || $res['activityStatus']['status'] == 0){ $canBuyCount = 0; }else{ $canBuyCount = $res['limit'] - $counts; $canBuyCount = $canBuyCount <= 0 ? 0 : $canBuyCount; } $info = ActivityCard::getOne(['object_id' => $id,'member_id' => $member_id,'type' => 2,'card_status' => [ ActivityCard::STATUS_WAITING,ActivityCard::STATUS_DOING]],true); $res['userActivityStatus'] = [ 'can_buy_count' => $canBuyCount, 'id' => CommonFun::getArrayValue($info,'id',''), 'card_status' => CommonFun::getArrayValue($info,'card_status',''), ]; } return CommonFun::returnSuccess($res); } }<file_sep>/config/params.php <?php use common\components\CommonFun; return []; <file_sep>/controllers/CommonController.php <?php namespace api\controllers; use common\components\Func; use Yii; use common\components\CommonFun; use common\models\OpenCity; use common\models\CommonModel; use yii\web\Controller; use common\models\Orders; use common\components\enum\OrderEnum; use common\models\Alisms; use common\components\SendSms; use yii\web\Response; use common\components\CommonValidate; use common\models\Members; use common\models\MembersFinances; use common\models\MerchantsApply; class CommonController extends BaseController { public function beforeAction($action) { parent::beforeAction($action); if ($this->isGet ) { return true; } if($action->id != 'merchants-apply'){ return true; } $outPut = parent::check($action); if ($outPut === true) { return true; } } /** * 商户申请入驻 * @author RTS 2018-11-29 14:35:13 */ public function actionMerchantsApply(){ $model = new MerchantsApply(); $data = $this->request->post(); if(!$model->load($this->request->post(),'')){ return CommonFun::returnFalse('处理失败,请稍后再试。'); } $res = MerchantsApply::findOne(['phone' => $model->phone]); if(!empty($res)){ return CommonFun::returnFalse('手机号:'.$model->phone.'已经提交过,请耐心等待,我们会尽快安排人员与您联系'); } try { $res = $model->save(); if($res === false){ throw new \Exception(); } return CommonFun::returnSuccess(); } catch (\Exception $e) { return CommonFun::returnFalse('处理失败,请稍后再试。'.__LINE__); } } /** * 经纬度获取文本 * @param string $lat * @param string $lon */ public function actionLocation($lat = '',$lon = ''){ if($lat == ''){ $redis = Yii::$app->redis; $redis->select(2); //2表 $openid = Yii::$app->request->headers->get('openid'); $location = $redis->get('location:'.$openid); if($location){ $location = json_decode($location, true); $lon = $location['longitude']; $lat = $location['latitude']; } } $res = CommonFun::getTencentLonLatInAddress($lon, $lat); $res['latitude'] = $lat; $res['longitude'] = $lon; return CommonFun::returnSuccess($res); } /** * 首页滚动订单消息 * @author RTS 2018年4月28日 13:10:06 */ public function actionOrderMsg(){ $where = [ 'order_status' => OrderEnum::ORDER_STATUS_DONE, ]; $data = Orders::getList($where,10,0,' rand() ',''); $return = []; if(empty($data['data'])){ return CommonFun::returnSuccess($return); } foreach ($data['data'] as $item){ if(in_array($item['type'],[OrderEnum::TYPE_ONLINEOFF_PAY,OrderEnum::TYPE_SHOP])){ $type = '购买商品获得省币:'.CommonFun::formatMoney($item['member_coin']); }else{ $type = '兑换商品使用省币:'.CommonFun::formatMoney($item['order_coin']); } $item['member_id'] = substr($item['member_id'], 4); $return[] = '会员:'.$item['member_id'].'***'.$type; } return CommonFun::returnSuccess($return); } /** * 发送验证码 */ public function actionSendSms() { if (Yii::$app->request->isAjax || Yii::$app->request->isPost) { $data = ['code' => -1, 'msg' => '错误, 请重试']; Yii::$app->response->format = Response::FORMAT_JSON; $phone = Yii::$app->request->post('phone'); $type = Yii::$app->request->post('type'); if (!isset(Alisms::$TYPE_TO_CONST[$type])) { return $data['msg'] = '业务类型错误'; } $obj = new SendSms(true); //验证请求次数 if (false && $obj->checkCount($phone)) { $data['msg'] = '您的手机号操作过于频繁,请稍后重试'; return $data; } //发送验证码 $tmpType = Alisms::$TYPE_TO_CONST[$type]; $res = $obj->verifyCode($tmpType, $phone); if ($res === true) { $data['code'] = 1; $data['msg'] = 'SUCCESS'; }else{ $data['code'] = 0; $data['msg'] = '发送失败,请稍候再试。'; } return $data; }; } //手机帐号密码登录 public function actionLogin(){ if(Yii::$app->request->isPost){ $account = trim(Yii::$app->request->post('account', '')); $password = trim(Yii::$app->request->post('password', '')); if(!CommonValidate::isMobile($account)){ CommonFun::returnFalse('帐号格式错误'); } if(CommonFun::utf8_strlen($password) < 6){ CommonFun::returnFalse('密码格式错误'); } $password = CommonFun::md5($password, '<PASSWORD>'); $query = Members::find() ->where('mobile=:m and loginpass=:p', [':m'=>$account, ':p'=>$password]) ->one(); if($query){ return CommonFun::returnSuccess(['member_id' => $query->id]); } return CommonFun::returnFalse('帐号密码错误'); } } //手机帐号验证码登录 public function actionLoginCode(){ if(Yii::$app->request->isPost){ $account = trim(Yii::$app->request->post('account', '')); $vercode = trim(Yii::$app->request->post('vercode', '')); if(!CommonValidate::isMobile($account)){ return CommonFun::returnFalse('帐号格式错误'); } if(CommonFun::utf8_strlen($vercode) != 6){ return CommonFun::returnFalse('验证码格式错误'); } $cv = new \common\components\SendSms(); if (!$cv->verifyValidate(Alisms::TYPE_LOGIN, (string)$account, $vercode)) { return CommonFun::returnFalse('验证码错误'); } //查询帐号是否存在 $model = Members::find() ->where('mobile=:m', [':m'=>$account]) ->one(); if($model){ return CommonFun::returnSuccess(['member_id' => $model->id]); }else{ //新建帐号 $member = new Members(); $member->mobile = $account; $member->status = 1; $member->ctime = time(); $member->save(); //用户财务表 $memberFinance = new MembersFinances(); $memberFinance->member_id = $member->id; $memberFinance->save(); return CommonFun::returnSuccess(['member_id' => $member->id]); } return CommonFun::returnFalse('登录失败'); } } /** * H5页面 如果是自动登录,检验用户 */ public function actionH5TokenVaild(){ if($this->isPost){ $uid = Yii::$app->request->post('uid'); $token = Yii::$app->request->post('token'); $type = Yii::$app->request->post('platform'); $vaildToken = CommonFun::md5($uid.$type.CommonFun::md5($uid).'qrcode-h5'); // CommonFun::pp($vaildToken); if($vaildToken != $token){ return CommonFun::returnFalse('token fail'); } $member = Members::getInfo($uid); if(empty($member)){ return CommonFun::returnFalse('account fail'); } return CommonFun::returnSuccess($member); } return CommonFun::returnFalse('error!'); } }<file_sep>/modules/notify/controllers/ExpressController.php <?php namespace app\modules\notify\controllers; use Yii; use common\components\CommonFun; use yii\web\Controller; use common\models\Orders; use common\models\CommonModel; use common\models\OrdersShipping; use common\components\CommonValidate; class ExpressController extends Controller { /** * 快递100推送 * @author RTS 2018年5月9日 13:22:14 */ public function actionIndex() { if(!CommonValidate::isPost()){ exit('err method'); } $param = $_POST ['param']; $this->log( '数据:' . json_encode ( $_POST, JSON_UNESCAPED_UNICODE )); try { $params = json_decode($param,true); $lastResult = CommonFun::getArrayValue($params,'lastResult',[]); $company = CommonFun::getArrayValue($lastResult,'com',''); $number = CommonFun::getArrayValue($lastResult,'nu',''); $data = CommonFun::getArrayValue($lastResult,'data',''); $res = false; if(!empty($data) && !empty($number)){ $res = OrdersShipping::fill($number,$data); } $this->log('成功返回:'.$res); exit ( '{"result":"true","returnCode":"200","message":"成功"}'); } catch ( \Exception $e ) { $this->log('失败返回'.$e->getMessage()); echo ('{"result":"false","returnCode":"500","message":"失败"}'); } } private function log($msg = ''){ CommonFun::log ( $msg, "callback", "express" ); } } <file_sep>/modules/local/controllers/MerchantsController.php <?php namespace app\modules\local\controllers; use api\controllers\BaseController; use common\components\Func; use common\extend\OSS\Common; use common\models\Category; use common\components\CommonGeoLocal; use common\models\CityCode; use common\components\CommonFun; use common\models\Coupons; use common\models\MerchantsAccount; use common\models\MerchantsAccountExtends; use common\models\MerchantsAccountSetting; use common\models\MerchantsExtracts; use common\models\MerchantsLocalFeatures; use common\models\MerchantsLocalProduct; use common\models\MerchantsLocalTag; use common\models\OpenCity; use common\models\ExchangePoint; use common\models\Orders; /** * Default controller for the `local` module */ class MerchantsController extends BaseController { //取出附近商家 private function getGeolocal($num = 20){ $key = CommonGeoLocal::getKey('local:',$this->region); $res = CommonGeoLocal::getLocal($key, $this->lon, $this->lat, $num); return $res; } //附近 public function actionNear(){ //看下是不是当前城市 $citys = OpenCity::findOne($this->city_id); if($citys && $citys->name != $this->region){ return CommonFun::returnSuccess(); } $res = $this->getGeolocal(); if(!$res) { return CommonFun::returnSuccess(); } $data = []; foreach ($res as $v){ $model = MerchantsAccount::getLocalData($v['merchants_id'], $v['distance']); if($model){ $data[] = $model; } } return CommonFun::returnSuccess($data); } /** * 根据城市来获取所有商家 * @throws \yii\db\Exception */ public function actionCityLists(){ $city = CommonFun::getParams('city', ''); if($city == 'undefined'){ $city = ''; } $sql = "SELECT a.id, a.name, a.account, ae.longitude, ae.latitude, ae.logo, ae.address, ae.slogan, mas.local_category FROM sf_merchants_account_extends ae, sf_merchants_account a, sf_merchants_account_setting mas where longitude <> '' and latitude <> '' and ae.id=a.id and a.id=mas.id and a.status=2 and a.is_local=1"; if($city){ $sql .= " and find_in_set('".$city."',ae.address)"; } $db = \Yii::$app->db; $query = $db->createCommand($sql); $data = $query->queryAll(); return CommonFun::returnSuccess($data); } /** * @param $city 城市 * @param $order_by 排序名 * @param $sort 排序方式 * @param $name 商家名称 * @param $category_id 分类ID * * @throws \yii\db\Exception */ public function actionList(){ $lat = $this->lat; $lng = $this->lon; if(!$lat || !$lng){ return CommonFun::returnFalse('未定位'); } $city = CommonFun::getParams('city', ''); if($city == 'undefined'){ $city = ''; } $order_by = CommonFun::getParams('order_by', ''); $sort = CommonFun::getParams('sort', 0); $name = CommonFun::getParams('name', ''); $category_id = CommonFun::getParams('category_id', 0); $distance = CommonFun::getParams('distance', 0); //距离 if($sort == 0){ $sort = 'asc'; }else{ $sort = 'desc'; } $sql = "SELECT a.id, a.name, a.account, ae.longitude, ae.latitude, ae.logo, ae.address, ae.slogan, ae.open_date, ae.peple_average, mas.local_category, ROUND(6378.138*2*ASIN(SQRT(POW(SIN((".$lat."*PI()/180-latitude*PI()/180)/2),2)+COS(".$lat."*PI()/180)*COS(latitude*PI()/180)*POW(SIN((".$lng."*PI()/180-longitude*PI()/180)/2),2)))*1000) AS distance FROM sf_merchants_account_extends ae, sf_merchants_account a, sf_merchants_account_setting mas where longitude <> '' and latitude <> '' and ae.id=a.id and a.id=mas.id and a.status=2 and a.is_local=1"; if($city){ $sql .= " and find_in_set('".$city."',ae.address)"; } if($name){ $sql .= " and a.name like '%".$name."%'"; } $category_id = intval($category_id); if($category_id > 0){ $sql .= " and find_in_set(".$category_id.", mas.local_category)"; } if($distance > 0){ $sql .= " having distance <= ".($distance * 1000); } if($order_by){ $sql .= " ORDER BY ".$order_by.' '.$sort; }else{ $sql .= " ORDER BY distance asc"; } //这里直接设置50个, 前端打包的时候放开 $sql .= " limit ".$this->offset. ','. $this->pageSize; // CommonFun::pp($sql); $db = \Yii::$app->db; $query = $db->createCommand($sql); $data = $query->queryAll(); if(!$data){ return CommonFun::returnSuccess(); } foreach ($data as $k=>$v){ $flags = []; //查找有没有兑换点 $point = ExchangePoint::findOne(['merchants_id'=>$v['id'], 'status'=>1]); if($point){ $pointArr['key'] = 1; $pointArr['item'] = '兑换点'; $flags = [$pointArr]; } //查商家有没有优惠券 $coupons = Coupons::findOne(['merchant_id'=>$v['id'], 'type'=>1]); if($coupons){ $flags[] = ['key'=>$coupons->id, 'item'=>$coupons->name]; } $data[$k]['tags'] = MerchantsLocalTag::getTags($v['id']); $data[$k]['flags'] = $flags; $data[$k]['distance'] = sprintf("%0.2f", $v['distance'] / 1000); // $data[$k]['order_num'] = Orders::getCount($v['id'], 3); } return CommonFun::returnSuccess(['page_size'=>$this->pageSize,'page_num' => ++$this->pageNum, 'lists' => $data]); // CommonFun::pp(MerchantsLocalTag::getTags(1003313)); } //分类商家、搜索 public function actionCategory($category_id, $search='', $sort='near'){ $ms = $this->getGeolocal(); if(!$ms) { return CommonFun::returnSuccess(); } $mids = MerchantsAccountSetting::getCategoryAccount($category_id, $search); $filterid = []; //合并附近 foreach ($mids as $k=>$v){ foreach ($ms as $kk=>$vv){ if($v['merchants_id'] == $vv['merchants_id']){ $filterid[] = $ms[$kk]; } } } $data = []; foreach ($filterid as $v){ $model = MerchantsAccount::getLocalData($v['merchants_id'], $v['distance']); if($model){ $data[] = $model; } } return CommonFun::returnSuccess($data); } //商家详情 public function actionView($merchants_id){ $query = MerchantsAccount::find(); $query->where('id=:id', [':id'=>$merchants_id]); $query->with(['point' => function($query){ return $query->where(['status'=>1]); }]); $model = $query->one(); $data = []; if($model){ $data['id'] = $model->id; $data['name'] = $model->name; $data['is_platform'] = $model->is_platform; $data['is_local'] = $model->is_local; $data['is_online'] = $model->is_online; $data['account'] = $model->account; $data['logo'] = $model->extends->logo; $data['image'] = $model->extends->image; $data['address'] = $model->extends->address; $data['phone'] = $model->extends->phone; $data['mobile'] = $model->extends->conact_mobile; $data['address'] = $model->extends->address; $data['longitude'] = $model->extends->longitude; $data['latitude'] = $model->extends->latitude; $data['slogan'] = $model->extends->slogan; $data['open_date'] = $model->extends->open_date; $data['peple_average'] = $model->extends->peple_average; $data['tags'] = MerchantsLocalTag::getTags($model->id); $data['exchange_point'] = ($model->point)?$model->point->id:0; $flags = []; //查找有没有兑换点 $point = ExchangePoint::findOne(['merchants_id'=>$model->id, 'status'=>1]); if($point){ $pointArr['key'] = 1; $pointArr['item'] = '兑换点'; $flags = [$pointArr]; } //查商家有没有优惠券 $coupons = Coupons::findOne(['merchant_id'=>$model->id, 'type'=>1]); if($coupons){ $flags[] = ['key'=>$coupons->id, 'item'=>$coupons->name]; } $data['flags'] = $flags; } return CommonFun::returnSuccess($data); } //商家商品 public function actionProducts($merchants_id){ $model = MerchantsLocalProduct::getProducts($merchants_id); return CommonFun::returnSuccess($model); } //特色 public function actionFeatures($id){ $model = MerchantsLocalFeatures::find()->where('merchants_id=:mid and active=1', [':mid'=>$id])->asArray()->all(); return CommonFun::returnSuccess($model); } //商家详情 public function actionContent($merchants_id){ $model = MerchantsAccountExtends::findOne($merchants_id); $data = []; if($model){ $data['content'] = $model->content; } return CommonFun::returnSuccess($data); } //快捷结算 public function actionPayment(){} //优惠券 public function actionCoupons($id){ $model = Coupons::find() ->select('id,name,amount,condition,type,limit') ->where('merchant_id=:mid and status=1', [':mid'=>$id]) ->asArray() ->all(); return CommonFun::returnSuccess($model); } } <file_sep>/modules/member/controllers/AddressController.php <?php namespace app\modules\member\controllers; /** * Created by PhpStorm. * User: zhongming * Date: 2018/4/3 下午4:42 */ use common\components\CommonValidate; use common\models\MembersAddress; use common\models\MembersBanks; use common\models\MerchantsFreezes; use gmars\sms\Sms; use \Yii; use common\components\CommonFun; use common\models\Members; use common\models\Alisms; use common\models\MembersFavorite; use yii\db\Expression; use yii\helpers\ArrayHelper; use api\controllers\MemberBaseController; class AddressController extends MemberBaseController{ //列表 public function actionLists(){ $lists = MembersAddress::getLists($this->member_id); return CommonFun::returnSuccess($lists); } //创建新的 public function actionCreate(){ if($this->isPost){ $name = Yii::$app->request->post('name'); $mobile = Yii::$app->request->post('mobile'); $area = Yii::$app->request->post('area'); $address = Yii::$app->request->post('address'); $default = Yii::$app->request->post('default', 0); if(CommonFun::utf8_strlen($name) < 2 || !CommonValidate::isMobile($mobile) || !in_array($default, [0,1])){ return CommonFun::returnFalse('name/mobile/default format error'); } if(CommonFun::utf8_strlen($area) < 4 || CommonFun::utf8_strlen($address) < 5){ return CommonFun::returnFalse('area/address format error'); } $id = ''; if($default == 1){ //查询默认 $model = MembersAddress::getDefaultAddress($this->member_id); if($model){ $id = $model['id']; } } $m = new MembersAddress(); $m->member_id = $this->member_id; $m->name = trim($name); $m->mobile = $mobile; $m->area = $area; $m->address = $address; $m->is_default = $default; $m->status = ($id)?$default:1; //如果是第一条数据不管什么情况都是默认 if($m->save()){ if($m->is_default == 1 && $id){ MembersAddress::updateAll(['is_default'=>0], ['id'=>$id]); } return CommonFun::returnSuccess(); } } return CommonFun::returnFalse('member address create fail'); } //更新 public function actionUpdate(){ if($this->isPost){ $id = intval(Yii::$app->request->post('id')); $name = Yii::$app->request->post('name'); $mobile = Yii::$app->request->post('mobile'); $area = Yii::$app->request->post('area'); $address = Yii::$app->request->post('address'); $default = Yii::$app->request->post('default', 0); if(!$id){ return CommonFun::returnFalse('id format error'); } if(CommonFun::utf8_strlen($name) < 2 || !CommonValidate::isMobile($mobile) || !in_array($default, [0,1])){ return CommonFun::returnFalse('name/mobile/default format error'); } if(CommonFun::utf8_strlen($area) < 4 || CommonFun::utf8_strlen($address) < 5){ return CommonFun::returnFalse('area/address format error'); } $m = MembersAddress::findOne($id); if(!$m){ return CommonFun::returnFalse('current address is not found'); } $defaultId = ''; if($default == 1){ //查询默认 $model = MembersAddress::getDefaultAddress($this->member_id); if($model && $id != $model['id']){ $defaultId = $model['id']; } } $m->name = trim($name); $m->mobile = $mobile; $m->area = $area; $m->address = $address; $m->is_default = $default; //如果是第一条数据不管什么情况都是默认 $m->status = 1; if($m->save()){ if($m->is_default == 1 && $defaultId){ MembersAddress::updateAll(['is_default'=>0], ['id'=>$defaultId]); } return CommonFun::returnSuccess(); } } return CommonFun::returnFalse('member address update fail'); } //删除 public function actionDelete(){ if($this->isPost) { $id = intval(Yii::$app->request->post('id')); $m = MembersAddress::findOne($id); if(!$m){ return CommonFun::returnFalse('current address is not found'); } $m->status = MembersAddress::STATUS_DISABLED; if($m->save()){ return CommonFun::returnSuccess(); } } return CommonFun::returnFalse('member address delete fail'); } //获取单个地址 public function actionView($id){ $data = MembersAddress::getData($this->member_id, $id); return CommonFun::returnSuccess($data); } //获取默认地址 public function actionDefault(){ $data = MembersAddress::getDefaultAddress($this->member_id); return CommonFun::returnSuccess($data); } //设置默认 public function actionSetting(){ if($this->isPost) { $id = intval(Yii::$app->request->post('id')); $m = MembersAddress::findOne($id); if(!$m){ return CommonFun::returnFalse('current address is not found'); } $defaultId = ''; if($m->is_default != MembersAddress::DEFAULT_YES){ //查询默认 $model = MembersAddress::getDefaultAddress($this->member_id); if($model && $id != $model['id']){ $defaultId = $model['id']; } } $m->is_default = MembersAddress::DEFAULT_YES; if($m->save()){ MembersAddress::updateAll(['is_default'=>0], ['id'=>$defaultId]); return CommonFun::returnSuccess(); } } return CommonFun::returnFalse('member address setting fail'); } }<file_sep>/modules/notify/controllers/WxController.php <?php namespace app\modules\notify\controllers; use Yii; use common\components\CommonFun; use yii\web\Controller; use common\models\pay\WxPayService; use common\models\OrdersPay; use common\models\MembersCurrency; use common\models\Orders; use common\models\Members; use common\models\MembersFinances; use common\components\enum\OrderEnum; use common\models\MembersFinancesDetail; use common\models\MoneyAllocateds; class WxController extends Controller { /** * 微信支付回调 * * @author RTS 2018年4月9日 14:12:10 */ public function actionPay() { $xml = isset ( $GLOBALS ['HTTP_RAW_POST_DATA'] ) ? $GLOBALS ['HTTP_RAW_POST_DATA'] : ""; $notify_array = CommonFun::FromXmlToArray ( $xml ); $wxpayserver = new WxPayService (); $notify_bool = $wxpayserver->notifyPubVerification ( $notify_array, 2, Yii::$app->wechat->partnerKey ); CommonFun::log ( "收到微信回调,校验结果:".$notify_bool.",数据:" . json_encode ( $notify_array, JSON_UNESCAPED_UNICODE ), "wxpay", "notify" ); if ($notify_bool) { // 校验成功 $out_trade_no = $notify_array ["out_trade_no"]; $transaction_id = $notify_array ["transaction_id"]; $total_fee = $notify_array ["total_fee"]; $data = OrdersPay::find ()->where ( [ 'trade_number' => $out_trade_no, 'status' => 1, 'pay_status' => 0 ] )->all(); $res = -1; $userInfo = []; if (! empty ( $data )) { foreach ( $data as $item ) { $res = MembersFinances::usePayment($item ['member_id'],$item['pay_balance_amount'],$item['pay_coin'],$item ['order_id'],$item['pay_amount']); if($res === true){ $totalPay = CommonFun::doNumber($item['pay_balance_amount'],$item['pay_amount'],'+'); $payInfo = [ 'pay_coin' => $item['pay_coin'], 'pay_amount' => $totalPay, 'pay_balance' => $item['pay_balance_amount'], 'pay_third_amount' => $item['pay_amount'], ]; $item->third_number = $transaction_id; $item->pay_status = OrderEnum::PAY_STATUS_PAYED; $where ['id'] = $item ['order_id']; $res = Orders::operation ( $where, 6, '用户', $payInfo ); } $item->remark = $res; $item->save(false); } } } CommonFun::log ( "处理结果:" . json_encode($res,JSON_UNESCAPED_UNICODE) . ',数据:' . json_encode ( $notify_array, JSON_UNESCAPED_UNICODE ), "wxpay", "notify" ); echo "SUCCESS"; exit (); } } <file_sep>/controllers/AdredirectController.php <?php namespace api\controllers; use common\components\CommonFun; use common\models\AdRecord; use common\models\Ad; class AdredirectController extends BaseLightController { /** * 广告跳转 * @param number $adId */ public function actionIndex(){ $adId = CommonFun::getParams('aid',0); $adRecord = new AdRecord(); $ad = Ad::findOne($adId); if($ad){ $adRecord->ip = CommonFun::getClientIP(); $adRecord->member_id = $this->member_id; $adRecord->ad_id = $adId; $adRecord->ctime = time(); $ad->click_count += 1; $ad->save(); $adRecord->save(); return $this->redirect($ad->url); } } } <file_sep>/modules/activity/controllers/SigninController.php <?php namespace app\modules\activity\controllers; use common\components\CommonFun; Use api\controllers\BaseController; use common\extend\OSS\Common; use common\models\MembersCurrency; use common\models\MembersSignin; use common\models\MembersSigninRecord; use api\controllers\MemberBaseController; /** * Default controller for the `activity` module */ class SigninController extends MemberBaseController { /** * Renders the index view for the module * @return string */ public function actionIndex() { $data['cond_days'] = 0; $data['today'] = false; $model = MembersSignin::findOne(['member_id'=>$this->member_id]); if($model){ //判断今天有没有签到 $time = getdate(); $today_zero = mktime(0, 0, 0, $time['mon'], $time['mday'], $time['year']); if($model->last_sign_time > $today_zero){ $data['today'] = true; } //判断昨日有没有签到,是否是连续签到 if($model->last_sign_time > ($today_zero - 24 * 60 *60)){ $data['cond_days'] = $model->cond_days; }else{ $data['cond_days'] = 0; } } CommonFun::returnSuccess($data); } //签到 public function actionCreate(){ $res['result'] = false; if($this->isPost){ $config = \Yii::$app->params['signin']; $time = getdate(); $today_zero = mktime(0, 0, 0, $time['mon'], $time['mday'], $time['year']); $model = MembersSignin::findOne(['member_id'=>$this->member_id]); if(!$model){ $model = new MembersSignin(); $model->member_id = $this->member_id; $model->last_sign_time = 0; $model->cond_days = 0; $model->save(); } if($today_zero < $model->last_sign_time && $model->last_sign_time < ($today_zero + 24*60*60)){ //已经签 $res['result'] = true; $res['is_signin'] = true; }else{ //先记录签到日志 $record = new MembersSigninRecord(); $record->ctime = time(); $record->member_id = $this->member_id; $record->coin = $config['coin']; $record->type = MembersSigninRecord::TYPE_NORMAL; $record->save(); //加省币 MembersCurrency::record($this->member_id, MembersCurrency::TYPE_INCR, MembersCurrency::SOURCE_SIGNIN, '', $config['coin']); //判断昨日有没有签到 if(($today_zero - 24 * 60 *60) < $model->last_sign_time && $model->last_sign_time < $today_zero){ //判断连续签到天数 $model->cond_days += 1; if($model->cond_days > 7){ $model->cond_days = 1; } //如果今天是第七天,那么省币在加一次 if($model->cond_days == $config['cond_days']){ $record = new MembersSigninRecord(); $record->ctime = time(); $record->member_id = $this->member_id; $record->coin = $config['cond_coin']; $record->type = MembersSigninRecord::TYPE_COND; $record->save(); //加省币 MembersCurrency::record($this->member_id, MembersCurrency::TYPE_INCR, MembersCurrency::SOURCE_SIGNIN_COND, '', $config['cond_coin']); } $model->last_sign_time = time(); }else{ $model->last_sign_time = time(); $model->cond_days = 1; } $model->save(); $res['result'] = true; $res['is_signin'] = false; } CommonFun::returnSuccess($res); } } } <file_sep>/models/User.php <?php namespace api\models; use yii\db\ActiveRecord; class User extends ActiveRecord { }<file_sep>/modules/member/controllers/CouponController.php <?php namespace app\modules\member\controllers; /** * Created by PhpStorm. * User: zhongming * Date: 2018/8/28 下午2:42 */ use common\models\Coupons; use common\models\MembersCoupon; use common\models\MerchantsAccount; use \Yii; use api\controllers\BaseController; use common\components\CommonFun; use api\controllers\MemberBaseController; class CouponController extends MemberBaseController{ /** * 获取用户优惠券列表 * @param int $type 1未使用 2已使用 3过期 */ public function actionLists($type = 1){ $data = []; if($type == 1 || $type == 3){ //找出过期的 $overdue = MembersCoupon::find() ->where('member_id=:mid and is_use = 0 and status = 1 and end_time < :date', [':mid'=>$this->member_id, ':date'=>date('Y-m-d', time())]) ->all(); if($overdue) { $ids = []; foreach ($overdue as $item) { $ids[] = $item->id; } MembersCoupon::updateAll(['status' => 0], ['in', 'id', $ids]); } } $query = MembersCoupon::find()->where('member_id=:mid',[':mid'=>$this->member_id]); switch ($type){ case 1: $query->andWhere('is_use=0 and status=1'); break; case 2: $query->andWhere('is_use=1 and status = 1'); $query->andWhere(['>', 'ctime', strtotime('-3 month')]); break; case 3: default: $query->andWhere('status = 0'); $query->andWhere(['>', 'ctime', strtotime('-3 month')]); break; } $model = $query->with('info')->asArray()->all(); if($model){ foreach ($model as $k=>$item){ if($item['info']['type'] == 1){ $model[$k]['amount'] = $item['amount']; } //商家 if(isset($item['info']['merchant_id']) && $item['info']['merchant_id'] > 0){ $model[$k]['merchant_name'] = MerchantsAccount::getName($item['info']['merchant_id']); } } } return CommonFun::returnSuccess($model); } //领取优惠券 public function actionReceive(){ if($this->isPost){ $id = Yii::$app->request->post('id', 0); if($id > 0){ $res = Coupons::send($this->member_id, $id); if(is_bool($res) && $res == true){ return CommonFun::returnSuccess(); }else{ return CommonFun::returnFalse($res); } } } } //使用券码领取优惠券 public function actionReceiveCode(){ $err = ''; if($this->isPost){ $code = trim(Yii::$app->request->post('code', '')); if($code){ if(strlen($code) < 6 || strlen($code) > 20){ $err = '优惠券格式错误'; }else{ $code = mb_strtoupper($code); $coupon = Coupons::getCode($code); if($coupon){ $res = Coupons::send($this->member_id, $coupon['id']); if(is_bool($res) && $res == true){ return CommonFun::returnSuccess(); }else{ return CommonFun::returnFalse($res); } } } } $err = ($err)?$err:'优惠券码错误'; } return CommonFun::returnFalse($err); } //获取用户在商家下优惠券 public function actionMerchant($merchant_id){ if(intval($merchant_id) == 0){ return CommonFun::returnFalse('数据错误'); } $sql = "select c.id as id,mc.id as mcid, count(mc.coupon_id) as mcnum from sf_coupons c,sf_members_coupon mc where c.id=mc.coupon_id and c.merchant_id={$merchant_id} and mc.member_id={$this->member_id} group by mc.coupon_id"; $data = Yii::$app->db->createCommand($sql)->queryAll(); return CommonFun::returnSuccess($data); } }<file_sep>/modules/member/controllers/AttractController.php <?php namespace app\modules\member\controllers; /** * Created by PhpStorm. * User: zhongming * Date: 2018/4/4 下午9:42 */ use common\components\CommonFun; use common\models\MembersAttracts; use common\models\MerchantsAccount; use \Yii; use api\controllers\MemberBaseController; class AttractController extends MemberBaseController{ //招商信息 public function actionInfo(){ $data = []; $data['num'] = 0; $data['amount'] = 0; $data['audit'] = 0; $model = MembersAttracts::find() ->where('member_id=:id', [':id'=>$this->member_id]) ->all(); if($model){ $tmpAmount = 0; // $audit = 0; foreach ($model as $v){ if($v->status == MembersAttracts::STATUS_NORMAL){ $tmpAmount += $v->amount; } if($v->status == MembersAttracts::STATUS_AUDIT){ $data['audit']++; } if($v->status == MembersAttracts::STATUS_NORMAL){ $data['num']++; } } $data['amount'] = CommonFun::doNumber($tmpAmount); } return CommonFun::returnSuccess($data); } //列表 public function actionLists(){ $data = []; $query = MembersAttracts::find() ->with(['merchant', 'merchant.extends']); $data['total'] = $query->count(); $data['page_size'] = $this->pageSize; $data['page_num'] = ++$this->pageNum; $model = $query->where('member_id=:memberId and status=:status', [':memberId'=>$this->member_id, ':status'=>MembersAttracts::STATUS_NORMAL]) ->offset($this->offset) ->limit($this->pageSize) ->all(); $data['lists'] = []; if($model){ foreach ($model as $v){ $data['lists'][] = [ // 'merchant_amount' => CommonFun::doNumber($v->merchants_total_amount), // 'amount' => CommonFun::doNumber($v->amount), 'name' => $v->merchant->name, 'account' => $v->merchant->account, 'merchant_id' => $v->merchants_id, 'reg_date' => date("Y-m-d", $v->ctime), 'merchant_logo' => $v->merchant->extends->logo ]; } } return CommonFun::returnSuccess($data); } //招商关系添加 public function actionRelate(){ if($this->isPost){ $merchants_id = Yii::$app->request->post('merchants_id'); $model = MerchantsAccount::findOne(['id'=>$merchants_id]); if(!$model){ return CommonFun::returnFalse('current marchant is not found'); } //查询关系是否存在 $m = MembersAttracts::record($this->member_id, $merchants_id); if(is_string($m)){ return CommonFun::returnFalse($m); }else if(is_bool($m)){ return CommonFun::returnSuccess(); } } return CommonFun::returnFalse('member attract fail'); } }<file_sep>/modules/cart/controllers/DefaultController.php <?php namespace app\modules\cart\controllers; use Yii; use common\components\CommonFun; use common\models\Cart; use common\models\MerchantsProduct; use common\models\CommonModel; use common\models\ExchangePointProduct; use common\models\MerchantsProductSku; use common\models\ExchangeProductSku; use common\models\ExchangeProduct; use common\models\ExchangePointProductSku; use api\controllers\MemberBaseController; class DefaultController extends MemberBaseController { public function beforeAction($action) { parent::beforeAction($action); if ($this->isGet ) { return true; } $outPut = parent::check($action); if ($outPut === true) { return true; } } /** * 编辑购物车 * @author RTS 2018年4月7日 13:37:35 */ public function actionEdit(){ $id = $this->request->post('id',0); $model = Cart::findOne(['member_id' => $this->member_id,'id' => $id,'status' => CommonModel::STATUS_ACTIVE]); if(empty($model)){ return CommonFun::returnFalse('对应的数据错误,请稍候再试。'); } $op_type = $this->request->post('op_type',1); if($op_type == 2){ $model->status = CommonModel::STATUS_DELETE; }else{ $quantity = intval($this->request->post('quantity',0)); if(!empty($quantity)){ $model->quantity = $quantity; } $comment = $this->request->post('comment','xxx'); if($comment != 'xxx'){ $model->comment = $comment; } } $res = $model->save(); if($res){ return CommonFun::returnSuccess(); } return CommonFun::returnFalse('操作失败,请稍候再试。'.json_encode($model->getErrors())); } /** * 购物车列表 * @author rts 2018年4月7日 13:06:54 */ public function actionList(){ $condition = ['member_id' => $this->member_id,'status' => CommonModel::STATUS_ACTIVE]; $data = Cart::find()->where($condition)->orderBy('ctime desc')->asArray()->all(); return CommonFun::returnSuccess(['list' => $data]); } /** * 加入购物车 * @author RTS 2018年4月7日 10:34:17 */ public function actionAdd() { $type = intval($this->request->post('type',0)); $product_id = intval($this->request->post('product_id',0)); $quantity = intval($this->request->post('quantity',0)); $exchange_point_id = intval($this->request->post('exchange_point_id',0)); $sku_id = intval($this->request->post('sku_id',0)); $sku_json = $this->request->post('sku_json',''); $where = ['id' => $product_id,'status' => CommonModel::STATUS_ACTIVE]; $exchange_point_product_id = 0; if($type == 0){ $productInfo = MerchantsProduct::find()->where($where)->with(['images' => function($query){ $query->where(['status' => 1,'type' => 1]); }])->asArray()->one(); $stock = intval($productInfo['stock']); }else { $where = [ 'status' => CommonModel::STATUS_ACTIVE, 'product_id' => $product_id, 'exchange_point_id' => $exchange_point_id, ]; $info = ExchangePointProduct::findOne($where); if(empty($info)){ return CommonFun::returnFalse("兑换点:{$exchange_point_id},未能找到对应的商品ID:{$product_id},请稍候再试。"); } $exchange_point_product_id = $info['id']; $stock = intval($info['stock']); $where = [ 'status' => CommonModel::STATUS_ACTIVE, 'id' => $product_id, ]; $productInfo = ExchangeProduct::find()->where($where)->with(['images' => function($query){ $query->where(['status' => 1,'type' => 1]); }])->asArray()->one(); } if(empty($productInfo)){ return CommonFun::returnFalse('获取商品信息失败,请稍候再试。'); } $limit = intval($productInfo['limit']); $product_name = $productInfo['title']; if($quantity > $limit){ // return CommonFun::returnFalse("加入购物车数量:{$quantity}大于限购数:{$limit}。"); return CommonFun::returnFalse("商品当前购买次数已达上限,请选择其它商品!"); } $object_id = $type == 0 ? $productInfo['merchants_id'] : $exchange_point_id; $coin = $type == 0 ? 0 : intval($productInfo['coin']); $product_img = ''; if(!empty($productInfo['images'])){ $product_img = $productInfo['images'][0]['src']; } $market_price = $productInfo['market_price']; $price = $productInfo['platform_price']; if(!empty($sku_id)){ $where = [ 'status' => CommonModel::STATUS_ACTIVE, 'product_id' => $product_id, 'id'=> $sku_id, ]; if($type == 0){ $skuInfo = MerchantsProductSku::findOne($where); if(empty($skuInfo)){ return CommonFun::returnFalse('获取SKU信息失败,请稍候再试。'); } $stock = intval($skuInfo['stock']); }else{//兑换点获取 库存 需要在点位上去取 $info = ExchangePointProductSku::findOne(['point_product_id' => $exchange_point_product_id,'product_sku_id' => $sku_id,'status'=> CommonModel::STATUS_ACTIVE]); if(empty($info)){ return CommonFun::returnFalse('兑换点SKU获取失败,请稍候再试。'); } $stock = $info['stock']; $skuInfo = ExchangeProductSku::findOne($where); if(empty($skuInfo)){ return CommonFun::returnFalse('获取SKU信息失败,请稍候再试。'); } } $price = floatval($skuInfo['price']); $market_price = floatval($skuInfo['old_price']); } if($quantity > $stock){ return CommonFun::returnFalse("加入购物车数量:{$quantity}大于库存数:{$stock}。"); } $model = new Cart(); $model->product_id = $product_id; $model->member_id = $this->member_id; $model->object_id = $object_id; $model->product_name = $product_name; $model->product_img = $product_img; $model->limit = $limit; $model->quantity = $quantity; $model->market_price = $market_price; $model->price = $price; $model->coin = $coin; $model->type = $type; $model->sku_id = $sku_id; $model->sku_json = $sku_json; $res = $model->save(); if($res){ return CommonFun::returnSuccess(['id' => $model->id]); } return CommonFun::returnFalse('操作失败,请稍候再试。'.json_encode($model->getErrors())); } } <file_sep>/modules/activity/controllers/PosterController.php <?php namespace app\modules\activity\controllers; use \Yii; use common\components\CommonFun; use common\models\CommonModel; use common\models\ActivityPoster; use api\controllers\MemberBaseController; class PosterController extends MemberBaseController{ /** * 获取列表 * @return unknown */ public function actionList(){ $lists = ActivityPoster::getList(['put_status' => CommonModel::STATUS_ACTIVE],$this->pageInfo,'sort desc',false,['id','name','img']); return CommonFun::returnSuccess(['rows' => $lists['data'],'counts' => $lists['count']]); } /** * 获取详情 * @return unknown */ public function actionDetails($id = 0){ $id = intval($id); $res = ActivityPoster::getOne(['id' => $id],true); if($res){ $res['qrcode_img'] = ActivityPoster::createQr($this->member_id,$res['img']); } return CommonFun::returnSuccess($res); } }<file_sep>/modules/member/controllers/RecommendController.php <?php namespace app\modules\member\controllers; /** * Created by PhpStorm. * User: zhongming * Date: 2018/4/5 下午9:44 */ use common\components\CommonFun; use common\models\Config; use common\models\MembersAttracts; use api\controllers\BaseController; use common\models\MerchantsAccount; use common\models\Recommends; use common\models\WeixinFans; use \Yii; use common\models\Members; use abei2017\wx\Application; use common\models\OssImg; use api\controllers\MemberBaseController; class RecommendController extends MemberBaseController{ //推荐信息 public function actionInfo(){ $data = []; $data['num'] = 0;//Recommends::getCount(Recommends::TYPE_MEMBER, $this->member_id); $data['amount'] = 0; $data['qrcode'] = ''; $query = Recommends::find() ->where('type=:type and obj_id=:oid and status=1',[':oid'=>$this->member_id, ':type'=>Recommends::TYPE_MEMBER]); $data['num'] = $query->count(); $model = $query->all(); if($model){ $tmpAmount = 0; foreach ($model as $v){ $tmpAmount += $v->amount; } $data['amount'] = CommonFun::doNumber($tmpAmount); } return CommonFun::returnSuccess($data); } //列表 public function actionLists(){ $data = []; $query = Recommends::find() ->where('type=:type and obj_id=:oid and status=1',[':oid'=>$this->member_id, ':type'=>Recommends::TYPE_MEMBER]); $data['total'] = $query->count(); $data['page_size'] = $this->pageSize; $data['page_num'] = ++$this->pageNum; $model = $query->offset($this->offset)->limit($this->pageSize)->orderBy('ctime desc')->all(); $data['lists'] = []; if($model){ foreach ($model as $v){ $data['lists'][] = [ 'member_id' => substr_replace($v->member_id, '****', 2, 3), 'total_amount' => CommonFun::doNumber($v->total_amount), 'amount' => CommonFun::doNumber($v->amount), 'ctime' => date('Y-m-d', $v->ctime), 'coin' => $v->recommend_coin, ]; } } return CommonFun::returnSuccess($data); } // //用户二维码 // public function actionQrcode(){ // $member = Members::findOne($this->member_id); // $data['url'] = ''; // if($member){ // if($member->recommend_qrcode){ // $data['url'] = $member->recommend_qrcode; // return CommonFun::returnSuccess($data); // }else{ // //获取推荐二维码 // $wechat = \Yii::$app->wechat; // $qrcode = $wechat->createQrCode([ // 'action_name' => 'QR_LIMIT_STR_SCENE', // 'action_info' => ['scene' => ['scene_str'=>'recommend:member_'.$member->id]] // ]); // $imgRawData = $wechat->getQrCodeUrl($qrcode['ticket']); // $member->recommend_qrcode = $imgRawData; // if($member->save()){ // return CommonFun::returnSuccess($data); // } // } // } // return CommonFun::returnFalse('member qrcode fail'); // } /** * 微信二维码 * @param int $type 0:服务号 1:小程序 */ public function actionQrcode($type = 0){ $data['url'] = ''; $query = WeixinFans::find() ->where('member_id=:mid', [':mid'=>$this->member_id]); if($type == 1){ $query->andWhere(['=', 'is_mini', 1]); }else{ $query->andWhere(['=', 'is_mini', 0]); } $weixinFans = $query->one(); if($weixinFans){ if($weixinFans->qrcode){ $data['url'] = $weixinFans->qrcode; return CommonFun::returnSuccess($data); }else{ if($type == 0){ //普通服务号 //获取推荐二维码 $wechat = \Yii::$app->wechat; $qrcode = $wechat->createQrCode([ 'action_name' => 'QR_LIMIT_STR_SCENE', 'action_info' => ['scene' => ['scene_str'=>'recommend:member_'.$this->member_id]] ]); $imgRawData = $wechat->getQrCodeUrl($qrcode['ticket']); $weixinFans->qrcode = $imgRawData; if($weixinFans->save()){ $data['url'] = $weixinFans->qrcode; return CommonFun::returnSuccess($data); } }else if($type == 1){ $config = Config::getConfigs('basic'); $conf = \Yii::$app->params['wxmini']; $app = new Application(['conf'=>$conf]); $qrcode = $app->driver("mini.qrcode"); $result = $qrcode->forever('pages/index/index?suid='.$this->member_id, $extra = ['is_hyaline'=>true]); $name = './uploads/qrcode-uid-'.$this->member_id.'.png'; file_put_contents($name, $result); $url = OssImg::upload($name); if($url) { @unlink($name); $weixinFans->qrcode = $config['oss_host'].$url; if($weixinFans->save()){ $data['url'] = $weixinFans->qrcode; return CommonFun::returnSuccess($data); } } } return CommonFun::returnFalse('获取二维码错误'); } } return CommonFun::returnFalse('微信信息不存在'); } }<file_sep>/modules/activity/controllers/GridController.php <?php namespace app\modules\activity\controllers; use common\components\CommonFun; Use api\controllers\BaseController; use common\extend\OSS\Common; use common\models\Config; use common\models\MembersCurrency; use common\models\MembersFinances; use common\models\MembersRotaryGirdRecord; use common\models\MembersRotaryGridAddress; use common\models\MembersSignin; use common\models\MembersSigninRecord; use common\models\RotaryGridItems; use common\models\MembersAddress; use api\controllers\MemberBaseController; /** * Default controller for the `activity` module */ class GridController extends MemberBaseController { /** * Renders the index view for the module * @return string */ public function actionLists() //奖品列表 { $model = RotaryGridItems::find() ->select('id,name,type,image,position') ->where('active = 1') ->orderBy('position asc') ->limit(8) ->asArray() ->all(); return CommonFun::returnSuccess($model); } public function actionNumber(){ $number = MembersRotaryGirdRecord::getNumbers($this->member_id); return CommonFun::returnSuccess($number); } public function actionStart(){ if($this->isPost){ $config = Config::getConfigs('luckygrid'); $number = MembersRotaryGirdRecord::getNumbers($this->member_id); if($number['signin'] > 0){ $category = 0; }else{ $category = 1; } if($number['signin'] == 0 && $number['coin'] == 0){ //次数用完 return CommonFun::returnFalse('抽奖次数不足'); } if($category == 1){ //使用省币抽奖 //验证省币是否够 $model = MembersFinances::findOne(['member_id'=>$this->member_id]); $coin = CommonFun::doNumber($model->coin); if($coin < $config['coin']){ return CommonFun::returnFalse('省币不足抽奖'); } //扣除省币 MembersCurrency::record($this->member_id, MembersCurrency::TYPE_REDUCE, MembersCurrency::SOURCE_ROTARY_GRID_USE, '', $config['coin']); } //开始抽 $model = RotaryGridItems::find() ->select('id,name,rate,coin,type,coupon_id') ->where('active = 1') ->orderBy('rate asc') ->limit(8) ->asArray() ->all(); $data = []; $itemId = $this->getRand($model); foreach ($model as $v){ if($v['id'] == $itemId){ $data = $v; } } if($data){ //记录抽奖 $model = new MembersRotaryGirdRecord(); $model->member_id = $this->member_id; $model->category = $category; $model->item_id= $data['id']; $model->type = $data['type']; $model->title = $data['name']; $model->coin = $data['coin']; $model->coupon_id = $data['coupon_id']; if($model->type == RotaryGridItems::TYPE_PRODUCT){ $model->is_use = 0; }else{ $model->is_use = 1; } $model->ctime = time(); $model->save(); if($model->type == RotaryGridItems::TYPE_COIN && $model->coin > 0){ //省币 //加省币 MembersCurrency::record($this->member_id, MembersCurrency::TYPE_INCR, MembersCurrency::SOURCE_ROTARY_GRID, '', $model->coin); }else if($model->type == RotaryGridItems::TYPE_COUPON){ //优惠券,目前不存在 }else if($model->type == RotaryGridItems::TYPE_PRODUCT){ //实物,发送短信 } //返回ID unset($data['rate']); } return CommonFun::returnSuccess($data); } } //抽奖算法 private function getRand($proArr){ $arr = []; $proSum = 100000; foreach ($proArr as $k=>$v){ if($k == 0){ if($v['rate'] == 0){ $left = 0; }else{ $left = 1; } }else{ $left = ($proArr[$k-1]['rate'] * 1000)+1; } $right = $proArr[$k]['rate'] * 1000; if(($k+1) == count($proArr)){ $right = $proSum; } $arr[$k] = [ 'id' => $v['id'], 'rate' => $v['rate'], 'left' => $left, 'right' => $right ]; } $randNum = mt_rand(1, $proSum); foreach($arr as $v){ if($randNum >= $v['left'] && $randNum <= $v['right']){ return $v['id']; } } } //中奖名单 public function actionNotice(){ $data = []; $model = MembersRotaryGirdRecord::find() ->select('member_id, title') ->where("title <> '谢谢参与'") ->orderBy('ctime desc') ->limit('20') ->asArray() ->all(); if($model){ foreach ($model as $k=>$v){ $data[$k] = $v; $data[$k]['member_id'] = substr_replace($v['member_id'], '****', 2, 3); } } return CommonFun::returnSuccess($data); } //获取用户转盘抽奖记录 public function actionRecord(){ $query = MembersRotaryGirdRecord::find() ->where('member_id=:mid', [':mid'=>$this->member_id]); $count = $query->count(); $data = $query ->orderBy('ctime desc') ->offset($this->offset) ->limit($this->pageSize) ->asArray() ->all(); if($data){ foreach ($data as $k => $item){ $data[$k]['ctime'] = date("Y-m-d H:i:s", $item['ctime']); } } return CommonFun::returnSuccess(['total' => $count,'list' => $data,'page_size' => $this->pageSize,'page_num' => ++$this->pageNum]); } //获取获奖商品详情 public function actionRecordView($id){ $model = MembersRotaryGirdRecord::find() ->where('id=:id',[':id'=>$id]) ->with('address') ->asArray() ->one(); return CommonFun::returnSuccess($model); } //设置收货地址 public function actionSettingAddress(){ if($this->isPost) { $id = \Yii::$app->request->post('id'); //取默认收货地址 $address = MembersAddress::getDefaultAddress($this->member_id); if(!$address){ return CommonFun::returnFalse('未找到默认地址'); } $model = MembersRotaryGridAddress::findOne(['r_id'=>$id]); if(!$model){ $model = new MembersRotaryGridAddress(); } $model->r_id = $id; $model->member_id = $this->member_id; $model->name = $address['name']; $model->mobile = $address['mobile']; $model->area = $address['area']; $model->address = $address['address']; $model->status = 1; if($model->save()){ return CommonFun::returnSuccess(); } return CommonFun::returnFalse('系统错误'); } } } <file_sep>/controllers/MemberBaseController.php <?php namespace api\controllers; use Yii; use common\models\WeixinFans; use common\components\CommonFun; class MemberBaseController extends BaseController { //public $member_id; public function init() { parent::init(); $this->member_id = Yii::$app->request->headers->get('uid'); $this->openid = Yii::$app->request->headers->get('openid'); if(!$this->member_id){ if($this->openid){ $this->weixin = WeixinFans::getInfo($this->openid); } $this->member_id = $this->weixin['member_id']; } if(!$this->member_id){ return CommonFun::returnFalse('Not login'); } } } <file_sep>/controllers/CityController.php <?php namespace api\controllers; use common\models\OpenCity; use common\components\CommonFun; use yii\web\Controller; class CityController extends BaseController { //开通城市 public function actionOpenCitys(){ $citys = OpenCity::getCitys(); $data = []; if($citys){ foreach ($citys as $k=>$item){ $data[] = [ 'id'=>$item['id'], 'name'=>$item['name'], 'code'=>$item['code'], 'longitude' => $item['longitude'], 'latitude' => $item['latitude'] ]; } } return CommonFun::returnSuccess($data); } } <file_sep>/modules/mall/controllers/ProductController.php <?php namespace app\modules\mall\controllers; use Yii; use api\controllers\BaseController; use common\components\CommonFun; use common\models\Category; use common\models\MerchantsProduct; use common\models\CommonModel; use common\models\MerchantsProductSku; use common\models\MerchantsProductComment; use callmez\wechat\sdk\mp\Merchant; use common\models\MerchantsAccount; use common\models\MembersFavorite; class ProductController extends BaseController { /** * 商城商品 * @author RTS 2018年4月1日 13:52:01 */ public function actionIndex() { $categoryId = intval(CommonFun::getParams('category_id',0)); $merchantsId = intval(CommonFun::getParams('merchants_id',0)); $key = Yii::$app->request->get('key',''); $query = MerchantsProduct::find(); $query->where(['status' => CommonModel::STATUS_ACTIVE,'product_status' => MerchantsProduct::STATUS_PUT_ON]); if(!empty($categoryId)){ $query->andWhere(['category_id' => $categoryId]); } if(!empty($merchantsId)){ $query->andWhere(['merchants_id' => $merchantsId]); } if(!empty($key)){ $query->andWhere(['like','title',$key]); } $order = CommonFun::getParams('order_by','ctime'); $sort = Yii::$app->request->get('sort',1); $sort = $sort == 1 ? ' desc ':' asc '; $order.= $sort; $query->orderBy($order); $query->select('title,sub_title,platform_price,market_price,brand_id,category_id,merchants_id,id,stock'); $query->with(['category' => function ($query){ $query->select('id','name'); },'merchants' => function ($query){ $query->select = ['id','name','is_platform']; },'brand'=>function ($query){ $query->select = ['id','name']; },'images'=>function ($query){ $query->where(['type' => 1]); }]); $total = $query->count(); $query->limit($this->pageSize)->offset($this->offset); $data = $query->asArray()->all(); return CommonFun::returnSuccess(['total' => $total,'list' => $data,'page_size'=>$this->pageSize,'page_num' => ++$this->pageNum]); } /** * 商城商品详情 * @author RTS 2018年4月2日 10:18:38 */ public function actionBasic($id = 0) { $query = MerchantsProduct::find(); $query->where(['id' => $id,'status'=>1,'product_status' => MerchantsProduct::STATUS_PUT_ON]); $query->select('title,sub_title,platform_price,market_price,id,limit,stock,merchants_id'); $query->with(['images'=>function ($query){ $query->where(['type' => 2]); },'content'=>function ($query){ $query->select = ['mobile_details']; }]); $data = $query ->asArray()->one(); return CommonFun::returnSuccess($data); } /** * 获取商品SKU * @param number $id * @author RTS 2018年4月3日 20:45:37 */ public function actionSku($id = 0){ $query = MerchantsProductSku::find(); $query->where(['product_id' => $id,'status'=> CommonModel::STATUS_ACTIVE]); $data = $query->asArray()->all(); if(empty($data)){ return CommonFun::returnSuccess(); } $tmp = $data[0]['name']; if(empty($tmp)){ return CommonFun::returnSuccess(); } $skuTps = explode(',', $data[0]['name']); foreach ($skuTps as $k=>$item){ $sku_groups[$item] = MerchantsProductSku::doSku($data,$k); } return CommonFun::returnSuccess(['sku_groups' => $sku_groups]); } /** * 获取sku对应的价格 * @param string $key * @param number $id * @author RTS 2018年4月3日 20:45:46 */ public function actionSkuPrice($key = '',$id = 0){ $query = MerchantsProductSku::find(); $query->where(['product_id' => $id,'item' => $key,'status'=> CommonModel::STATUS_ACTIVE]); $data = $query->asArray()->one(); return CommonFun::returnSuccess($data); } /** * 获取商品评价 * @param number $id */ public function actionComments($id = 0){ $query = MerchantsProductComment::find(); $query->select = ['score','content','ctime','member_id']; $query->where(['product_id' => $id,'display' => 1,'status'=> CommonModel::STATUS_ACTIVE]); $query->orderBy('ctime desc'); $query->with(['member'=>function ($query){ $query->select = ['nickname','id']; }]); $total = $query->count(); $query->orderBy('ctime desc')->limit($this->pageSize)->offset($this->offset); $data = $query->asArray()->all(); return CommonFun::returnSuccess(['total' => $total,'list' => $data,'page_size'=>$this->pageSize,'page_num' => ++$this->pageNum]); } /** * 获取商品商户信息 * @param number $id */ public function actionMerchants($merchants_id = 0){ $query = MerchantsAccount::find(); $query->select = ['name','id']; $query->where(['id' => $merchants_id]); $query->with(['extends'=>function ($query){ $query->select = ['logo','id']; }]); $data = $query->asArray()->one(); if(!empty($data)){ $query = MerchantsProduct::find(); $query->where(['merchants_id' => $merchants_id,'status'=> CommonModel::STATUS_ACTIVE,'product_status' => MerchantsProduct::STATUS_PUT_ON]); $sell_counts = $query->count('id'); $focus = MembersFavorite::getCounts($merchants_id,MembersFavorite::TYPE_MERCHANTS); $data['feedback_rate'] = '100%'; $data['focus'] = $focus; $data['sell_counts'] = $sell_counts; } return CommonFun::returnSuccess($data); } } <file_sep>/modules/order/controllers/DefaultController.php <?php namespace app\modules\order\controllers; use common\extend\OSS\Common; use common\models\AlipayFans; use common\models\MembersCoupon; use common\models\MiniTemplateinfo; use common\models\pay\AliMiniService; use common\models\pay\AlipayService; use common\models\pay\WxMiniService; use Yii; use api\controllers\BaseController; use common\components\CommonFun; use common\models\Cart; use common\models\MerchantsProduct; use common\models\CommonModel; use common\models\ExchangePointProduct; use common\models\MerchantsProductSku; use common\models\ExchangeProductSku; use common\models\MembersAddress; use common\models\Orders; use common\components\enum\OrderEnum; use callmez\wechat\sdk\mp\Merchant; use common\models\MerchantsAccount; use common\models\ExchangePoint; use common\models\ExchangeProduct; use PetstoreIO\Order; use yii\helpers\ArrayHelper; use common\models\pay\WxPayService; use common\models\Members; use common\models\OrdersPay; use common\models\MembersCurrency; use common\components\FinanceSign; use common\models\OrdersComments; use common\models\MembersFinances; use api\controllers\MemberBaseController; class DefaultController extends MemberBaseController { public function beforeAction($action) { parent::beforeAction($action); if ($this->isGet ) { return true; } $outPut = parent::check($action); if ($outPut === true) { return true; } } /** * 购物车生成订单 * @author RTS 2018年4月8日 09:02:52 * update: 2018年8月8日 source 添加订单来源(微信/小程序/支付宝...) see OrderEnum::PAY_TYPE */ public function actionAddForCart() { $ids = $this->request->post('id',''); $address_id = intval($this->request->post('address_id',0)); $address_info = $this->checkAddressInfo($address_id); $idArr = explode(',', $ids); $query = Cart::find()->where(['in' , 'id' , $idArr]); $query->andWhere(['status' => 1,'member_id' => $this->member_id]); $data = $query->all(); if(empty($data)){ return CommonFun::returnFalse('对应的数据错误,请稍后再试。'); } $return = []; $orderModel = new Orders(); foreach ($data as $item){ $order = []; $order['type'] = $item['type'] + 1; $order['member_id'] = $item['member_id']; $order['product_id'] = $item['product_id']; $order['order_obj_id'] = $item['object_id']; $order['title'] = $item['product_name']; $order['image'] = $item['product_img']; $order['product_amount'] = $item['quantity'] * $item['price']; $order['product_coin'] = $item['quantity'] * $item['coin']; $order['comment'] = $item['comment']; $order['shipping_fee'] = floatval(CommonFun::getArrayValue(Yii::$app->params['basic'],'shipping_fee',0));//配送费用 $order['order_amount'] = $order['product_amount'] + $order['shipping_fee']; $order['order_coin'] = $order['product_coin']; $order['shipping_type'] = OrderEnum::SHIPPING_TYPE_PLATFROM; $order['shipping_name'] = OrderEnum::$SHIPPING_TYPE[OrderEnum::SHIPPING_TYPE_PLATFROM]; $source = ($this->request->post('source'))?$this->request->post('source'):0; $order['pay_type'] = $source; $order['pay_name'] = OrderEnum::$PAY_TYPE[$source]; $product_info = [ 'product_id' => $item['product_id'], 'product_name' => $item['product_name'], 'market_price' => $item['market_price'], 'platfrom_price' => $item['price'], 'platfrom_coin'=> $item['coin'], 'number' => $item['quantity'], 'sku_ids' => $item['sku_id'], 'sku_json' => $item['sku_json'], 'status' => 1 ]; $orderId = 0; $cache_name = $this->member_id.'_'.$item['product_id'].'_'.$item['sku_id'].'_'.$item['object_id'].'_'.$order['type']; $res = $orderModel->create($order,$product_info,$address_info,$orderId,$cache_name); if($res === true){ $cache_value = intval(CommonFun::getCache($cache_name)); $cache_value = CommonFun::doNumber($cache_value,$item['quantity'],'+'); CommonFun::setCache($cache_name,$cache_value,2); $res = $orderId; } $return[] = [$item['id'] => $res]; if($orderId > 0){ $item->status = CommonModel::STATUS_DELETE; $item->save(); } //sleep(1); //TODO member_coin 订单返用户省币 shipping_type 配送方式(自提/商家配送/平台配送/其它) shipping_name 配送名称 } return CommonFun::returnSuccess($return); } /** * 直接结算生成订单 * @author RTS 2018年4月8日 14:23:11 * update: 2018年8月8日 source 添加订单来源(微信/小程序/支付宝...) see OrderEnum::PAY_TYPE */ public function actionAddForSettlement() { $money = floatval($this->request->post('money',0.01)); $merchants_id = intval($this->request->post('merchants_id',0)); $comment = $this->request->post('comment',''); $res = MerchantsAccount::find()->where(['id' => $merchants_id])->select('id')->with(['extends' => function ($q){ $q->select = ['id','logo']; }])->asArray()->one(); if(empty($res)){ return CommonFun::returnFalse('商户信息错误,请稍候再试。'); } $orderModel = new Orders(); $order['type'] = OrderEnum::TYPE_ONLINEOFF_PAY; $order['member_id'] = $this->member_id; $order['product_id'] = 0; $order['order_obj_id'] = $merchants_id; $order['title'] = '结算订单'; $order['image'] = CommonFun::getArrayValue($res['extends'],'logo'); $order['product_amount'] = $money; $order['product_coin'] = 0; $order['comment'] = $comment; $order['member_coin'] = 0;//订单返用户省币 $order['shipping_fee'] = 0;//配送费用 $order['order_amount'] = CommonFun::doNumber($money, $order['shipping_fee'], '+'); $order['order_coin'] = $order['product_coin']; $order['shipping_type'] = OrderEnum::SHIPPING_TYPE_SELF; $order['shipping_name'] = OrderEnum::$SHIPPING_TYPE[OrderEnum::SHIPPING_TYPE_SELF]; $source = ($this->request->post('source'))?$this->request->post('source'):0; $order['pay_type'] = $source; $order['pay_name'] = OrderEnum::$PAY_TYPE[$source]; $orderId = 0; $res = $orderModel->create($order,[],[],$orderId); CommonFun::log([$order,$res, $orderId],__FUNCTION__,'orders'); if($res === true){ $res = $orderId; return CommonFun::returnSuccess(['id' => $res]); } return CommonFun::returnFalse('生成订单失败,请稍候再试。'); } private function checkAddressInfo($address_id = 0){ $address_info = MembersAddress::find()->where(['id' => $address_id, 'member_id' => $this->member_id ])->asArray()->one(); if(empty($address_info)){ return CommonFun::returnFalse('地址信息错误,请稍后再试。'); } return $address_info; } /** * 兑换生成订单 * @author RTS 2018年4月8日 15:05:32 * update: 2018年8月8日 source 添加订单来源(微信/小程序/支付宝...) see OrderEnum::PAY_TYPE */ public function actionAddForExchange() { $product_info = $this->request->post('product_info',[]); $exchange_point_id = intval($this->request->post('exchange_point_id',0)); $comment = $this->request->post('comment',''); $return = []; $orderModel = new Orders(); foreach ($product_info as $info){ $pid = $info['pid']; $quantity = $info['quantity']; $item = ExchangePointProduct::find()->where(['exchange_point_id' => $exchange_point_id,'product_id' => $pid,'status' => CommonModel::STATUS_ACTIVE])->select('id')->asArray()->one(); if(empty($item)){ return CommonFun::returnFalse('商品ID:'.$pid.'兑换点信息不存在,请稍候再试。'); } //update 2018.11.16 21:21 胡 //处理用户纯省币限制 $memberCoinNums = Orders::getMemberExchangeCoinNums($this->member_id, $exchange_point_id); if($memberCoinNums !== true){ return CommonFun::returnFalse($memberCoinNums); } $query = ExchangeProduct::find(); $condition = ['id' => $pid,'product_status' => ExchangeProduct::STATUS_PUT_ON,'status' => CommonModel::STATUS_ACTIVE]; $query->where($condition); $query->select = ['title','sub_title','coin','market_price','limit','platform_price','id']; $query->with(['images' => function($query){ $query->where(['type' => 1,'status' => 1]); $query->select = ['id','product_id','src']; }]); $item = $query->asArray()->one(); if(empty($item)){ return CommonFun::returnFalse('商品ID:'.$pid.'信息不存在,请稍候再试。'); } $order = []; $order['type'] = OrderEnum::TYPE_EXCHANGE_OFF; $order['member_id'] = $this->member_id; $order['product_id'] = $pid; $order['order_obj_id'] = $exchange_point_id; $order['title'] = $item['title']; $order['image'] = !empty($item['images']) ? $item['images'][0]['src'] : ''; $order['product_amount'] = $quantity * $item['platform_price']; $order['product_coin'] = $quantity * $item['coin']; $order['comment'] = $comment; $order['shipping_fee'] = 0;//配送费用 $order['order_amount'] = $order['product_amount'] + $order['shipping_fee']; $order['order_coin'] = $order['product_coin']; $order['shipping_type'] = OrderEnum::SHIPPING_TYPE_SELF; $order['shipping_name'] = OrderEnum::$SHIPPING_TYPE[OrderEnum::SHIPPING_TYPE_SELF]; $source = ($this->request->post('source'))?$this->request->post('source'):0; $order['pay_type'] = $source; $order['pay_name'] = OrderEnum::$PAY_TYPE[$source]; $product_info = [ 'product_id' => $pid, 'product_name' => $item['title'], 'market_price' => $item['market_price'], 'platfrom_price' => $item ['platform_price'], 'platfrom_coin' => $item ['coin'], 'number' => $quantity, 'sku_ids' => 0, 'sku_json' => '', 'status' => 1 ]; $orderId = 0; $res = $orderModel->create($order,$product_info,[],$orderId); if($res === true){ $res = $orderId; } $return[] = [$pid => $res]; } return CommonFun::returnSuccess($return); } /** * 订单列表 * @author RTS 2018年4月16日 10:28:11 */ public function actionList(){ $order_status = CommonFun::getParams('order_status',''); $type = CommonFun::getParams('type',''); $where = [ 'member_id' => $this->member_id, 'status' => 1, ]; if(!empty($type)){ if(in_array($type,[2,21])){ $type = [2,21]; } $where['type'] = $type; } $qwhere = Orders::getWhere($order_status); $where = ArrayHelper::merge($qwhere, $where); $res = Orders::getList($where,$this->pageSize,$this->offset); return CommonFun::returnSuccess([ 'total' => $res['total'], 'list' => $res['data'], 'page_size' =>$this->pageSize, 'page_num' => ++$this->pageNum ]); } /** * 订单详情 * @author RTS 2018年4月17日 09:20:38 */ public function actionDetails($id = 0){ $where = [ 'member_id' => $this->member_id, 'id' => $id, ]; $data = Orders::details ( $where ); return CommonFun::returnSuccess ( $data ); } /** * 支付订单 * * @param number $orderId * update: 2018年8月8日 OrderEnum::PAY_TYPE 按支付类型 返回不同支付场景 * create: 2018年9月1日 coupon_id 增加优惠券ID 用户可以使用优惠券抵扣 */ public function actionPay() { $data = []; $is_use_balance = $this->request->post ( 'is_use_balance',0 ); if($this->api_source == 'alimini'){ //支付宝过来的特殊处理,它的my.httpRequest POST是不支持数组模式 $data[0]['id'] = $this->request->post ( 'id', 0); $data[0]['coupon_id'] = $this->request->post ( 'coupon_id', 0); }else{ $data = $this->request->post ( 'data', []); } if (empty ( $data ) || ! is_array ( $data )) { return CommonFun::returnFalse ( '接收数据为空或格式错误' ); } $info = Members::getFinances ( $this->member_id ); if (empty ( $info )) { return CommonFun::returnFalse ( '用户财务信息获取失败。' ); } $totalMoney = 0; $totalCoin = 0; $totalBalanceAmount = 0; $trade_number = WxPayService::createTradeNumber (); $where = [ 'member_id' => $this->member_id, 'payment_status' => OrderEnum::PAY_STATUS_UNPAY ]; $orderArr = []; $userBalance = $info['balance']; //当同一个用户进来后 所有支付方式应该是相同的,所以取一个值 $pay_type = 0; $ids = []; //订单ID组 foreach ( $data as $item ) { $where ['id'] = $item ['id']; $is_use_coin = intval(CommonFun::getArrayValue($item,'is_use_coin',0)); $order = Orders::details ( $where ); if (empty ( $order )) { return CommonFun::returnFalse ( '订单:'.$item['id'].'数据获取失败。'); } if($order['order_status'] > OrderEnum::ORDER_STATUS_PAYING){ return CommonFun::returnFalse ( '订单:'.$item['id'].'状态已发生改变,请刷新页面后再试。'); } $pay_type = $order['pay_type']; // 2018.9.1 优惠券处理 $coupon = null; $coupon_id = (isset($item ['coupon_id'])?$item ['coupon_id']: 0); if($coupon_id > 0){ $coupon = MembersCoupon::find() ->where('is_use=0 and status=1 and id=:id', [':id'=>$coupon_id]) ->one(); if(!$coupon){ return CommonFun::returnFalse('优惠券已使用或者不存在'); } } if($coupon){ $order = Orders::findOne($item['id']); $order->coupons_id = $coupon->id; $order->coupons_category = $coupon->info->category; $order->coupons_name = $coupon->info->name; if($coupon->info->type == 1){ $order->coupons_amount = $order->order_amount * (1 - ($coupon->amount/10)); }else{ $order->coupons_amount = $coupon->amount; } $order->save(); //保存 } $coin = CommonFun::getArrayValue($order,'order_coin',0); $amount = $order['order_amount']; //如果有优惠券 先抵扣 下面余额部分不会超 if($coupon){ $amount = CommonFun::doNumber($amount, $order['coupons_amount'],'-'); } if($coin > 0){ if($is_use_coin){//用币则累计进去 $totalCoin = CommonFun::doNumber($totalCoin,$coin,'+'); }else{//不用则转换成金钱 $amount = CommonFun::doNumber($amount,($coin*1),'+'); $coin = 0; } } $pay_balance_amount = 0; $order_org_amount = $amount;//订单原始金额 if($is_use_balance == 1 && $userBalance > 0){//计算余额能抵扣多少 if($userBalance >= $amount ){//如果余额大于当前需要金额 则余额全部抵扣 $pay_balance_amount = $amount; $userBalance = CommonFun::doNumber($userBalance,$amount,'-'); $amount = 0; }else{//如果余额小于当前 则全部抵扣 $pay_balance_amount = $userBalance; $amount = CommonFun::doNumber($amount,$userBalance,'-'); $userBalance = 0; } } $payData [] = [ 'member_id' => $this->member_id, 'order_id' => $item['id'], 'order_sn' => $order['order_sn'], 'pay_type' => $order['pay_type'], //2018.8.8 添加 'trade_number' => $trade_number, 'pay_coin' => $coin,//需要根据是否愿意使用 'pay_balance_amount' => $pay_balance_amount,//余额需要支付多少 'pay_amount' => $amount,//如果不想用省币 此项目加上订单省币转换的RMB 'ctime' => date('Y-m-d H:i:s'), 'utime' => date('Y-m-d H:i:s'), ]; $ids[] = $item['id']; $orderArr[] = ['id' => $item ['id'],'order_sn' => $order['order_sn'],'order_org_amount' => $order_org_amount,'pay_coin' => $coin,'pay_balance_amount' => $pay_balance_amount,'pay_amount' => $amount]; $totalBalanceAmount = CommonFun::doNumber($totalBalanceAmount,$pay_balance_amount,'+'); $totalMoney = CommonFun::doNumber($totalMoney,$amount,'+'); } //微信小程序需要记录提交的formid if(in_array($pay_type, [OrderEnum::PAY_TYPE_WXMINI, OrderEnum::PAY_TYPE_ALIMINI])){ $formid = $this->request->post('formid', ''); if($formid){ $mini = new MiniTemplateinfo(); $mini->category = $pay_type==OrderEnum::PAY_TYPE_ALIMINI?2:1; $mini->type = MiniTemplateinfo::TYPE_ORDER; $mini->obj_id = join(',', $ids); $mini->member_id = $this->member_id; $mini->form_id = $formid; $mini->ctime = time(); $mini->is_send = 0; $mini->send_time = 0; $mini->openid = $this->openid; $mini->save(); } } if($totalCoin > 0 && $info['coin'] < $totalCoin){ return CommonFun::returnFalse("您的省币:{$info['coin']}不足以支付当前订单需要的省币:{$totalCoin}"); } if($totalBalanceAmount > 0 && $totalBalanceAmount > $info['balance']){ return CommonFun::returnFalse("您的余额:{$info['balance']}不足以支付当前订单需要的余额:{$totalBalanceAmount}"); } $totalWXPayMoney = $totalMoney; if($totalWXPayMoney == 0){//不需要额外三方支付 则直接扣除余额+省币 if($totalCoin == 0 && $totalBalanceAmount == 0 ){ return CommonFun::returnFalse("支付失败,需扣除金额:{$totalMoney},省币:{$totalCoin},请稍候再试。"); } foreach ($orderArr as $item){ $res = MembersFinances::usePayment($this->member_id,$item['pay_balance_amount'],$item['pay_coin'],$item ['id']); if($res !== true){ return CommonFun::returnFalse("支付存在失败:{$res}"); } $where ['id'] = $item ['id']; $payInfo = [ 'pay_coin' => $item['pay_coin'], 'pay_amount' => $item['order_org_amount'], 'pay_balance' => $item['pay_balance_amount'], 'pay_third_amount' => 0,//第三方支付为0 ]; Orders::operation($where,6,'用户',$payInfo); } return CommonFun::returnSuccess(['is_pay' => 0, 'is_wx_pay' => 0]); //is_wx_pay 将在后续版本中作废 } /** * 2018年8月8日 新增 根据支付类型返回需要的第三方支付包 * $pay_type 使用这个来验证 */ $payRes = []; switch ($pay_type){ case OrderEnum::PAY_TYPE_WXMINI: //微信小程序 $payRes = WxMiniService::tradePub('支付'.Yii::$app->params['basic']['shop_name'].'订单',$totalWXPayMoney,$trade_number,'JSAPI','',$this->openid); break; case OrderEnum::PAY_TYPE_ALIPAY: //支付宝 $user_id = AlipayFans::getUserId($this->member_id); $payRes = AlipayService::tradePub('支付'.Yii::$app->params['basic']['shop_name'].'订单', $totalWXPayMoney, $trade_number, $user_id); break; case OrderEnum::PAY_TYPE_ALIMINI: //支付宝小程序 //获取用户UID $user_id = AlipayFans::getUserId($this->member_id); $payRes = AliMiniService::tradePub('支付'.Yii::$app->params['basic']['shop_name'].'订单', $totalWXPayMoney, $trade_number, $user_id); break; case OrderEnum::PAY_TYPE_WEIXIN: //默认为微信 default: $payRes = WxPayService::tradePub('支付'.Yii::$app->params['basic']['shop_name'].'订单',$totalWXPayMoney,$trade_number,'JSAPI','',$this->openid); break; } if($payRes === false){ return CommonFun::returnFalse("支付中心返回失败,请稍候再试。"); } //写入支付记录 $fields = ['member_id', 'order_id','order_sn', 'pay_type', 'trade_number','pay_coin','pay_balance_amount','pay_amount','ctime','utime']; $res = \Yii::$app->db->createCommand()->batchInsert(OrdersPay::tableName(), $fields, $payData)->execute(); if($res == 0){ return CommonFun::returnFalse("写入数据失败,请稍候再试。"); } return CommonFun::returnSuccess([ 'is_pay' => 1, 'is_wx_pay' => 1, 'wx_package' => $payRes, //后续版本作废 'package' => $payRes, 'total_money' => $totalWXPayMoney ]); } /** * 操作订单 * @param number $orderId */ public function actionOperation(){ $orderId = intval($this->request->post('id',0)); $type = intval($this->request->post('type',0)); $where = [ 'member_id' => $this->member_id, 'id' => $orderId, ]; $res = Orders::operation($where,$type); if($res !== true){ return CommonFun::returnFalse('操作失败:'.$res); } return CommonFun::returnSuccess(); } public function actionCommentsList($product_id = 0,$object_id = 0,$type = 0){ $where = [ 'status' => CommonModel::STATUS_ACTIVE, ]; if(!empty($product_id)){ $where['product_id'] = $product_id; } if(!empty($object_id)){ $where['object_id'] = $object_id; } if(!empty($type)){ $where['order_type'] = $type; } $query = OrdersComments::find(); $query->where($where); $query->orderBy('ctime desc'); $total = $query->count(); $query->with(['member' => function($query){ $query->select = ['nickname','id']; }]); $query->limit($this->pageSize)->offset($this->offset); $data = $query->asArray()->all(); return CommonFun::returnSuccess(['total' => $total,'list' => $data]); } /** * 提交评价 * @author RTS 2018年4月21日 13:43:46 */ public function actionCommentsAdd(){ $id = intval($this->request->post('id',0)); $content = $this->request->post('content',''); $score = intval($this->request->post('score',5)); $info = Orders::find()->where(['id' => $id,'member_id' => $this->member_id])->select('title,product_id,order_obj_id,type')->one(); if(empty($info)){ return CommonFun::returnFalse('未找到对应订单数据,请稍候再试'); } $model = new OrdersComments(); $model->member_id = $this->member_id; $model->product_id = $info['product_id']; $model->order_type = $info['type']; $model->title = $info['title']; $model->content =$content; $model->score = $score; $model->object_id = $info['order_obj_id']; $model->order_id = $id; $res = $model->save(); if($res){ return CommonFun::returnSuccess(); } return CommonFun::returnFalse('操作失败,请稍候再试。'); } /** * 查询订单支付情况 * @author RTS 2018年5月2日 09:40:29 */ public function actionQueryPayInfo($ids = ''){ if(empty($ids)){ return CommonFun::returnFalse('订单ID为空'); } $ids = explode(',', $ids); $return = []; $total_pay_coin = 0;//所有支付币 $total_pay_balance = 0;//所有的余额支付 $total_pay_amount = 0;//所有的第三方支付金额 $total_coin = 0;//获得所有的币 $total_coupon_amount = 0; //优惠券金额 $order_amount = 0;//订单总金额 $order_coin = 0;//订单总省币 $order_shipping_fee = 0;//订单运费 $point = null; //兑换点信息 foreach ($ids as $item){ if(empty($item)){ continue; } $info = Orders::find()->where(['id' => $item,'status' => CommonModel::STATUS_ACTIVE,'member_id' => $this->member_id])->asArray()->one(); if(empty($info)){ return CommonFun::returnFalse('订单id:'.$item.'获取数据失败,请稍候再试。'); } // $info = Orders::find()->where(['id' => $item,'status' => CommonModel::STATUS_ACTIVE])->asArray()->one(); if($info['type'] == OrderEnum::TYPE_ONLINEOFF_PAY){ //结算订单只有一单,返回当前兑换点 $tmp_point = ExchangePoint::findOne(['merchants_id'=>$info['order_obj_id']]); if($tmp_point){ $point = $tmp_point->toArray(); } } if($info['payment_status'] != OrderEnum::PAY_STATUS_PAYED){ return CommonFun::returnFalse('订单id:'.$item.'未支付,请稍候再试。'); } $payInfo = OrdersPay::findOne(['order_id' => $item,'pay_status' => 1]); if(!empty($payInfo)){ $info['pay_coin'] = $payInfo['pay_coin']; $info['pay_balance_amount'] = $payInfo['pay_balance_amount']; $info['pay_amount'] = $payInfo['pay_amount']; }else{ $info['pay_balance_amount'] = $info['pay_amount']; $info['pay_amount'] = 0;//没有第三方支付 则第三方支付为0 } $return['details'][$item] = [ 'pay_coin' => $info['pay_coin'], 'pay_amount' => $info['pay_amount'], 'pay_balance' => $info['pay_balance_amount'], 'coin' => $info['member_coin'], 'coupons_amount' => $info['coupons_amount'], 'order_amount' => $info['order_amount'], 'order_coin' => $info['order_coin'], 'shipping_fee' => $info['shipping_fee'] ]; $total_pay_coin = CommonFun::doNumber($total_pay_coin,$info['pay_coin'],'+'); $total_pay_balance = CommonFun::doNumber($total_pay_balance,$info['pay_balance_amount'],'+'); $total_pay_amount = CommonFun::doNumber($total_pay_amount,$info['pay_amount'],'+'); $total_coin = CommonFun::doNumber($total_coin,$info['member_coin'],'+'); $total_coupon_amount = CommonFun::doNumber($total_coupon_amount, $info['coupons_amount'],'+'); $order_amount = CommonFun::doNumber($order_amount, $info['order_amount'],'+'); $order_coin = CommonFun::doNumber($order_coin, $info['order_coin'],'+'); $order_shipping_fee = CommonFun::doNumber($order_shipping_fee, $info['shipping_fee'],'+'); } $return['total']['total_pay_coin'] = $total_pay_coin; $return['total']['total_pay_balance'] = $total_pay_balance; $return['total']['total_pay_amount'] = $total_pay_amount; $return['total']['total_coin'] = $total_coin; $return['total']['total_coupon_amount'] = $total_coupon_amount; $return['total']['order_amount'] = $order_amount; $return['total']['order_coin'] = $order_coin; $return['total']['order_shipping_fee'] = $order_shipping_fee; $return['point'] = $point; return CommonFun::returnSuccess($return); } } <file_sep>/modules/mall/controllers/CategoryController.php <?php namespace app\modules\mall\controllers; use api\controllers\BaseController; use common\components\CommonFun; use common\models\Category; class CategoryController extends BaseController { /** * 在线商城分类 * @author RTS 2018年4月1日 13:42:48 */ public function actionIndex() { $model = Category::getCategoryByCity(Category::TYPE_PRODUCT); return CommonFun::returnSuccess($model); } } <file_sep>/modules/activity/controllers/PagesController.php <?php namespace app\modules\activity\controllers; use common\components\CommonFun; Use api\controllers\BaseController; use common\models\ActivityPages; /** * Default controller for the `activity` module */ class PagesController extends BaseController { public function actionIndex($id){ if(intval($id) == 0){ return CommonFun::returnFalse('错误'); } $data = []; $model = ActivityPages::find()->where(['id'=>$id, 'active'=>1])->one(); if($model){ $data['name'] = $model->name; $data['url'] = $model->url; } return CommonFun::returnSuccess($data); } } <file_sep>/controllers/AdpController.php <?php namespace api\controllers; use common\extend\OSS\Common; use common\models\Adp; use common\components\CommonFun; use common\models\AdRecord; class AdpController extends BaseController { /** * 获取banner位 * @param string $pos */ public function actionBanner(){ $pos = CommonFun::getParams('pos', 'local'); $cid = 17; if($pos == 'local'){ $cid = 18; } return $this->actionAdps($cid); } /** * 获取广告位广告 * @param $id * @param int $type category|adp */ public function actionAdps($id = '', $type='category'){ if($type == 'category'){ $cid = intval($id); $adp = Adp::getCategoryAdps($cid, $this->city_id,$this->token,$this->openid); return CommonFun::returnSuccess($adp); }else{ $apid = intval($id); if($apid > 0){ $adp = Adp::getAdpLists($apid, $this->city_id,$this->token,$this->openid); }else{ $adp = []; } return CommonFun::returnSuccess($adp); } } } <file_sep>/modules/member/controllers/ProfileController.php <?php namespace app\modules\member\controllers; /** * Created by PhpStorm. * User: zhongming * Date: 2018/4/2 上午9:42 */ use common\components\CommonValidate; use common\models\MembersBanks; use common\models\WeixinFans; use gmars\sms\Sms; use \Yii; use api\controllers\BaseController; use common\components\CommonFun; use common\models\Members; use common\models\Alisms; use yii\db\Expression; use api\controllers\MemberBaseController; class ProfileController extends MemberBaseController{ //用户信息 public function actionInfo(){ $data = Members::getInfo($this->member_id, $this->api_source); return CommonFun::returnSuccess($data); } //用户昵称 post public function actionNickname(){ if($this->isPost){ $nickname = Yii::$app->request->post('nickname'); if($nickname && CommonFun::utf8_strlen($nickname) >= 2){ if($res = Members::updateNickname($this->member_id, $nickname)){ return CommonFun::returnSuccess($res); } } } return CommonFun::returnFalse('modified nickname fail'); } /** * 发送短信 * @author RTS 2018年4月27日 10:12:24 */ public function actionSendSms(){ if($this->isPost){ $mobile = Yii::$app->request->post('mobile'); $cv = new \common\components\SendSms(true); $res = $cv->verifyCode(Alisms::TYPE_MODIFIED_PASSWORD, $mobile); if($res == false){ return CommonFun::returnFalse('发送失败,请稍候再试。'); } return CommonFun::returnSuccess(); } } //修改手机号/帐号 public function actionAccount(){ if($this->isPost){ $mobile = Yii::$app->request->post('mobile'); $vercode = Yii::$app->request->post('vercode'); if(!CommonValidate::isMobile($mobile)){ CommonFun::returnFalse('mobile fail'); } $cv = new \common\components\SendSms(); if (!$cv->verifyValidate(Alisms::TYPE_MODIFIED_PASSWORD, (string)$mobile, $vercode)) { CommonFun::returnFalse('verifycode fail'); } $m = Members::findOne($this->member_id); if($m){ $m->mobile = $mobile; if($m->save()){ CommonFun::returnSuccess(); } } CommonFun::returnFalse('modified account/mobile fail.'); } } //修改性别 public function actionGender() { if ($this->isPost) { $sex = Yii::$app->request->post('sex'); if(array_key_exists($sex, Members::$GENDERS)){ $m = Members::findOne($this->member_id); if($m){ $m->sex = $sex; if($m->save()){ CommonFun::returnSuccess(); } } } } CommonFun::returnFalse('modified gender fail.'); } //修改地址 public function actionAddress() { if ($this->isPost) { $address = Yii::$app->request->post('address'); if(!empty($address) && CommonFun::utf8_strlen($address) >= 10){ $m = Members::findOne($this->member_id); if($m && $m->address != $address){ $m->address = $address; if($m->save()){ CommonFun::returnSuccess(); } } } } CommonFun::returnFalse('modified address fail.'); } //密码修改 public function actionPassword(){ if($this->isPost){ $types = [1,2,3]; //限定类型 1=登录密码|2=支付密码|3=提现密码 $type = Yii::$app->request->post('type'); $oldpassword = trim(Yii::$app->request->post('oldpassword')); $newpassword = trim(Yii::$app->request->post('newpassword')); if(!in_array($type, $types) || CommonFun::utf8_strlen($newpassword) < 6){ CommonFun::returnFalse('密码格式不正确'); } $m = Members::findOne($this->member_id); if($type != 1 && $m->loginpass == ''){ CommonFun::returnFalse('请先设置登录密码'); } // $oldpassword = md5($oldpassword.'<PASSWORD>'); if($m->loginpass){ if($m->loginpass != CommonFun::md5($oldpassword.$m->salt, 'member-loginpass')){ CommonFun::returnFalse('登录密码错误,请重新输入'); } } // $newpassword = md5($newpassword.'<PASSWORD>'); switch ($type){ case 1: $m->loginpass = CommonFun::md5($newpassword.$m->salt, 'member-loginpass'); break; case 2: $m->paypass = CommonFun::md5($newpassword.$m->salt, 'member-paypass'); break; case 3: $m->txpass = CommonFun::md5($newpassword.$m->salt, 'member-txpass'); break; } if($m->save()){ CommonFun::returnSuccess(); } } CommonFun::returnFalse('修改密码失败'); } //获取平台支持银行列表 public function actionOpenBanks() { $data = Yii::$app->params['bankList']; CommonFun::returnSuccess($data); } //提现银行列表 public function actionBanks() { $model = MembersBanks::find() ->select(new Expression("id, bank_name, account, account_name,bank_deposit, status, from_unixtime(ctime, '%Y-%m-%d') ctime")) ->where('member_id=:mid and status=1', [':mid'=>$this->member_id]) ->asArray() ->all(); // CommonFun::pp($model); // return $model; return CommonFun::returnSuccess($model); } //添加提现信息 public function actionNewBank() { if($this->isPost){ $bank_name = Yii::$app->request->post('bank_name'); $account_name = Yii::$app->request->post('account_name'); $account_number = Yii::$app->request->post('account_number'); $bank_deposit = Yii::$app->request->post('bank_deposit',''); if(!in_array($bank_name, Yii::$app->params['bankList'])){ CommonFun::returnFalse('bank name fail.'); } if(CommonFun::utf8_strlen($account_name) < 2){ CommonFun::returnFalse('account name fail.'); } if(CommonFun::utf8_strlen($account_number) < 10){ CommonFun::returnFalse('account number fail.'); } $model = new MembersBanks(); $model->member_id = $this->member_id; $model->bank_name = $bank_name; $model->account = $account_number; $model->account_name = $account_name; $model->bank_deposit = $bank_deposit; $model->status = 1; $model->ctime = time(); $model->save(); if($model->save()){ CommonFun::returnSuccess(); } } CommonFun::returnFalse('new bank fail.'); } //删除一个提现银行 public function actionDelBank(){ if($this->isPost){ $id = intval(Yii::$app->request->post('id')); $model = MembersBanks::findOne($id); if($model){ if($model->delete()){ CommonFun::returnSuccess(); } } } CommonFun::returnFalse('delete bank fail.'); } /** * 微信授权信息补全 * 此次 处理weixin_fans * members 表验证当前帐号是否是 "微信用户" or "alipay...." */ public function actionWeixinAccountPerform(){ $data = Yii::$app->request->post('data', ''); if($data){ $info = WeixinFans::getInfo($this->openid); if($info){ $info->nickname = $data['nickName']; $info->sex = $data['gender']; $info->headimgurl = isset($data['avatarUrl'])?urldecode(base64_decode($data['avatarUrl'])):''; $info->language = $data['language']; $info->country = $data['country']; $info->province = $data['province']; $info->city = $data['city']; if($info->save()){ $member = Members::findOne($this->member_id); if($member){ if($member->nickname == '微信用户' || strpos($member->nickname, 'alipay') == 0){ $member->nickname = $data['nickName']; $member->sex = $data['gender']; } $member->save(); } $me = Members::getInfo($this->member_id, 'miniprogram'); return CommonFun::returnSuccess($me); } return CommonFun::returnFalse($info->getErrors()); } } return CommonFun::returnFalse('无数据'); } }<file_sep>/modules/exchange/controllers/ProductController.php <?php namespace app\modules\exchange\controllers; use api\controllers\BaseController; use common\models\Category; use common\components\CommonFun; use common\models\ExchangePoint; use common\models\CommonModel; use common\models\ExchangePointProduct; use common\components\CommonFinance; use common\models\ExchangeProduct; use common\models\ExchangeProductContent; use common\models\ExchangeProductSku; use common\models\MerchantsProduct; use common\models\MerchantsProductSku; use common\models\ExchangePointProductSku; use yii\db\Expression; /** * Default controller for the `local` module */ class ProductController extends BaseController { /** * 获取商品列表 所有商品必须挂在兑换点上 * @param number $category_id 分类ID * @param number $point_id 兑换点ID */ public function actionIndex(){ $category_id = CommonFun::getParams('category_id',0); $brand_id = CommonFun::getParams('brand_id',0); $point_id = CommonFun::getParams('point_id',0); $order_by = CommonFun::getParams('order_by',' order,sf_exchange_product.ctime '); $sort = CommonFun::getParams('sort',1); $key = CommonFun::getParams('key',''); $tags = CommonFun::getParams('tags',''); $is_coin = CommonFun::getParams('iscoin',0); if(empty($point_id)){ //线上兑换点需要全国开放,定位有可能在其它城市, 如果定位城市有线上兑换点用线上的,如果没有拿总部的 //$this->region = '成都市'; $point_id = 1000001; $pointInfo = ExchangePoint::findOne(['city' => $this->region,'status' => CommonModel::STATUS_ACTIVE,'is_online' => 1]); if($pointInfo){ $point_id = $pointInfo['id']; // return CommonFun::returnFalse('兑换点信息错误,请稍候再试。'); } } $qurey = ExchangePointProduct::find(); $qurey->where(['exchange_point_id' => $point_id, 'sf_exchange_point_product.status'=>1]); if(!empty($tags)){ $qurey->andWhere(new Expression("FIND_IN_SET($tags, tags)")); } $qurey->select = ['sf_exchange_point_product.id as exp_p_id','tags','product_id','exchange_point_id','sf_exchange_point_product.stock']; $sort = $sort == 1 ? ' desc ':' asc '; if(!empty($order_by)){ $order_by .= $sort; if(CommonFun::startWith($order_by,'sf_exchange_point_product')){ $qurey->orderBy($order_by); $order_by = ''; } } $qurey->joinWith(['product' => function($qurey) use ($category_id,$order_by,$key,$sort,$brand_id, $is_coin){ $qurey->select = ['sf_exchange_product.id','brand_id','title','sub_title','coin','platform_price','limit','category_id','market_price']; $where = ['product_status' => ExchangeProduct::STATUS_PUT_ON]; $qurey->where($where); if(!empty($category_id)){ //查看分类是不是一级分类 $category = Category::getCategory($category_id); if($category){ if(count($category['child']) == 0){ $qurey->andWhere(['=', 'category_id', $category_id]); }else{ $ids = [$category_id]; foreach ($category['child'] as $v){ $ids[] = $v['id']; } $qurey->andWhere(['in', 'category_id', $ids]); } } } if(!empty($order_by)){ $qurey->orderBy($order_by); } if(!empty($key)){ $qurey->andWhere(['like','title',$key]); } if(!empty($brand_id)){ $qurey->andWhere(['brand_id' => $brand_id]); } //如果只需要纯省币 if($is_coin == 1){ $qurey->andWhere(['>', 'coin', 0]); $qurey->andWhere(['=', 'platform_price', 0]); } $qurey->with(['images'=>function ($qurey){ $qurey->where(['type' => 1]); }]); }]); $count = $qurey->count('exchange_point_id'); $qurey->limit($this->pageSize)->offset($this->offset); $data = $qurey->asArray()->all(); return CommonFun::returnSuccess(['total' => $count,'list' => $data,'page_size' => $this->pageSize,'page_num' => ++$this->pageNum]); } /** * 产品详情 * @param number $point_id * @param number $product_id */ public function actionDetails($point_id = 0,$product_id = 0){ $point = ExchangePointProduct::find(); $point->where(['product_id' => $product_id,'exchange_point_id' => $point_id]); $point->orderBy('status desc'); $model = $point->one(); // $model = ExchangePointProduct::findOne(['product_id' => $product_id,'exchange_point_id' => $point_id]); // CommonFun::pp($model); if(empty($model)){ return CommonFun::returnFalse('对应数据未能找到!'); } $condition = ['id' => $product_id,'product_status' => ExchangeProduct::STATUS_PUT_ON]; $query = ExchangeProduct::find(); $query->where($condition); $query->select = ['title','sub_title','coin','market_price','limit','platform_price','id']; $query->with(['images'=>function($query){ $query->where(['type' => 2,'status' => 1]); }]); $query->where($condition); $data = $query->asArray()->one(); if(empty($data)){ return CommonFun::returnFalse('对应数据未能找到!!'); } $data['stock'] = $model['stock']; $data['exp_p_id'] = $model['id']; $data['tags'] = $model['tags']; $data['status'] = $model['status']; //覆盖状态 return CommonFun::returnSuccess($data); } /** * 获取商品详情 * @param $product_id * @param $type 1手机端 2pc端 */ public function actionContent($product_id, $type = 1){ $query = ExchangeProductContent::find()->where(['product_id'=>$product_id]); if($type == 1){ $query->select('product_id, simple_desc, mobile_details'); }else{ $query->select('product_id, simple_desc, pc_details'); } $data = $query->one()->toArray(); return CommonFun::returnSuccess($data); } /** * 获取商品SKU 需要先在兑换点商品表获取主键 反查兑换点sku表 * @param number $id * @author RTS 2018年4月5日 18:37:52 */ public function actionSku($id = 0,$point_id = 0){ $data = ExchangePointProduct::find()->where(['product_id' => $id,'exchange_point_id' => $point_id,'status'=> CommonModel::STATUS_ACTIVE])->select('id')->one(); if(empty($data)){ return CommonFun::returnFalse('商品信息获取失败,请稍候再试。'); } $query = ExchangePointProductSku::find(); $query->where(['point_product_id' => $data['id'],'status'=> CommonModel::STATUS_ACTIVE]); $query->with(['sku'=>function($query){ $query->select = ['name','item','id']; $query->where = ['status' => 1]; }]); $data = $query->asArray()->all(); if(empty($data)){ return CommonFun::returnSuccess(); } if(empty($data[0]['sku'])){ return CommonFun::returnSuccess(); } $tmp = $data[0]['sku']['name']; $skuTps = explode(',', $tmp); foreach ($skuTps as $k=>$item){ $sku_groups[$item] = MerchantsProductSku::doSku($data,$k); } return CommonFun::returnSuccess(['sku_groups' => $sku_groups]); } /** * 获取sku对应的价格 * @param string $key * @param number $id * @author RTS 2018年4月3日 20:45:46 */ public function actionSkuPrice($key = '',$id = 0,$point_id = 0){ $query = ExchangeProductSku::find(); $key = strval($key); $query->where(['product_id' => $id,'item' => $key,'status'=> CommonModel::STATUS_ACTIVE]); //$query->select = ['']; $data = $query->asArray()->one(); if(empty($data)){ return CommonFun::returnFalse('数据获取失败,请稍候再试。'); } $skuId = $data['id']; $info = ExchangePointProduct::findOne(['product_id' => $id,'exchange_point_id' => $point_id,'status'=> CommonModel::STATUS_ACTIVE]); if(empty($info)){ return CommonFun::returnFalse('兑换点数据获取失败,请稍候再试。'); } $info = ExchangePointProductSku::findOne(['point_product_id' => $info['id'],'product_sku_id' => $skuId,'status'=> CommonModel::STATUS_ACTIVE]); if(empty($info)){ return CommonFun::returnFalse('兑换点SKU获取失败,请稍候再试。'); } $data['stock'] = $info['stock']; return CommonFun::returnSuccess($data); } } <file_sep>/controllers/PagesController.php <?php namespace api\controllers; use common\components\CommonFun; use common\models\PagesIndexArea; class PagesController extends BaseController { function actionIndex($id){ $model = PagesIndexArea::find() ->where('is_open=1 and id=:id', [':id'=>$id]) ->with('items') ->asArray() ->one(); CommonFun::returnSuccess($model); } } <file_sep>/modules/notify/controllers/AlipayController.php <?php namespace app\modules\notify\controllers; use common\models\pay\AliMiniService; use Yii; use common\components\CommonFun; use yii\web\Controller; use common\models\OrdersPay; use common\models\Orders; use common\models\MembersFinances; use common\components\enum\OrderEnum; class AlipayController extends Controller { //支付宝回调 public function actionPay(){ $notify_array = $_POST; // $notify_array = '{"gmt_create":"2018-09-29 11:36:09","charset":"UTF-8","seller_email":"<EMAIL>","subject":"支付省生活商城订单","sign":"<KEY>,"buyer_id":"2088202279261083","invoice_amount":"0.01","notify_id":"2018092900222113616061080508658231","fund_bill_list":"[{\"amount\":\"0.01\",\"fundChannel\":\"ALIPAYACCOUNT\"}]","notify_type":"trade_status_sync","trade_status":"TRADE_SUCCESS","receipt_amount":"0.01","buyer_pay_amount":"0.01","app_id":"2018090661290548","sign_type":"RSA2","seller_id":"2088131566758334","gmt_payment":"2018-09-29 11:36:15","notify_time":"2018-09-29 11:36:16","version":"1.0","out_trade_no":"1809T64DSVA7IQX3JSI13CDH545YOVHF","total_amount":"0.01","trade_no":"2018092922001461080581262710","auth_app_id":"2018090661290548","buyer_logon_id":"<EMAIL>","point_amount":"0.00"}'; // $notify_array = json_decode($notify_array, true); CommonFun::log ( "收到支付宝回调, 数据:" . json_encode ( $notify_array, JSON_UNESCAPED_UNICODE ), "alipay", "notify" ); // $pay_no = $notify_array['out_trade_no']; // $pays = AliMiniService::query($pay_no); if(($notify_array['trade_status'] == 'TRADE_FINISHED' OR $notify_array['trade_status'] == 'TRADE_SUCCESS')){ $trade_no = $notify_array ["trade_no"]; $data = OrdersPay::find ()->where ( [ 'trade_number' => $notify_array['out_trade_no'], 'status' => 1, 'pay_status' => 0 ] )->all(); $res = -1; if (! empty ( $data )) { foreach ( $data as $item ) { $res = MembersFinances::usePayment($item ['member_id'], $item['pay_balance_amount'], $item['pay_coin'], $item ['order_id'], $item['pay_amount']); if($res === true){ $totalPay = CommonFun::doNumber($item['pay_balance_amount'], $item['pay_amount'],'+'); $payInfo = [ 'pay_coin' => $item['pay_coin'], 'pay_amount' => $totalPay, 'pay_balance' => $item['pay_balance_amount'], 'pay_third_amount' => $item['pay_amount'], ]; $item->third_number = $trade_no; $item->pay_status = OrderEnum::PAY_STATUS_PAYED; $where ['id'] = $item ['order_id']; $res = Orders::operation ( $where, 6, '用户', $payInfo ); } $item->remark = $res; $item->save(false); } } CommonFun::log ( "处理结果:" . json_encode($res,JSON_UNESCAPED_UNICODE), "alipay", "notify" ); } echo 'success'; exit; } }
c922ccef21b910460996c25f61adaa0e98887f12
[ "Markdown", "PHP" ]
47
PHP
zhongmingX/sf-api
1d644f66616a6e1173f11529721fa04143fb0d13
f186bf552c6e8eb22b03ee4c2ec21b10492b7c55
refs/heads/master
<repo_name>aosborne17/OOP_Polymorphism<file_sep>/README.md ## Polymorphism In inheritance, the child class inherits the methods from the parent class. However, it is possible to modify a method in a child class that it has inherited from the parent class. <file_sep>/polymorphism.py class Bird: """ Polymorphism allows us to define the same methods in our parent class to our child class but the change the outcome of the method This is helpful if the action of the parent class is not exactly what we want for the child class """ def intro(self): print("There are many types of birds.") def flight(self): print("Most of the birds can fly but some cannot.") """ As we can see, we have the same method 'flight', but in the subclass it's action has been changed slightly to print something else. """ class sparrow(Bird): def flight(self): print("Sparrows can fly.") class ostrich(Bird): def flight(self): print("Ostriches cannot fly.")
03b79ef4c116fbc0572d176875b7edd7106ebb6f
[ "Markdown", "Python" ]
2
Markdown
aosborne17/OOP_Polymorphism
b253d9edac152fd3ac1d68df06b3cbc1521977b6
eae0035ce806eedf341487b2a1a799f5e4ca02f6
refs/heads/master
<repo_name>pkuong/ibm-analytics-engine-python<file_sep>/tests/library/cf/spaces_test.py from unittest import TestCase from mock import Mock, MagicMock from ibm_analytics_engine.cf.client import CloudFoundryAPI from ibm_analytics_engine.cf.spaces import Space class Space_Test(TestCase): def test(self): mock = Mock(spec=CloudFoundryAPI) mock._request = MagicMock() mock.api_endpoint = 'my_url' s = Space(mock) s.get_spaces() mock._request.assert_called_once_with(description='get_space', http_method='get', url='my_url/v2/spaces') def test_with_name(self): mock = Mock(spec=CloudFoundryAPI) mock._request = MagicMock() mock.api_endpoint = 'my_url' s = Space(mock) s.get_spaces('space_name') mock._request.assert_called_once_with(description='get_space', http_method='get', url='my_url/v2/spaces?q=name:space_name') <file_sep>/docs/example_scripts/cluster_status.py import time from ibm_analytics_engine.cf.client import CloudFoundryAPI from ibm_analytics_engine import IAE cf = CloudFoundryAPI(api_key_filename='your_api_key_filename') iae = IAE(cf_client=cf) while True: status = iae.status(cluster_instance_guid='12345-12345-12345-12345') if status == 'succeeded' or status == 'failed': break time.sleep(60) print(status) <file_sep>/tests/library/iae_test.py from unittest import TestCase from mock import Mock, MagicMock from ibm_analytics_engine import IAE, CloudFoundryAPI, IAEServicePlanGuid, IAEClusterSpecificationExamples from ibm_analytics_engine.cf.service_instances import ServiceInstance class IAE_Test(TestCase): def test_provision_without_poll_basic_spark(self): mock = Mock(spec=CloudFoundryAPI) mock.service_instances = MagicMock() iae = IAE(cf_client=mock) cluster_spec = IAEClusterSpecificationExamples.SINGLE_NODE_BASIC_SPARK iae.create_cluster( service_instance_name='my_cluster', service_plan_guid='my_service_plan', space_guid='my_space_guid', cluster_creation_parameters=cluster_spec ) mock.service_instances.provision.assert_called_once_with( 'my_cluster', 'my_service_plan', 'my_space_guid', cluster_spec, poll_for_completion=False ) def test_provision_without_poll_basic_haddop(self): mock = Mock(spec=CloudFoundryAPI) mock.service_instances = MagicMock() iae = IAE(cf_client=mock) cluster_spec = IAEClusterSpecificationExamples.SINGLE_NODE_BASIC_HADOOP iae.create_cluster( service_instance_name='my_cluster', service_plan_guid='my_service_plan', space_guid='my_space_guid', cluster_creation_parameters=cluster_spec ) mock.service_instances.provision.assert_called_once_with( 'my_cluster', 'my_service_plan', 'my_space_guid', cluster_spec, poll_for_completion=False ) def test_list_clusters(self): mock = Mock(spec=CloudFoundryAPI) service_instances = Mock(spec=ServiceInstance) service_instances.get_service_instances.return_value = [ { 'name':'abc', 'guid':'12345', 'last_operation': {'state': 'failed' }, 'service_plan': { 'guid': IAEServicePlanGuid.LITE} }, { 'name':'def', 'guid':'01234', 'last_operation': {'state': 'succeeded' }, 'service_plan': { 'guid': IAEServicePlanGuid.LITE} } ] mock.service_instances = service_instances iae = IAE(cf_client=mock) clusters = iae.clusters('my_space_guid', status='succeeded') mock.service_instances.get_service_instances.assert_called_once_with('my_space_guid') assert len(clusters) == 1 # FIXME - re-enable this # assert clusters[0] == { # 'name': 'def', # 'guid': '01234', # 'state': 'succeeded' # } def test_list_clusters_with_keyerror(self): mock = Mock(spec=CloudFoundryAPI) service_instances = Mock(spec=ServiceInstance) service_instances.get_service_instances.return_value = [ { 'non_existent_key': None }, { 'non_existent_key': None }, ] mock.service_instances = service_instances iae = IAE(cf_client=mock) clusters = iae.clusters('my_space_guid') mock.service_instances.get_service_instances.assert_called_once_with('my_space_guid') assert len(clusters) == 0 <file_sep>/docs/example_scripts/create_cluster.py from ibm_analytics_engine.cf.client import CloudFoundryAPI from ibm_analytics_engine import IAE, IAEServicePlanGuid cf = CloudFoundryAPI(api_key_filename='your_api_key_filename') space_guid = cf.space_guid(org_name='your_org_name', space_name='your_space_name') iae = IAE(cf_client=cf) cluster_instance_guid = iae.create_cluster( service_instance_name='SPARK_CLUSTER', service_plan_guid=IAEServicePlanGuid.LITE, space_guid=space_guid, cluster_creation_parameters={ "hardware_config": "default", "num_compute_nodes": 1, "software_package": "ae-1.0-spark", } ) print('>> IAE cluster instance id: {}'.format(cluster_instance_guid)) # This call blocks for several minutes. See the Get Cluster Status example # for alternative options. status = iae.status( cluster_instance_guid=cluster_instance_guid, poll_while_in_progress=True) print('>> Cluster status: {}'.format(status)) <file_sep>/docs/example_scripts/cluster_credentials.py import json from ibm_analytics_engine.cf.client import CloudFoundryAPI from ibm_analytics_engine import IAE cf = CloudFoundryAPI(api_key_filename='your_api_key_filename') iae = IAE(cf_client=cf) vcap_json = iae.get_or_create_credentials(cluster_instance_guid='12345-12345-12345-12345') # prettify json vcap_formatted = json.dumps(vcap_json, indent=4, separators=(',', ': ')) print(vcap_formatted) <file_sep>/ibm_analytics_engine/cf/service_instances.py from __future__ import absolute_import from .logger import Logger from datetime import datetime, timedelta import time import requests import json class ServiceInstance: def __init__(self, cf_client): self.cf_client = cf_client def get_service_instances(self, space_guid): # https://apidocs.cloudfoundry.org/270/spaces/get_space_summary.html # TODO: # - replace spaces call with https://apidocs.cloudfoundry.org/270/service_instances/list_all_service_instances.html # note list_all_service_instances uses pagination url = '{}/v2/spaces/{}/summary'.format(self.cf_client.api_endpoint, space_guid) response = self.cf_client._request(url=url, http_method='get', description='get_service_instances') return response.json()['services'] # TODO rename service_instance_id to service_instance_guid def delete_service_instance(self, service_instance_id, recursive=False): url = '{}/v2/service_instances/{}?recursive={}'.format(self.cf_client.api_endpoint, service_instance_id, json.dumps(recursive)) response = self.cf_client._request(url=url, http_method='delete', description='delete_service_instances') return response # TODO rename to create_service_instance def provision(self, service_instance_name, service_plan_guid, space_guid, parameters, poll_for_completion=False): url = '{}/v2/service_instances?accepts_incomplete=true'.format(self.cf_client.api_endpoint) data = { "name": service_instance_name, "space_guid": space_guid, "service_plan_guid": service_plan_guid, "parameters": parameters } response = self.cf_client._request(url=url, http_method='post', data=data, description='provision') new_instance_guid = response.json()['metadata']['guid'] if poll_for_completion: self.poll_for_completion(new_instance_guid) return response.json() def status(self, service_instance_id): url = '{}/v2/service_instances/{}'.format(self.cf_client.api_endpoint, service_instance_id) response = self.cf_client._request(url=url, http_method='get', description='get_status') return response.json() # TODO rename service_instance_id to service_instance_guid def poll_for_completion(self, service_instance_id): url = '{}/v2/service_instances/{}'.format(self.cf_client.api_endpoint, service_instance_id) headers = self.cf_client._request_headers() poll_start = datetime.now() # Status codes: https://apidocs.cloudfoundry.org/245/service_instances/creating_a_service_instance.html status = 'in progress' while status == 'in progress': if (datetime.now() - poll_start).seconds > (self.cf_client.provision_poll_timeout_mins * 60): raise TimeoutError('Failed to provision with {} minutes'.format(self.cf_client.provision_poll_timeout_mins)) try: response = requests.get(url, headers=headers) response.raise_for_status() d = response.json() last_operation = d['entity']['last_operation'] self.cf_client.log.debug('Poll status response for service_instance_guid: {} : {}'.format(service_instance_id, str(last_operation))) if last_operation['type'] == 'create': status = last_operation['state'] except requests.exceptions.RequestException as e: self.cf_client.log.error('Service Provision Status Response: ' + response.text) raise time.sleep(30) self.cf_client.log.debug('provisioning completed: ' + status) # returns succeeded or failed return status <file_sep>/ibm_analytics_engine/iae.py from __future__ import absolute_import from __future__ import print_function from .dataplatform_api import DataPlatformAPI from .cf.client import CloudFoundryException from .logger import Logger """ .. module:: iae :platform: Unix, Windows :synopsis: Classes for working with IBM Analytics Engine .. moduleauthor:: <NAME> <<EMAIL>> """ class IAEServicePlanGuid: """Service Plan Guid for IBM Analytics Engine.""" LITE = 'acb06a56-fab1-4cb1-a178-c811bc676164' """IBM Analytics Engine 'Lite' plan.""" STD_HOURLY = '9ba7e645-fce1-46ad-90dc-12655bc45f9e' """IBM Analytics Engine 'Standard Hourly' plan.""" STD_MONTHLY = 'f801e166-2c73-4189-8ebb-ef7c1b586709' """IBM Analytics Engine 'Standard Monthly' plan.""" guids = [ LITE, STD_HOURLY, STD_MONTHLY ] class IAEClusterSpecificationExamples: """Example cluster specifications""" SINGLE_NODE_BASIC_SPARK = { "num_compute_nodes": 1, "hardware_config": "default", "software_package": "ae-1.0-spark" } """Basic single node spark cluster with default hardware.""" SINGLE_NODE_BASIC_HADOOP = { "num_compute_nodes": 1, "hardware_config": "default", "software_package": "ae-1.0-hadoop-spark" } """Basic single node hadoop cluster with default hardware.""" class IAE: """ This class provides methods for working with IBM Analytics Engine (IAE) deployment operations. Many of the methods in this calls are performed by calling the Cloud Foundry Rest API (https://apidocs.cloudfoundry.org/272/). The Cloud Foundry API is quite abstract, so this class provides methods names that are more meaningful for those just wanting to work with IAE. This class does not save the state from the Cloud Foundry operations - it retrieve all state from Cloud Foundry as required. """ def __init__(self, cf_client): """ Create a new instance of the IAE client. Args: cf_client (CloudFoundryAPI): The object that makes the Cloud Foundry rest API calls. """ assert cf_client is not None, "This action requires a CloudFoundryAPI instance" if cf_client: self.cf_client = cf_client self.dataplatform_api = DataPlatformAPI(cf_client) self.log = Logger().get_logger(self.__class__.__name__) # # generic cluster operations # # TODO create an class for the last_operation_status def clusters(self, space_guid, short=True, status=None): """ Returns a list of clusters in the `space_guid` Args: space_guid (:obj:`str`): The space_guid to query for IAE clusters. short (:obj:`bool`, optional): Whether to return short (brief) output. If false, returns the full Cloud Foundry API output. status (:obj:`str`, optional): Filter the return only the provided status values. Returns: :obj:`list`: If the `short=True`, this method returns: `[ (cluster_name, cluster_guid, last_operation_state), ... ]` | The `last_operation_status` may be: | | - `in progress` | - `succeeded` | - `failed` """ # TODO pass IAEServicePlanGuid.guids to the filter parameter in the cf api call iae_instances = self.cf_client.service_instances.get_service_instances( space_guid) clusters = [] for i in iae_instances: try: if i['service_plan']['guid'] in IAEServicePlanGuid.guids: if status is None or status == i['last_operation']['state']: if short: clusters.append({ 'name': i['name'], 'guid': i['guid'], 'state': i['last_operation']['state'] }) else: clusters.append(i) except KeyError: pass return clusters # TODO what is returned on error? def create_cluster( self, service_instance_name, service_plan_guid, space_guid, cluster_creation_parameters): """ Create a new IAE Cluster` Args: service_instance_name (:obj:`str`): The name you would like for the Cluster. service_plan_guid (:obj:`IAEServicePlanGuid`): The guid representing the type of Cluster to create. space_guid (:obj:`str`): The space guid where the Cluster will be created. cluster_creation_parameters (:obj:`dict`): The cluster creation parameters. An example cluster creation parameters is shown below: | { | "num_compute_nodes": 1, | "hardware_config": "Standard", | "software_package": "ae-1.0-spark", | "customization": [{ | "name": "action1", | "type": "bootstrap", | "script": { | "source_type": "http", | "script_path": "http://path/to/your/script" | }, | "script_params": [] | }] | } Returns: :obj:`str`: The cluster_instance_guid """ # Create instance response = self.cf_client.service_instances.provision( service_instance_name, service_plan_guid, space_guid, cluster_creation_parameters, poll_for_completion=False) cluster_instance_guid = response['metadata']['guid'] return cluster_instance_guid # # operations on a specific cluster - requires cluster_instance_id # # TODO rename to cloud foundry status def status(self, cluster_instance_guid, poll_while_in_progress=False): if poll_while_in_progress: return self.cf_client.service_instances.poll_for_completion( cluster_instance_guid) else: status = self.cf_client.service_instances.status( service_instance_id=cluster_instance_guid) return status['entity']['last_operation']['state'] def dataplatform_status(self, vcap): return self.dataplatform_api.status(vcap) def delete_cluster(self, cluster_instance_guid, recursive=False): try: self.cf_client.service_instances.delete_service_instance( service_instance_id=cluster_instance_guid, recursive=recursive) except CloudFoundryException as e: self.log.debug(e.message) raise def get_or_create_credentials(self, cluster_instance_guid,): get_sk_json = self.cf_client.service_keys.get_service_keys( service_instance_guid=cluster_instance_guid) if get_sk_json['total_results'] >= 1: # we found some credentials, so return the first set of credentials return get_sk_json['resources'][0]['entity']['credentials'] else: status = self.status(cluster_instance_guid=cluster_instance_guid) if status != 'succeeded': raise RuntimeError("Cluster status is '{}' but must be 'succeeded' to create credentials.".format(status)) # create some credentials and return them create_sk_json = self.cf_client.service_keys.create_service_key(cluster_instance_guid) return create_sk_json['entity']['credentials'] def print_all_clusters(self): import pprint pp = pprint.PrettyPrinter(indent=4) for org in self.cf_client.orgs_and_spaces(): for space in org['spaces']: print('ORG {} | SPACE {}'.format(org['name'], space['name'])) print() clusters = self.clusters(space_guid=space['guid']) if len(clusters) > 0: for cluster in clusters: pp.pprint(cluster) print() class AmbariOperations: def __init__(self, vcap=None, vcap_filename=None): self.log = Logger().get_logger(self.__class__.__name__) assert (vcap is not None or vcap_filename is not None) \ and (vcap is None or vcap_filename is None), \ "You must only provide a vcap object OR vcap_filename parameter" if vcap_filename is not None: import json vcap = json.load(open(vcap_filename)) try: self.USER = vcap['cluster']['user'] self.PASSWORD = vcap['cluster']['password'] self.AMBARI_URL = vcap['cluster']['service_endpoints']['ambari_console'] self.CLUSTER_ID = vcap['cluster']['cluster_id'] except KeyError as e: self.log.error("Couldn't parse vcap credential json - attribute {} not found.".format(str(e))) raise # ensure we are compatible with python 2 and 3 try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse url = urlparse(self.AMBARI_URL) self.HOST = url.hostname self.PORT = url.port self.PROTOCOL = url.scheme from ambariclient.client import Ambari self.ambari_client = Ambari(self.HOST, port=self.PORT, username=self.USER, password=<PASSWORD>, protocol=self.PROTOCOL) def get_namenode_hostname(self): # gets first cluster - there will only be one CLUSTER_NAME = self.ambari_client.clusters.next().cluster_name namenode_hc = self.ambari_client \ .clusters(CLUSTER_NAME) \ .services('HDFS') \ .components('NAMENODE') \ .host_components namenode_host_name = [hc.host_name for hc in namenode_hc if hc.host_name][0] return namenode_host_name <file_sep>/docs/example_scripts/run_docker_notebook.sh #!/bin/bash export VCAP_STR="$(cat vcap.json)" KG_HTTP_USER=$(python -c "import json, os; print(json.loads(os.environ['VCAP_STR'])['cluster']['user'])") KG_HTTP_PASS=$(python -c "import json, os; print(json.loads(os.environ['VCAP_STR'])['cluster']['password'])") KG_HTTP_URL=$(python -c "import json, os; print(json.loads(os.environ['VCAP_STR'])['cluster']['service_endpoints']['notebook_gateway'])") KG_WS_URL=$(python -c "import json, os; print(json.loads(os.environ['VCAP_STR'])['cluster']['service_endpoints']['notebook_gateway_websocket'])") # Create a directory for the notebooks so they don't disappear when the docker constainer shuts down if [ ! -d notebooks ] then mkdir notebooks fi docker run -it --rm \ -v $(pwd)/notebooks:/tmp/notebooks \ -e KG_HTTP_USER=$KG_HTTP_USER \ -e KG_HTTP_PASS=$KG_HTTP_PASS \ -e KG_URL=$KG_HTTP_URL \ -e KG_WS_URL=$KG_WS_URL \ -p 8888:8888 \ biginsights/jupyter-nb-nb2kg # Open a browser window to: http://127.0.0.1:8888 <file_sep>/docs/requirements.txt nbsphinx==0.2.17 <file_sep>/docs/example_scripts/delete_cluster.py from ibm_analytics_engine.cf.client import CloudFoundryAPI, CloudFoundryException from ibm_analytics_engine import IAE cf = CloudFoundryAPI(api_key_filename='your_api_key_filename') iae = IAE(cf_client=cf) try: iae.delete_cluster( cluster_instance_guid='12345-12345-12345-12345', recursive=True) print('Cluster deleted.') except CloudFoundryException as e: print('Unable to delete cluster: ' + str(e)) <file_sep>/docs/example_scripts/find_space_guid.py from ibm_analytics_engine.cf.client import CloudFoundryAPI cf = CloudFoundryAPI(api_key_filename='your_api_key_filename') try: space_guid = cf.space_guid(org_name='your_org_name', space_name='your_space_name') print(space_guid) except ValueError as e: # Space not found print(e) <file_sep>/tests/library/cf/client_test.py from unittest import TestCase from mock import Mock, patch import sys import tempfile import os import json import requests from requests.exceptions import RequestException from ibm_analytics_engine import CloudFoundryAPI, CloudFoundryException class TestCloudFoundryAPI(TestCase): def test_invalid_api_key_file(self): try: error_class = IOError except BaseException: error_class = FileNotFoundError with self.assertRaises(error_class): cf = CloudFoundryAPI(api_key_filename='does_not_exist') def mocked_requests_get(*args, **kwargs): if args[0] == 'https://api.ng.bluemix.net/v2/info': return MockResponse({"authorization_endpoint": "https://login.ng.bluemix.net/UAALoginServerWAR"}, 200) @patch('requests.get', side_effect=mocked_requests_get) def test_api_key_file(self, mock_get): # delete=True means the file will be deleted on close tmp = tempfile.NamedTemporaryFile(delete=True) try: data = json.dumps({ "name": "iae-key", "description": "", "createdAt": "2017-11-14T12:30+0000", "apiKey": "" }).encode('utf-8') tmp.write(data) tmp.flush() cf = CloudFoundryAPI(api_key_filename=tmp.name) finally: tmp.close() # deletes the file class MockResponse: def __init__(self, json_data, status_code, raise_for_status_flag=False, text_data=''): self.json_data = json_data self.text = text_data self.status_code = status_code self.raise_for_status_flag = raise_for_status_flag def raise_for_status(self): if self.raise_for_status_flag: self.text = 'some error occurred' raise requests.exceptions.HTTPError() else: return def json(self): return self.json_data class TestCloudFoundryAPI_Request(TestCase): def mocked_requests_get(*args, **kwargs): if args[0] == 'https://api.ng.bluemix.net/v2/info': return MockResponse({"authorization_endpoint": "https://login.ng.bluemix.net/UAALoginServerWAR"}, 200) else: return MockResponse(None, None, True, 'text_data') @patch('requests.get', side_effect=mocked_requests_get) def test_request_method(self, mock_get): cf = CloudFoundryAPI(api_key='abcdef') with self.assertRaises(CloudFoundryException): cf._request('url', 'get', 'some_data', 'description', create_auth_headers=False) class TestCloudFoundryAPI_Auth(TestCase): def mocked_requests_get(*args, **kwargs): if args[0] == 'https://api.ng.bluemix.net/v2/info': return MockResponse({"authorization_endpoint": "https://login.ng.bluemix.net/UAALoginServerWAR"}, 200) raise RuntimeError("Unhandle GET request: " + args[0]) def mocked_requests_post(*args, **kwargs): if args[0] == 'https://login.ng.bluemix.net/UAALoginServerWAR/oauth/token': return MockResponse(None, None, True) raise RuntimeError("Unhandle GET request: " + args[0]) @patch('requests.get', side_effect=mocked_requests_get) @patch('requests.post', side_effect=mocked_requests_post) def test_auth(self, mock_get, mock_post): cf = CloudFoundryAPI(api_key='abcdef') with self.assertRaises(RequestException): cf.auth() class TestCloudFoundryAPI_Oidc(TestCase): def mocked_requests_get(*args, **kwargs): if args[0] == 'https://api.ng.bluemix.net/v2/info': return MockResponse({"authorization_endpoint": "https://login.ng.bluemix.net/UAALoginServerWAR"}, 200) raise RuntimeError("Unhandle GET request: " + args[0]) def mocked_requests_post(*args, **kwargs): if args[0] == 'https://login.ng.bluemix.net/UAALoginServerWAR/oauth/token': return MockResponse({'access_token': '<PASSWORD>', 'token_type': 'bearer', 'refresh_token': '<PASSWORD>', 'expires_in': 1209599}, 200) if args[0] == 'https://iam.bluemix.net/identity/token': return MockResponse(None, None, True) raise RuntimeError("Unhandle GET request: " + args[0]) @patch('requests.get', side_effect=mocked_requests_get) @patch('requests.post', side_effect=mocked_requests_post) def test_auth(self, mock_get, mock_post): cf = CloudFoundryAPI(api_key='abcdef') with self.assertRaises(RequestException): cf.oidc_token() <file_sep>/docs/example_scripts/clusters.py from ibm_analytics_engine.cf.client import CloudFoundryAPI from ibm_analytics_engine import IAE cf = CloudFoundryAPI(api_key_filename='your_api_key_filename') space_guid = cf.space_guid(org_name='your_org_name', space_name='your_space_name') iae = IAE(cf_client=cf) for i in iae.clusters(space_guid=space_guid): print(i) <file_sep>/ibm_analytics_engine/dataplatform_api.py from __future__ import absolute_import from .logger import Logger import requests import json from datetime import datetime, timedelta class DataPlatformAPI: def __init__(self, cf_client): assert cf_client is not None self.cf_client = cf_client self.log = Logger().get_logger(self.__class__.__name__) def _request_headers(self): iam_token = self.cf_client.get_oidc_token()['access_token'] headers = { 'Authorization': 'Bearer {}'.format(iam_token) } return headers def _request(self, url, http_method='get', data=None, description='', create_auth_headers=True): if create_auth_headers: headers = self._request_headers() else: headers = {} try: if http_method == 'get': response = requests.get(url, headers=headers) elif http_method == 'post': response = requests.post(url, headers=headers, data=json.dumps(data)) elif http_method == 'delete': response = requests.delete(url, headers=headers) response.raise_for_status() except requests.exceptions.RequestException as e: self.log.error('{} : {} {} : {} {}'.format(description, http_method, url, response.status_code, response.text)) raise try: self.log.debug('{} : {} {} : {} {}'.format(description, http_method, url, response.status_code, json.dumps(response.json()))) except ValueError: self.log.debug('{} : {} {} : {} {}'.format(description, http_method, url, response.status_code, response.text)) return response def status(self, vcap): api_url = vcap['cluster_management']['api_url'] + '/state' response = self._request(url=api_url, http_method='get', description='status') return response.json() <file_sep>/ibm_analytics_engine/__init__.py """A python library for working with IBM Analytics Engine .. moduleauthor:: <NAME> <<EMAIL>> """ from __future__ import absolute_import from .iae import IAE, IAEServicePlanGuid, IAEClusterSpecificationExamples from .iae import AmbariOperations from .dataplatform_api import DataPlatformAPI from .logger import Logger from .cf.client import CloudFoundryAPI, CloudFoundryException <file_sep>/tests/library/cf/__init__.py from __future__ import absolute_import from ibm_analytics_engine.cf.client import CloudFoundryAPI from ibm_analytics_engine.cf.service_instances import ServiceInstance <file_sep>/ibm_analytics_engine/cf/spaces.py from __future__ import absolute_import from .logger import Logger class Space: def __init__(self, cf_client): self.cf_client = cf_client def get_spaces(self, name=None, filter_string=None): assert name is None or filter_string is None or \ name is None and filter_string is None, "You can provide name or filter_string, but not both" if name: url = '{}/v2/spaces?q=name:{}'.format(self.cf_client.api_endpoint, name) elif filter_string: url = '{}/v2/spaces?{}'.format(self.cf_client.api_endpoint, filter_string) else: url = '{}/v2/spaces'.format(self.cf_client.api_endpoint) response = self.cf_client._request(url=url, http_method='get', description='get_space') return response.json() <file_sep>/ibm_analytics_engine/cf/service_keys.py from __future__ import absolute_import from .logger import Logger from datetime import datetime, timedelta import time import requests import json class ServiceKey: def __init__(self, cf_client): self.cf_client = cf_client def get_service_keys(self, service_instance_guid, name=None): if name: url = '{}/v2/service_keys?q=service_instance_guid:{}&q=name:{}'.format(self.cf_client.api_endpoint, service_instance_guid, name) else: url = '{}/v2/service_keys?q=service_instance_guid:{}'.format(self.cf_client.api_endpoint, service_instance_guid) response = self.cf_client._request(url=url, http_method='get', description='get_service_keys') return response.json() def create_service_key(self, service_instance_guid, name='Credentials-1'): url = '{}/v2/service_keys'.format(self.cf_client.api_endpoint) data = { "service_instance_guid": service_instance_guid, "name": name, } response = self.cf_client._request(url=url, http_method='post', data=data, description='create_service_key') return response.json() <file_sep>/docs/example_scripts/list_orgs_and_spaces.py from ibm_analytics_engine.cf.client import CloudFoundryAPI cf = CloudFoundryAPI(api_key_filename='your_api_key_filename') cf.print_orgs_and_spaces() <file_sep>/docs/apidocs.rst ******** API Docs ******** .. automodule:: ibm_analytics_engine =========================== Service Instance Operations =========================== Lifecycle operations for an IAE service instance. .. autoclass:: IAE :members: __init__, create_cluster, clusters More api docs coming soon ... ===================== Spark Livy Operations ===================== Not implemented yet. ==================== Spark SSH Operations ==================== Not implemented yet. ================= Ambari Operations ================= Not implemented yet. ======================== Cloud Foundry Operations ======================== .. autoclass:: CloudFoundryAPI :members: __init__ =============== Utility Classes =============== IBMServicePlanGuid ------------------ .. _IBMServicePlanGuid-ref: .. autoclass:: IAEServicePlanGuid :members: <file_sep>/tests/doc/test_delete_cluster.py import sys import os import tempfile import json curfilePath = os.path.abspath(__file__) scriptDir = os.path.abspath(os.path.join(curfilePath, os.pardir, os.pardir, os.pardir, 'docs', 'example_scripts')) from unittest import TestCase from mock import Mock, MagicMock import mock class MockResponse: def __init__(self, json_data, status_code): self.json_data = json_data self.status_code = status_code def raise_for_status(self): return def json(self): return self.json_data class DocExampleScripts_Test(TestCase): def mocked_requests_get(*args, **kwargs): if args[0] == 'https://api.ng.bluemix.net/v2/info': return MockResponse({"authorization_endpoint": "https://login.ng.bluemix.net/UAALoginServerWAR"}, 200) raise RuntimeError("Unhandled url {}".format(args[0])) def mocked_requests_post(*args, **kwargs): if args[0] == 'https://login.ng.bluemix.net/UAALoginServerWAR/oauth/token': return MockResponse({'access_token': 'aaaaa', 'token_type': 'bearer', 'refresh_token': '<PASSWORD>', 'expires_in': 1209599}, 200) raise RuntimeError("Unhandled url {}".format(args[0])) def mocked_requests_delete(*args, **kwargs): if args[0] == 'https://api.ng.bluemix.net/v2/service_instances/12345-12345-12345-12345?recursive=true': return MockResponse({}, 204) raise RuntimeError("Unhandled url {}".format(args[0])) @mock.patch('requests.get', side_effect=mocked_requests_get) @mock.patch('requests.post', side_effect=mocked_requests_post) @mock.patch('requests.delete', side_effect=mocked_requests_delete) def test(self, mock_get, mock_post, mock_delete): tmp = tempfile.NamedTemporaryFile(delete=True) try: data = json.dumps({ "name": "iae-key", "description": "", "createdAt": "2017-11-14T12:30+0000", "apiKey": "" }).encode('utf-8') tmp.write(data) tmp.flush() from ibm_analytics_engine import CloudFoundryAPI CloudFoundryAPI.api_key_filename = tmp.name sys.path.append(os.path.abspath(os.path.join(scriptDir))) import delete_cluster del CloudFoundryAPI.api_key_filename finally: tmp.close() # deletes the file <file_sep>/tests/library/cf/service_instance_test.py from unittest import TestCase from mock import Mock, MagicMock from ibm_analytics_engine.cf.client import CloudFoundryAPI from ibm_analytics_engine.cf.service_instances import ServiceInstance class ServiceInstance_Test(TestCase): def test_provision_without_poll(self): mock = Mock(spec=CloudFoundryAPI) mock._request = MagicMock() mock.api_endpoint = 'my_url' si = ServiceInstance(mock) si.provision( service_instance_name='my_cluster', service_plan_guid='my_service_plan', space_guid='my_space_guid', parameters={ "somedata": "default", } ) mock._request.assert_called_once_with( data={'name': 'my_cluster', 'space_guid': 'my_space_guid', 'service_plan_guid': 'my_service_plan', 'parameters': {'somedata': 'default'}}, description='provision', http_method='post', url='my_url/v2/service_instances?accepts_incomplete=true' ) <file_sep>/docs/examples.rst ******** Examples ******** This section shows example code snippets for working with this library. ============= Prerequisites ============= **API Key** The lifecycle of an IBM Analytics Engine cluster is controlled through Cloud Foundry (e.g. create, delete, status operations). This python library requires an API key to work with the Cloud Foundry APIs. For more information on IBM Cloud API Keys including how to create and download an API Key, see https://console.bluemix.net/docs/iam/userid_keys.html#userapikey **Installation** Ensure you have installed this library. Install with: .. code-block:: python pip install --upgrade git+https://github.com/snowch/ibm-analytics-engine-python@master ======= Logging ======= Log level is controlled with the environment variable ``LOG_LEVEL``. You may set it programmatically in your code: .. code-block:: python os.environ["LOG_LEVEL"] = "DEBUG" Typical valid values are ERROR, WARNING, INFO, DEBUG. For a full list of values, see: https://docs.python.org/3/library/logging.html#logging-levels ======================= Finding your space guid ======================= Many operations in this library require you to specify a space guid. You can list the spaces guids for your account using this example: .. literalinclude:: example_scripts/list_orgs_and_spaces.py Alternatively, if you know your organisation name and space name, you can use the following: .. literalinclude:: example_scripts/find_space_guid.py ============== Create Cluster ============== This example shows how to create a basic spark cluster. .. literalinclude:: example_scripts/create_cluster.py The above example creates a LITE cluster. See :ref:`IBMServicePlanGuid` for the available service plan guids. ============== Delete Cluster ============== .. literalinclude:: example_scripts/delete_cluster.py ============================== Get or Create Credentials ============================== .. literalinclude:: example_scripts/cluster_credentials.py To save the returned data to disk, you can do something like: .. code-block:: python with open('./vcap.json', 'w') as vcap_file: vcap_file.write(vcap_formatted) ================== Get Cluster Status ================== To return the Cloud Foundry status: .. literalinclude:: example_scripts/cluster_status.py Alternative option to poll for the Cloud Foundry status. Note that this approach can block for many minutes while a cluster is being provisioned. While it is blocked, there is no progress output: .. literalinclude:: example_scripts/cluster_status_poll.py To return the Data Platform API status: .. literalinclude:: example_scripts/cluster_dp_api_status.py ============= List Clusters ============= .. literalinclude:: example_scripts/clusters.py ======================== Jupyter Notebook Gateway ======================== This is an example script for running a docker notebook that connects to the cluster using the JNBG protocol and the credentials in your vcap.json file. .. literalinclude:: example_scripts/run_docker_notebook.sh <file_sep>/ibm_analytics_engine/cf/client.py from __future__ import absolute_import from .logger import Logger from .service_instances import ServiceInstance from .service_keys import ServiceKey from .spaces import Space from .organizations import Organization import requests import json from datetime import datetime, timedelta class CloudFoundryException(Exception): def __init__(self, message, *args): self.message = message super(CloudFoundryException, self).__init__(message, *args) class CloudFoundryAPI(object): def __init__(self, api_key=None, api_key_filename=None, api_endpoint='https://api.ng.bluemix.net', provision_poll_timeout_mins=30): self.log = Logger().get_logger(self.__class__.__name__) self.provision_poll_timeout_mins = provision_poll_timeout_mins assert api_key is not None or api_key_filename is not None, "You must provide a value for api_key or for api_key_filename" # allow tests to override the api_key_filename parameter if hasattr(CloudFoundryAPI, 'api_key_filename') and CloudFoundryAPI is not None: api_key_filename = CloudFoundryAPI.api_key_filename if api_key_filename is not None: try: with open(api_key_filename, 'r') as api_file: d = json.load(api_file) try: self.api_key = d['apikey'] except KeyError: # The attibute name used to be self.api_key = d['apiKey'] except: self.log.error('Error retrieving "apiKey" from file {}'.format(api_key_filename)) raise else: self.api_key = api_key self.api_endpoint = api_endpoint self.info = self._get_info() self.service_instances = ServiceInstance(self) self.service_keys = ServiceKey(self) self.spaces = Space(self) self.organizations = Organization(self) def auth(self): self.log.debug('Authenticating to CloudFoundry') url = self.info['authorization_endpoint'] + '/oauth/token' headers = { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8', 'Accept': 'application/x-www-form-urlencoded;charset=utf-8', 'Authorization': 'Basic Y2Y6' } data = 'grant_type=password&username=apikey&password={}'.<PASSWORD>(self.api_key) try: response = requests.post(url, headers=headers, data=data) response.raise_for_status() except requests.exceptions.RequestException as e: self.log.error('Cloud Foundry Auth Response: ' + response.text) # TODO we should define a custom application exception for this raise self.auth_token = response.json() self.expires_at = datetime.now() + timedelta(seconds=self.auth_token['expires_in']/60) self.log.debug('Authenticated to CloudFoundry') def oidc_token(self): self.log.debug('Retrieving IAM token') url='https://iam.bluemix.net/identity/token' data="grant_type=urn:ibm:params:oauth:grant-type:apikey&apikey={}".format(self.api_key) try: response = requests.post(url, data=data) response.raise_for_status() except requests.exceptions.RequestException as e: self.log.error('IAM token response: ' + response.text) raise self.oidc_token = response.json() self.oidc_expires_at = datetime.now() + timedelta(seconds=self.oidc_token['expires_in']/60) self.log.debug('Retrieved IAM token') return self.oidc_token def get_auth_token(self): if not hasattr(self, 'auth_token') or not hasattr(self, 'expires_at') or datetime.now() > self.expires_at: self.auth() return self.auth_token def get_oidc_token(self): if not hasattr(self, 'oidc_token') or not hasattr(self, 'oidc_expires_at') or datetime.now() > self.oidc_expires_at: self.oidc_token() return self.oidc_token def _request_headers(self): auth_token = self.get_auth_token() access_token = auth_token['access_token'] token_type = auth_token['token_type'] headers = { 'accept': 'application/json', 'authorization': '{} {}'.format(token_type, access_token), 'cache-control': 'no-cache', 'content-type': 'application/json' } return headers def _request(self, url, http_method='get', data=None, description='', create_auth_headers=True): if create_auth_headers: headers = self._request_headers() else: headers = {} try: if http_method == 'get': response = requests.get(url, headers=headers) elif http_method == 'post': response = requests.post(url, headers=headers, data=json.dumps(data)) elif http_method == 'delete': response = requests.delete(url, headers=headers) response.raise_for_status() except requests.exceptions.RequestException as e: self.log.debug('{} : {} {} : {} {}'.format(description, http_method, url, response.status_code, response.text)) raise CloudFoundryException(message=response.text) try: self.log.debug('{} : {} {} : {} {}'.format(description, http_method, url, response.status_code, json.dumps(response.json()))) except ValueError: self.log.debug('{} : {} {} : {} {}'.format(description, http_method, url, response.status_code, response.text)) return response def _get_info(self): url = '{}/v2/info'.format(self.api_endpoint) response = self._request(url=url, http_method='get', description='_get_info', create_auth_headers=False) return response.json() def space_guid(self, org_name, space_name): assert org_name is not None, "org_name must be provided" assert space_name is not None, "space_name must be provided" org_json = self.organizations.get_organizations(org_name) # Organisation names should be unique - there should only be one result if org_json['total_results'] != 1: raise ValueError('organization name "{}" was not found'.format(org_name)) org_guid = org_json['resources'][0]['metadata']['guid'] space_filter_string = 'q=organization_guid:{}'.format(org_guid) spaces_json = self.spaces.get_spaces(filter_string=space_filter_string) if spaces_json['total_results'] == 0: raise ValueError('no spaces found for orgnaization "{}"'.format(org_name)) for spc in spaces_json['resources']: if spc['entity']['name'] == space_name: return spc['metadata']['guid'] raise ValueError('space "{}" not found for organization "{}"'.format(space_name, org_name)) def orgs_and_spaces(self, org_name=None, space_name=None): if space_name is not None: spaces_json = self.spaces.get_spaces(name=space_name) else: spaces_json = self.spaces.get_spaces() if org_name is not None: organizations_json = self.organizations.get_organizations(org_name) else: organizations_json = self.organizations.get_organizations() def get_spaces_for_org(organization_guid, spaces_json): spaces = [] for spc in spaces_json['resources']: if spc['entity']['organization_guid'] == organization_guid: spaces.append(spc) return spaces orgs_and_spaces = [] for organization in organizations_json['resources']: spaces = [] for space in get_spaces_for_org(organization['metadata']['guid'], spaces_json): spaces.append({ 'name': space['entity']['name'], 'guid': space['metadata']['guid'] }) orgs_and_spaces.append({ 'name': organization['entity']['name'], 'guid': organization['metadata']['guid'], 'spaces': spaces }) return orgs_and_spaces def print_clusters_in_all_spaces(self): import pprint pp = pprint.PrettyPrinter(indent=4) for org in self.cf.orgs_and_spaces(): for space in org['spaces']: print('ORG {} | SPACE {}'.format(org['name'], space['name'])) print() clusters = iae.clusters(space_guid=space['guid']) if len(clusters) > 0: for cluster in clusters: pp.pprint(cluster) print() def print_orgs_and_spaces(self, org_name=None, space_name=None): oas = self.orgs_and_spaces(org_name, space_name) max_len = 0 for o in oas: if len(o['name']) > max_len: max_len = len(o['name']) for s in o['spaces']: if len(s['name']) > max_len: max_len = len(s['name']) for o in oas: orgname=o['name'] orgguid=o['guid'] format='Org: {orgname:{width}} {orgguid}'.format(orgname=orgname, width=max_len, orgguid=orgguid) print('-' * len(format)) print(format) for s in o['spaces']: spcname=s['name'] spcguid=s['guid'] print('> Spc: {spcname:{width}} {spcguid}'.format(spcname=spcname, width=max_len, spcguid=spcguid)) <file_sep>/ibm_analytics_engine/cf/organizations.py from __future__ import absolute_import from .logger import Logger class Organization: def __init__(self, cf_client): self.cf_client = cf_client def get_organizations(self, name=None): if name: url = '{}/v2/organizations?q=name:{}'.format(self.cf_client.api_endpoint, name) else: url = '{}/v2/organizations'.format(self.cf_client.api_endpoint) response = self.cf_client._request(url=url, http_method='get', description='get_space') return response.json() <file_sep>/docs/example_scripts/cluster_status_poll.py from ibm_analytics_engine.cf.client import CloudFoundryAPI from ibm_analytics_engine import IAE cf = CloudFoundryAPI(api_key_filename='your_api_key_filename') iae = IAE(cf_client=cf) status = iae.status( cluster_instance_guid='12345-12345-12345-12345', poll_while_in_progress=True) print(status) <file_sep>/tests/library/cf/service_keys_test.py from unittest import TestCase from mock import Mock, MagicMock from ibm_analytics_engine.cf.client import CloudFoundryAPI from ibm_analytics_engine.cf.service_keys import ServiceKey class ServiceKey_Test(TestCase): def test_get_service_keys(self): mock = Mock(spec=CloudFoundryAPI) mock._request = MagicMock() mock.api_endpoint = 'my_url' si = ServiceKey(mock) si.get_service_keys( service_instance_guid='my_space_guid' ) mock._request.assert_called_once_with( description='get_service_keys', http_method='get', url='my_url/v2/service_keys?q=service_instance_guid:my_space_guid' ) def test_get_service_keys_with_name(self): mock = Mock(spec=CloudFoundryAPI) mock._request = MagicMock() mock.api_endpoint = 'my_url' si = ServiceKey(mock) si.get_service_keys( service_instance_guid='my_space_guid', name='my_key_name' ) mock._request.assert_called_once_with( description='get_service_keys', http_method='get', url='my_url/v2/service_keys?q=service_instance_guid:my_space_guid&q=name:my_key_name' ) <file_sep>/docs/example_scripts/cluster_dp_api_status.py from ibm_analytics_engine.cf.client import CloudFoundryAPI from ibm_analytics_engine import IAE cf = CloudFoundryAPI(api_key_filename='your_api_key_filename') iae = IAE(cf_client=cf) vcap = iae.get_or_create_credentials(cluster_instance_guid='12345-12345-12345-12345') status = iae.dataplatform_status(vcap) print(status) <file_sep>/docs/index.rst *************************** IBM Analyics Engine Library *************************** This project is a Python library for working with the IBM Analytics Engine. The github repository for this library can be found here: - https://github.com/snowch/ibm-analytics-engine-python ---- .. toctree:: :maxdepth: 2 :caption: Contents: examples apidocs example_notebooks/CreateCluster example_notebooks/DockerExampleNB2KG ---- Install with: .. code-block:: python pip install --upgrade git+https://github.com/snowch/ibm-analytics-engine-python@master NOTE: This documentation is a work-in-progress. It will be complete within the next few days/weeks. Please come back soon ... Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search`
42c794a86322974a577fa9d434d085bb5236698b
[ "Python", "Text", "reStructuredText", "Shell" ]
29
Python
pkuong/ibm-analytics-engine-python
d4e16446782c516c08f6b03bc4a68557ca2859c8
01fb50eae398a31662dec40317c8a2080a3a6b44
refs/heads/master
<repo_name>LuisPerez0790/event<file_sep>/.apt_generated/com/gob/scjn/service/mapper/VenueMapperImpl.java package com.gob.scjn.service.mapper; import com.gob.scjn.domain.Venue; import com.gob.scjn.service.dto.VenueDTO; import java.util.ArrayList; import java.util.List; import javax.annotation.Generated; import org.springframework.stereotype.Component; @Generated( value = "org.mapstruct.ap.MappingProcessor", date = "2018-07-21T14:51:12-0500", comments = "version: 1.2.0.Final, compiler: Eclipse JDT (IDE) 3.12.3.v20170228-1205, environment: Java 1.8.0_171 (Oracle Corporation)" ) @Component public class VenueMapperImpl implements VenueMapper { @Override public Venue toEntity(VenueDTO dto) { if ( dto == null ) { return null; } Venue venue = new Venue(); venue.setId( dto.getId() ); venue.setName( dto.getName() ); venue.setAddress( dto.getAddress() ); venue.setImageUrl( dto.getImageUrl() ); venue.setPhone( dto.getPhone() ); venue.setUrl( dto.getUrl() ); venue.setGoogleMaps( dto.getGoogleMaps() ); venue.setDescription( dto.getDescription() ); return venue; } @Override public VenueDTO toDto(Venue entity) { if ( entity == null ) { return null; } VenueDTO venueDTO = new VenueDTO(); venueDTO.setId( entity.getId() ); venueDTO.setName( entity.getName() ); venueDTO.setAddress( entity.getAddress() ); venueDTO.setImageUrl( entity.getImageUrl() ); venueDTO.setPhone( entity.getPhone() ); venueDTO.setUrl( entity.getUrl() ); venueDTO.setGoogleMaps( entity.getGoogleMaps() ); venueDTO.setDescription( entity.getDescription() ); return venueDTO; } @Override public List<Venue> toEntity(List<VenueDTO> dtoList) { if ( dtoList == null ) { return null; } List<Venue> list = new ArrayList<Venue>( dtoList.size() ); for ( VenueDTO venueDTO : dtoList ) { list.add( toEntity( venueDTO ) ); } return list; } @Override public List<VenueDTO> toDto(List<Venue> entityList) { if ( entityList == null ) { return null; } List<VenueDTO> list = new ArrayList<VenueDTO>( entityList.size() ); for ( Venue venue : entityList ) { list.add( toDto( venue ) ); } return list; } } <file_sep>/.apt_generated/com/gob/scjn/service/mapper/MenuItemsLanguageMapperImpl.java package com.gob.scjn.service.mapper; import com.gob.scjn.domain.MenuItemsLanguage; import com.gob.scjn.service.dto.MenuItemsLanguageDTO; import java.util.ArrayList; import java.util.List; import javax.annotation.Generated; import org.springframework.stereotype.Component; @Generated( value = "org.mapstruct.ap.MappingProcessor", date = "2018-07-24T19:22:05-0500", comments = "version: 1.2.0.Final, compiler: Eclipse JDT (IDE) 3.12.3.v20170228-1205, environment: Java 1.8.0_171 (Oracle Corporation)" ) @Component public class MenuItemsLanguageMapperImpl implements MenuItemsLanguageMapper { @Override public MenuItemsLanguageDTO toDto(MenuItemsLanguage arg0) { if ( arg0 == null ) { return null; } MenuItemsLanguageDTO menuItemsLanguageDTO = new MenuItemsLanguageDTO(); menuItemsLanguageDTO.setId( arg0.getId() ); menuItemsLanguageDTO.setName( arg0.getName() ); menuItemsLanguageDTO.setLanguage( arg0.getLanguage() ); return menuItemsLanguageDTO; } @Override public List<MenuItemsLanguageDTO> toDto(List<MenuItemsLanguage> arg0) { if ( arg0 == null ) { return null; } List<MenuItemsLanguageDTO> list = new ArrayList<MenuItemsLanguageDTO>( arg0.size() ); for ( MenuItemsLanguage menuItemsLanguage : arg0 ) { list.add( toDto( menuItemsLanguage ) ); } return list; } @Override public MenuItemsLanguage toEntity(MenuItemsLanguageDTO arg0) { if ( arg0 == null ) { return null; } MenuItemsLanguage menuItemsLanguage = new MenuItemsLanguage(); menuItemsLanguage.setId( arg0.getId() ); menuItemsLanguage.setName( arg0.getName() ); menuItemsLanguage.setLanguage( arg0.getLanguage() ); return menuItemsLanguage; } @Override public List<MenuItemsLanguage> toEntity(List<MenuItemsLanguageDTO> arg0) { if ( arg0 == null ) { return null; } List<MenuItemsLanguage> list = new ArrayList<MenuItemsLanguage>( arg0.size() ); for ( MenuItemsLanguageDTO menuItemsLanguageDTO : arg0 ) { list.add( toEntity( menuItemsLanguageDTO ) ); } return list; } } <file_sep>/.apt_generated/com/gob/scjn/domain/SitePage_.java package com.gob.scjn.domain; import java.time.Instant; import javax.annotation.Generated; import javax.persistence.metamodel.SetAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor") @StaticMetamodel(SitePage.class) public abstract class SitePage_ { public static volatile SingularAttribute<SitePage, Site> site; public static volatile SetAttribute<SitePage, SitePageLanguage> pages; public static volatile SetAttribute<SitePage, CMS> cms; public static volatile SingularAttribute<SitePage, Long> id; public static volatile SingularAttribute<SitePage, Instant> updatedDate; public static volatile SingularAttribute<SitePage, Instant> creationDate; public static volatile SingularAttribute<SitePage, String> menuEntry; public static volatile SingularAttribute<SitePage, String> slug; public static volatile SingularAttribute<SitePage, Long> order; public static volatile SingularAttribute<SitePage, Boolean> status; } <file_sep>/src/main/java/com/gob/scjn/service/impl/MenuItemsServiceImpl.java package com.gob.scjn.service.impl; import com.gob.scjn.service.MenuItemsService; import com.gob.scjn.domain.MenuItems; import com.gob.scjn.repository.MenuItemsRepository; import com.gob.scjn.service.dto.MenuItemsDTO; import com.gob.scjn.service.mapper.MenuItemsMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * Service Implementation for managing MenuItems. */ @Service @Transactional public class MenuItemsServiceImpl implements MenuItemsService { private final Logger log = LoggerFactory.getLogger(MenuItemsServiceImpl.class); private final MenuItemsRepository menuItemsRepository; private final MenuItemsMapper menuItemsMapper; public MenuItemsServiceImpl(MenuItemsRepository menuItemsRepository, MenuItemsMapper menuItemsMapper) { this.menuItemsRepository = menuItemsRepository; this.menuItemsMapper = menuItemsMapper; } /** * Save a menuItems. * * @param menuItemsDTO the entity to save * @return the persisted entity */ @Override public MenuItemsDTO save(MenuItemsDTO menuItemsDTO) { log.debug("Request to save MenuItems : {}", menuItemsDTO); MenuItems menuItems = menuItemsMapper.toEntity(menuItemsDTO); menuItems = menuItemsRepository.save(menuItems); return menuItemsMapper.toDto(menuItems); } /** * Get all the menuItems. * * @return the list of entities */ @Override @Transactional(readOnly = true) public List<MenuItemsDTO> findAll() { log.debug("Request to get all MenuItems"); return menuItemsRepository.findAll().stream() .map(menuItemsMapper::toDto) .collect(Collectors.toCollection(LinkedList::new)); } /** * Get one menuItems by id. * * @param id the id of the entity * @return the entity */ @Override @Transactional(readOnly = true) public Optional<MenuItemsDTO> findOne(Long id) { log.debug("Request to get MenuItems : {}", id); return menuItemsRepository.findById(id) .map(menuItemsMapper::toDto); } /** * Delete the menuItems by id. * * @param id the id of the entity */ @Override public void delete(Long id) { log.debug("Request to delete MenuItems : {}", id); menuItemsRepository.deleteById(id); } } <file_sep>/src/main/java/com/gob/scjn/domain/SiteColorPalette.java package com.gob.scjn.domain; import javax.persistence.*; import java.io.Serializable; import java.util.Objects; /** * A SiteColorPalette. */ @Entity @Table(name = "site_color_palette") public class SiteColorPalette implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "jhi_primary") private String primary; @Column(name = "secondary") private String secondary; @Column(name = "inverse") private String inverse; @Column(name = "complementary") private String complementary; // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getPrimary() { return primary; } public SiteColorPalette primary(String primary) { this.primary = primary; return this; } public void setPrimary(String primary) { this.primary = primary; } public String getSecondary() { return secondary; } public SiteColorPalette secondary(String secondary) { this.secondary = secondary; return this; } public void setSecondary(String secondary) { this.secondary = secondary; } public String getInverse() { return inverse; } public SiteColorPalette inverse(String inverse) { this.inverse = inverse; return this; } public void setInverse(String inverse) { this.inverse = inverse; } public String getComplementary() { return complementary; } public SiteColorPalette complementary(String complementary) { this.complementary = complementary; return this; } public void setComplementary(String complementary) { this.complementary = complementary; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SiteColorPalette siteColorPalette = (SiteColorPalette) o; if (siteColorPalette.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), siteColorPalette.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "SiteColorPalette{" + "id=" + getId() + ", primary='" + getPrimary() + "'" + ", secondary='" + getSecondary() + "'" + ", inverse='" + getInverse() + "'" + ", complementary='" + getComplementary() + "'" + "}"; } } <file_sep>/src/test/java/com/gob/scjn/web/rest/EventLanguageResourceIntTest.java package com.gob.scjn.web.rest; import com.gob.scjn.EventApp; import com.gob.scjn.domain.EventLanguage; import com.gob.scjn.repository.EventLanguageRepository; import com.gob.scjn.service.EventLanguageService; import com.gob.scjn.service.dto.EventLanguageDTO; import com.gob.scjn.service.mapper.EventLanguageMapper; import com.gob.scjn.web.rest.errors.ExceptionTranslator; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.util.List; import static com.gob.scjn.web.rest.TestUtil.createFormattingConversionService; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import com.gob.scjn.domain.enumeration.Language; /** * Test class for the EventLanguageResource REST controller. * * @see EventLanguageResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = EventApp.class) public class EventLanguageResourceIntTest { private static final String DEFAULT_NAME = "AAAAAAAAAA"; private static final String UPDATED_NAME = "BBBBBBBBBB"; private static final String DEFAULT_DESCRIPTION = "AAAAAAAAAA"; private static final String UPDATED_DESCRIPTION = "BBBBBBBBBB"; private static final String DEFAULT_ADDRESS = "AAAAAAAAAA"; private static final String UPDATED_ADDRESS = "BBBBBBBBBB"; private static final Language DEFAULT_LANGUAGE = Language.ENGLISH; private static final Language UPDATED_LANGUAGE = Language.FRENCH; @Autowired private EventLanguageRepository eventLanguageRepository; @Autowired private EventLanguageMapper eventLanguageMapper; @Autowired private EventLanguageService eventLanguageService; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; @Autowired private ExceptionTranslator exceptionTranslator; @Autowired private EntityManager em; private MockMvc restEventLanguageMockMvc; private EventLanguage eventLanguage; @Before public void setup() { MockitoAnnotations.initMocks(this); final EventLanguageResource eventLanguageResource = new EventLanguageResource(eventLanguageService); this.restEventLanguageMockMvc = MockMvcBuilders.standaloneSetup(eventLanguageResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setControllerAdvice(exceptionTranslator) .setConversionService(createFormattingConversionService()) .setMessageConverters(jacksonMessageConverter).build(); } /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static EventLanguage createEntity(EntityManager em) { EventLanguage eventLanguage = new EventLanguage() .name(DEFAULT_NAME) .description(DEFAULT_DESCRIPTION) .address(DEFAULT_ADDRESS) .language(DEFAULT_LANGUAGE); return eventLanguage; } @Before public void initTest() { eventLanguage = createEntity(em); } @Test @Transactional public void createEventLanguage() throws Exception { int databaseSizeBeforeCreate = eventLanguageRepository.findAll().size(); // Create the EventLanguage EventLanguageDTO eventLanguageDTO = eventLanguageMapper.toDto(eventLanguage); restEventLanguageMockMvc.perform(post("/api/event-languages") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(eventLanguageDTO))) .andExpect(status().isCreated()); // Validate the EventLanguage in the database List<EventLanguage> eventLanguageList = eventLanguageRepository.findAll(); assertThat(eventLanguageList).hasSize(databaseSizeBeforeCreate + 1); EventLanguage testEventLanguage = eventLanguageList.get(eventLanguageList.size() - 1); assertThat(testEventLanguage.getName()).isEqualTo(DEFAULT_NAME); assertThat(testEventLanguage.getDescription()).isEqualTo(DEFAULT_DESCRIPTION); assertThat(testEventLanguage.getAddress()).isEqualTo(DEFAULT_ADDRESS); assertThat(testEventLanguage.getLanguage()).isEqualTo(DEFAULT_LANGUAGE); } @Test @Transactional public void createEventLanguageWithExistingId() throws Exception { int databaseSizeBeforeCreate = eventLanguageRepository.findAll().size(); // Create the EventLanguage with an existing ID eventLanguage.setId(1L); EventLanguageDTO eventLanguageDTO = eventLanguageMapper.toDto(eventLanguage); // An entity with an existing ID cannot be created, so this API call must fail restEventLanguageMockMvc.perform(post("/api/event-languages") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(eventLanguageDTO))) .andExpect(status().isBadRequest()); // Validate the EventLanguage in the database List<EventLanguage> eventLanguageList = eventLanguageRepository.findAll(); assertThat(eventLanguageList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void getAllEventLanguages() throws Exception { // Initialize the database eventLanguageRepository.saveAndFlush(eventLanguage); // Get all the eventLanguageList restEventLanguageMockMvc.perform(get("/api/event-languages?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(eventLanguage.getId().intValue()))) .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString()))) .andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION.toString()))) .andExpect(jsonPath("$.[*].address").value(hasItem(DEFAULT_ADDRESS.toString()))) .andExpect(jsonPath("$.[*].language").value(hasItem(DEFAULT_LANGUAGE.toString()))); } @Test @Transactional public void getEventLanguage() throws Exception { // Initialize the database eventLanguageRepository.saveAndFlush(eventLanguage); // Get the eventLanguage restEventLanguageMockMvc.perform(get("/api/event-languages/{id}", eventLanguage.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(eventLanguage.getId().intValue())) .andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString())) .andExpect(jsonPath("$.description").value(DEFAULT_DESCRIPTION.toString())) .andExpect(jsonPath("$.address").value(DEFAULT_ADDRESS.toString())) .andExpect(jsonPath("$.language").value(DEFAULT_LANGUAGE.toString())); } @Test @Transactional public void getNonExistingEventLanguage() throws Exception { // Get the eventLanguage restEventLanguageMockMvc.perform(get("/api/event-languages/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test @Transactional public void updateEventLanguage() throws Exception { // Initialize the database eventLanguageRepository.saveAndFlush(eventLanguage); int databaseSizeBeforeUpdate = eventLanguageRepository.findAll().size(); // Update the eventLanguage EventLanguage updatedEventLanguage = eventLanguageRepository.findById(eventLanguage.getId()).get(); // Disconnect from session so that the updates on updatedEventLanguage are not directly saved in db em.detach(updatedEventLanguage); updatedEventLanguage .name(UPDATED_NAME) .description(UPDATED_DESCRIPTION) .address(UPDATED_ADDRESS) .language(UPDATED_LANGUAGE); EventLanguageDTO eventLanguageDTO = eventLanguageMapper.toDto(updatedEventLanguage); restEventLanguageMockMvc.perform(put("/api/event-languages") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(eventLanguageDTO))) .andExpect(status().isOk()); // Validate the EventLanguage in the database List<EventLanguage> eventLanguageList = eventLanguageRepository.findAll(); assertThat(eventLanguageList).hasSize(databaseSizeBeforeUpdate); EventLanguage testEventLanguage = eventLanguageList.get(eventLanguageList.size() - 1); assertThat(testEventLanguage.getName()).isEqualTo(UPDATED_NAME); assertThat(testEventLanguage.getDescription()).isEqualTo(UPDATED_DESCRIPTION); assertThat(testEventLanguage.getAddress()).isEqualTo(UPDATED_ADDRESS); assertThat(testEventLanguage.getLanguage()).isEqualTo(UPDATED_LANGUAGE); } @Test @Transactional public void updateNonExistingEventLanguage() throws Exception { int databaseSizeBeforeUpdate = eventLanguageRepository.findAll().size(); // Create the EventLanguage EventLanguageDTO eventLanguageDTO = eventLanguageMapper.toDto(eventLanguage); // If the entity doesn't have an ID, it will be created instead of just being updated restEventLanguageMockMvc.perform(put("/api/event-languages") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(eventLanguageDTO))) .andExpect(status().isBadRequest()); // Validate the EventLanguage in the database List<EventLanguage> eventLanguageList = eventLanguageRepository.findAll(); assertThat(eventLanguageList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional public void deleteEventLanguage() throws Exception { // Initialize the database eventLanguageRepository.saveAndFlush(eventLanguage); int databaseSizeBeforeDelete = eventLanguageRepository.findAll().size(); // Get the eventLanguage restEventLanguageMockMvc.perform(delete("/api/event-languages/{id}", eventLanguage.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate the database is empty List<EventLanguage> eventLanguageList = eventLanguageRepository.findAll(); assertThat(eventLanguageList).hasSize(databaseSizeBeforeDelete - 1); } @Test @Transactional public void equalsVerifier() throws Exception { TestUtil.equalsVerifier(EventLanguage.class); EventLanguage eventLanguage1 = new EventLanguage(); eventLanguage1.setId(1L); EventLanguage eventLanguage2 = new EventLanguage(); eventLanguage2.setId(eventLanguage1.getId()); assertThat(eventLanguage1).isEqualTo(eventLanguage2); eventLanguage2.setId(2L); assertThat(eventLanguage1).isNotEqualTo(eventLanguage2); eventLanguage1.setId(null); assertThat(eventLanguage1).isNotEqualTo(eventLanguage2); } @Test @Transactional public void dtoEqualsVerifier() throws Exception { TestUtil.equalsVerifier(EventLanguageDTO.class); EventLanguageDTO eventLanguageDTO1 = new EventLanguageDTO(); eventLanguageDTO1.setId(1L); EventLanguageDTO eventLanguageDTO2 = new EventLanguageDTO(); assertThat(eventLanguageDTO1).isNotEqualTo(eventLanguageDTO2); eventLanguageDTO2.setId(eventLanguageDTO1.getId()); assertThat(eventLanguageDTO1).isEqualTo(eventLanguageDTO2); eventLanguageDTO2.setId(2L); assertThat(eventLanguageDTO1).isNotEqualTo(eventLanguageDTO2); eventLanguageDTO1.setId(null); assertThat(eventLanguageDTO1).isNotEqualTo(eventLanguageDTO2); } @Test @Transactional public void testEntityFromId() { assertThat(eventLanguageMapper.fromId(42L).getId()).isEqualTo(42); assertThat(eventLanguageMapper.fromId(null)).isNull(); } } <file_sep>/.apt_generated/com/gob/scjn/service/mapper/EventUserMapperImpl.java package com.gob.scjn.service.mapper; import com.gob.scjn.domain.EventUser; import com.gob.scjn.service.dto.EventUserDTO; import java.util.ArrayList; import java.util.List; import javax.annotation.Generated; import org.springframework.stereotype.Component; @Generated( value = "org.mapstruct.ap.MappingProcessor", date = "2018-07-21T14:51:12-0500", comments = "version: 1.2.0.Final, compiler: Eclipse JDT (IDE) 3.12.3.v20170228-1205, environment: Java 1.8.0_171 (Oracle Corporation)" ) @Component public class EventUserMapperImpl implements EventUserMapper { @Override public EventUserDTO toDto(EventUser entity) { if ( entity == null ) { return null; } EventUserDTO eventUserDTO = new EventUserDTO(); eventUserDTO.setId( entity.getId() ); eventUserDTO.setName( entity.getName() ); eventUserDTO.setLastName( entity.getLastName() ); eventUserDTO.setUserName( entity.getUserName() ); eventUserDTO.setInstitution( entity.getInstitution() ); eventUserDTO.setPosition( entity.getPosition() ); eventUserDTO.setEmail( entity.getEmail() ); eventUserDTO.setDescription( entity.getDescription() ); eventUserDTO.setImageUrl( entity.getImageUrl() ); eventUserDTO.setUserType( entity.getUserType() ); return eventUserDTO; } @Override public List<EventUser> toEntity(List<EventUserDTO> dtoList) { if ( dtoList == null ) { return null; } List<EventUser> list = new ArrayList<EventUser>( dtoList.size() ); for ( EventUserDTO eventUserDTO : dtoList ) { list.add( toEntity( eventUserDTO ) ); } return list; } @Override public List<EventUserDTO> toDto(List<EventUser> entityList) { if ( entityList == null ) { return null; } List<EventUserDTO> list = new ArrayList<EventUserDTO>( entityList.size() ); for ( EventUser eventUser : entityList ) { list.add( toDto( eventUser ) ); } return list; } @Override public EventUser toEntity(EventUserDTO eventUserDTO) { if ( eventUserDTO == null ) { return null; } EventUser eventUser = new EventUser(); eventUser.setId( eventUserDTO.getId() ); eventUser.setName( eventUserDTO.getName() ); eventUser.setLastName( eventUserDTO.getLastName() ); eventUser.setUserName( eventUserDTO.getUserName() ); eventUser.setInstitution( eventUserDTO.getInstitution() ); eventUser.setPosition( eventUserDTO.getPosition() ); eventUser.setEmail( eventUserDTO.getEmail() ); eventUser.setDescription( eventUserDTO.getDescription() ); eventUser.setImageUrl( eventUserDTO.getImageUrl() ); eventUser.setUserType( eventUserDTO.getUserType() ); return eventUser; } } <file_sep>/.apt_generated/com/gob/scjn/service/mapper/SiteColorPaletteMapperImpl.java package com.gob.scjn.service.mapper; import com.gob.scjn.domain.SiteColorPalette; import com.gob.scjn.service.dto.SiteColorPaletteDTO; import java.util.ArrayList; import java.util.List; import javax.annotation.Generated; import org.springframework.stereotype.Component; @Generated( value = "org.mapstruct.ap.MappingProcessor", date = "2018-07-21T14:51:12-0500", comments = "version: 1.2.0.Final, compiler: Eclipse JDT (IDE) 3.12.3.v20170228-1205, environment: Java 1.8.0_171 (Oracle Corporation)" ) @Component public class SiteColorPaletteMapperImpl implements SiteColorPaletteMapper { @Override public SiteColorPalette toEntity(SiteColorPaletteDTO dto) { if ( dto == null ) { return null; } SiteColorPalette siteColorPalette = new SiteColorPalette(); siteColorPalette.setId( dto.getId() ); siteColorPalette.setPrimary( dto.getPrimary() ); siteColorPalette.setSecondary( dto.getSecondary() ); siteColorPalette.setInverse( dto.getInverse() ); siteColorPalette.setComplementary( dto.getComplementary() ); return siteColorPalette; } @Override public SiteColorPaletteDTO toDto(SiteColorPalette entity) { if ( entity == null ) { return null; } SiteColorPaletteDTO siteColorPaletteDTO = new SiteColorPaletteDTO(); siteColorPaletteDTO.setId( entity.getId() ); siteColorPaletteDTO.setPrimary( entity.getPrimary() ); siteColorPaletteDTO.setSecondary( entity.getSecondary() ); siteColorPaletteDTO.setInverse( entity.getInverse() ); siteColorPaletteDTO.setComplementary( entity.getComplementary() ); return siteColorPaletteDTO; } @Override public List<SiteColorPalette> toEntity(List<SiteColorPaletteDTO> dtoList) { if ( dtoList == null ) { return null; } List<SiteColorPalette> list = new ArrayList<SiteColorPalette>( dtoList.size() ); for ( SiteColorPaletteDTO siteColorPaletteDTO : dtoList ) { list.add( toEntity( siteColorPaletteDTO ) ); } return list; } @Override public List<SiteColorPaletteDTO> toDto(List<SiteColorPalette> entityList) { if ( entityList == null ) { return null; } List<SiteColorPaletteDTO> list = new ArrayList<SiteColorPaletteDTO>( entityList.size() ); for ( SiteColorPalette siteColorPalette : entityList ) { list.add( toDto( siteColorPalette ) ); } return list; } } <file_sep>/src/test/java/com/gob/scjn/web/rest/SitePageLanguageResourceIntTest.java package com.gob.scjn.web.rest; import com.gob.scjn.EventApp; import com.gob.scjn.domain.SitePageLanguage; import com.gob.scjn.repository.SitePageLanguageRepository; import com.gob.scjn.service.SitePageLanguageService; import com.gob.scjn.service.dto.SitePageLanguageDTO; import com.gob.scjn.service.mapper.SitePageLanguageMapper; import com.gob.scjn.web.rest.errors.ExceptionTranslator; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Base64Utils; import javax.persistence.EntityManager; import java.util.List; import static com.gob.scjn.web.rest.TestUtil.createFormattingConversionService; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import com.gob.scjn.domain.enumeration.Language; /** * Test class for the SitePageLanguageResource REST controller. * * @see SitePageLanguageResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = EventApp.class) public class SitePageLanguageResourceIntTest { private static final String DEFAULT_EXCEPT_PAGE = "AAAAAAAAAA"; private static final String UPDATED_EXCEPT_PAGE = "BBBBBBBBBB"; private static final String DEFAULT_CONTENT = "AAAAAAAAAA"; private static final String UPDATED_CONTENT = "BBBBBBBBBB"; private static final String DEFAULT_TITLE = "AAAAAAAAAA"; private static final String UPDATED_TITLE = "BBBBBBBBBB"; private static final Language DEFAULT_LANGUAGE = Language.ENGLISH; private static final Language UPDATED_LANGUAGE = Language.FRENCH; @Autowired private SitePageLanguageRepository sitePageLanguageRepository; @Autowired private SitePageLanguageMapper sitePageLanguageMapper; @Autowired private SitePageLanguageService sitePageLanguageService; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; @Autowired private ExceptionTranslator exceptionTranslator; @Autowired private EntityManager em; private MockMvc restSitePageLanguageMockMvc; private SitePageLanguage sitePageLanguage; @Before public void setup() { MockitoAnnotations.initMocks(this); final SitePageLanguageResource sitePageLanguageResource = new SitePageLanguageResource(sitePageLanguageService); this.restSitePageLanguageMockMvc = MockMvcBuilders.standaloneSetup(sitePageLanguageResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setControllerAdvice(exceptionTranslator) .setConversionService(createFormattingConversionService()) .setMessageConverters(jacksonMessageConverter).build(); } /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static SitePageLanguage createEntity(EntityManager em) { SitePageLanguage sitePageLanguage = new SitePageLanguage() .exceptPage(DEFAULT_EXCEPT_PAGE) .content(DEFAULT_CONTENT) .title(DEFAULT_TITLE) .language(DEFAULT_LANGUAGE); return sitePageLanguage; } @Before public void initTest() { sitePageLanguage = createEntity(em); } @Test @Transactional public void createSitePageLanguage() throws Exception { int databaseSizeBeforeCreate = sitePageLanguageRepository.findAll().size(); // Create the SitePageLanguage SitePageLanguageDTO sitePageLanguageDTO = sitePageLanguageMapper.toDto(sitePageLanguage); restSitePageLanguageMockMvc.perform(post("/api/site-page-languages") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(sitePageLanguageDTO))) .andExpect(status().isCreated()); // Validate the SitePageLanguage in the database List<SitePageLanguage> sitePageLanguageList = sitePageLanguageRepository.findAll(); assertThat(sitePageLanguageList).hasSize(databaseSizeBeforeCreate + 1); SitePageLanguage testSitePageLanguage = sitePageLanguageList.get(sitePageLanguageList.size() - 1); assertThat(testSitePageLanguage.getExceptPage()).isEqualTo(DEFAULT_EXCEPT_PAGE); assertThat(testSitePageLanguage.getContent()).isEqualTo(DEFAULT_CONTENT); assertThat(testSitePageLanguage.getTitle()).isEqualTo(DEFAULT_TITLE); assertThat(testSitePageLanguage.getLanguage()).isEqualTo(DEFAULT_LANGUAGE); } @Test @Transactional public void createSitePageLanguageWithExistingId() throws Exception { int databaseSizeBeforeCreate = sitePageLanguageRepository.findAll().size(); // Create the SitePageLanguage with an existing ID sitePageLanguage.setId(1L); SitePageLanguageDTO sitePageLanguageDTO = sitePageLanguageMapper.toDto(sitePageLanguage); // An entity with an existing ID cannot be created, so this API call must fail restSitePageLanguageMockMvc.perform(post("/api/site-page-languages") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(sitePageLanguageDTO))) .andExpect(status().isBadRequest()); // Validate the SitePageLanguage in the database List<SitePageLanguage> sitePageLanguageList = sitePageLanguageRepository.findAll(); assertThat(sitePageLanguageList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void getAllSitePageLanguages() throws Exception { // Initialize the database sitePageLanguageRepository.saveAndFlush(sitePageLanguage); // Get all the sitePageLanguageList restSitePageLanguageMockMvc.perform(get("/api/site-page-languages?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(sitePageLanguage.getId().intValue()))) .andExpect(jsonPath("$.[*].exceptPage").value(hasItem(DEFAULT_EXCEPT_PAGE.toString()))) .andExpect(jsonPath("$.[*].content").value(hasItem(DEFAULT_CONTENT.toString()))) .andExpect(jsonPath("$.[*].title").value(hasItem(DEFAULT_TITLE.toString()))) .andExpect(jsonPath("$.[*].language").value(hasItem(DEFAULT_LANGUAGE.toString()))); } @Test @Transactional public void getSitePageLanguage() throws Exception { // Initialize the database sitePageLanguageRepository.saveAndFlush(sitePageLanguage); // Get the sitePageLanguage restSitePageLanguageMockMvc.perform(get("/api/site-page-languages/{id}", sitePageLanguage.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(sitePageLanguage.getId().intValue())) .andExpect(jsonPath("$.exceptPage").value(DEFAULT_EXCEPT_PAGE.toString())) .andExpect(jsonPath("$.content").value(DEFAULT_CONTENT.toString())) .andExpect(jsonPath("$.title").value(DEFAULT_TITLE.toString())) .andExpect(jsonPath("$.language").value(DEFAULT_LANGUAGE.toString())); } @Test @Transactional public void getNonExistingSitePageLanguage() throws Exception { // Get the sitePageLanguage restSitePageLanguageMockMvc.perform(get("/api/site-page-languages/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test @Transactional public void updateSitePageLanguage() throws Exception { // Initialize the database sitePageLanguageRepository.saveAndFlush(sitePageLanguage); int databaseSizeBeforeUpdate = sitePageLanguageRepository.findAll().size(); // Update the sitePageLanguage SitePageLanguage updatedSitePageLanguage = sitePageLanguageRepository.findById(sitePageLanguage.getId()).get(); // Disconnect from session so that the updates on updatedSitePageLanguage are not directly saved in db em.detach(updatedSitePageLanguage); updatedSitePageLanguage .exceptPage(UPDATED_EXCEPT_PAGE) .content(UPDATED_CONTENT) .title(UPDATED_TITLE) .language(UPDATED_LANGUAGE); SitePageLanguageDTO sitePageLanguageDTO = sitePageLanguageMapper.toDto(updatedSitePageLanguage); restSitePageLanguageMockMvc.perform(put("/api/site-page-languages") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(sitePageLanguageDTO))) .andExpect(status().isOk()); // Validate the SitePageLanguage in the database List<SitePageLanguage> sitePageLanguageList = sitePageLanguageRepository.findAll(); assertThat(sitePageLanguageList).hasSize(databaseSizeBeforeUpdate); SitePageLanguage testSitePageLanguage = sitePageLanguageList.get(sitePageLanguageList.size() - 1); assertThat(testSitePageLanguage.getExceptPage()).isEqualTo(UPDATED_EXCEPT_PAGE); assertThat(testSitePageLanguage.getContent()).isEqualTo(UPDATED_CONTENT); assertThat(testSitePageLanguage.getTitle()).isEqualTo(UPDATED_TITLE); assertThat(testSitePageLanguage.getLanguage()).isEqualTo(UPDATED_LANGUAGE); } @Test @Transactional public void updateNonExistingSitePageLanguage() throws Exception { int databaseSizeBeforeUpdate = sitePageLanguageRepository.findAll().size(); // Create the SitePageLanguage SitePageLanguageDTO sitePageLanguageDTO = sitePageLanguageMapper.toDto(sitePageLanguage); // If the entity doesn't have an ID, it will be created instead of just being updated restSitePageLanguageMockMvc.perform(put("/api/site-page-languages") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(sitePageLanguageDTO))) .andExpect(status().isBadRequest()); // Validate the SitePageLanguage in the database List<SitePageLanguage> sitePageLanguageList = sitePageLanguageRepository.findAll(); assertThat(sitePageLanguageList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional public void deleteSitePageLanguage() throws Exception { // Initialize the database sitePageLanguageRepository.saveAndFlush(sitePageLanguage); int databaseSizeBeforeDelete = sitePageLanguageRepository.findAll().size(); // Get the sitePageLanguage restSitePageLanguageMockMvc.perform(delete("/api/site-page-languages/{id}", sitePageLanguage.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate the database is empty List<SitePageLanguage> sitePageLanguageList = sitePageLanguageRepository.findAll(); assertThat(sitePageLanguageList).hasSize(databaseSizeBeforeDelete - 1); } @Test @Transactional public void equalsVerifier() throws Exception { TestUtil.equalsVerifier(SitePageLanguage.class); SitePageLanguage sitePageLanguage1 = new SitePageLanguage(); sitePageLanguage1.setId(1L); SitePageLanguage sitePageLanguage2 = new SitePageLanguage(); sitePageLanguage2.setId(sitePageLanguage1.getId()); assertThat(sitePageLanguage1).isEqualTo(sitePageLanguage2); sitePageLanguage2.setId(2L); assertThat(sitePageLanguage1).isNotEqualTo(sitePageLanguage2); sitePageLanguage1.setId(null); assertThat(sitePageLanguage1).isNotEqualTo(sitePageLanguage2); } @Test @Transactional public void dtoEqualsVerifier() throws Exception { TestUtil.equalsVerifier(SitePageLanguageDTO.class); SitePageLanguageDTO sitePageLanguageDTO1 = new SitePageLanguageDTO(); sitePageLanguageDTO1.setId(1L); SitePageLanguageDTO sitePageLanguageDTO2 = new SitePageLanguageDTO(); assertThat(sitePageLanguageDTO1).isNotEqualTo(sitePageLanguageDTO2); sitePageLanguageDTO2.setId(sitePageLanguageDTO1.getId()); assertThat(sitePageLanguageDTO1).isEqualTo(sitePageLanguageDTO2); sitePageLanguageDTO2.setId(2L); assertThat(sitePageLanguageDTO1).isNotEqualTo(sitePageLanguageDTO2); sitePageLanguageDTO1.setId(null); assertThat(sitePageLanguageDTO1).isNotEqualTo(sitePageLanguageDTO2); } @Test @Transactional public void testEntityFromId() { assertThat(sitePageLanguageMapper.fromId(42L).getId()).isEqualTo(42); assertThat(sitePageLanguageMapper.fromId(null)).isNull(); } } <file_sep>/src/main/java/com/gob/scjn/service/MenuItemsLanguageService.java package com.gob.scjn.service; import com.gob.scjn.service.dto.MenuItemsLanguageDTO; import java.util.List; import java.util.Optional; /** * Service Interface for managing MenuItemsLanguage. */ public interface MenuItemsLanguageService { /** * Save a menuItemsLanguage. * * @param menuItemsLanguageDTO the entity to save * @return the persisted entity */ MenuItemsLanguageDTO save(MenuItemsLanguageDTO menuItemsLanguageDTO); /** * Get all the menuItemsLanguages. * * @return the list of entities */ List<MenuItemsLanguageDTO> findAll(); /** * Get the "id" menuItemsLanguage. * * @param id the id of the entity * @return the entity */ Optional<MenuItemsLanguageDTO> findOne(Long id); /** * Delete the "id" menuItemsLanguage. * * @param id the id of the entity */ void delete(Long id); } <file_sep>/src/main/java/com/gob/scjn/service/dto/VenueDTO.java package com.gob.scjn.service.dto; import java.io.Serializable; import java.util.Objects; /** * A DTO for the Venue entity. */ public class VenueDTO implements Serializable { private Long id; private String name; private String address; private String imageUrl; private String phone; private String url; private String googleMaps; private String description; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getGoogleMaps() { return googleMaps; } public void setGoogleMaps(String googleMaps) { this.googleMaps = googleMaps; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } VenueDTO venueDTO = (VenueDTO) o; if (venueDTO.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), venueDTO.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "VenueDTO{" + "id=" + getId() + ", name='" + getName() + "'" + ", address='" + getAddress() + "'" + ", imageUrl='" + getImageUrl() + "'" + ", phone='" + getPhone() + "'" + ", url='" + getUrl() + "'" + ", googleMaps='" + getGoogleMaps() + "'" + ", description='" + getDescription() + "'" + "}"; } } <file_sep>/src/main/java/com/gob/scjn/domain/SiteFooter.java package com.gob.scjn.domain; import javax.persistence.*; import java.io.Serializable; import java.util.Objects; /** * A SiteFooter. */ @Entity @Table(name = "site_footer") public class SiteFooter implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Lob @Column(name = "address") private String address; @Lob @Column(name = "contact") private String contact; @Lob @Column(name = "links") private String links; @Lob @Column(name = "more_content") private String moreContent; @Column(name = "google_maps") private String googleMaps; // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getAddress() { return address; } public SiteFooter address(String address) { this.address = address; return this; } public void setAddress(String address) { this.address = address; } public String getContact() { return contact; } public SiteFooter contact(String contact) { this.contact = contact; return this; } public void setContact(String contact) { this.contact = contact; } public String getLinks() { return links; } public SiteFooter links(String links) { this.links = links; return this; } public void setLinks(String links) { this.links = links; } public String getMoreContent() { return moreContent; } public SiteFooter moreContent(String moreContent) { this.moreContent = moreContent; return this; } public void setMoreContent(String moreContent) { this.moreContent = moreContent; } public String getGoogleMaps() { return googleMaps; } public SiteFooter googleMaps(String googleMaps) { this.googleMaps = googleMaps; return this; } public void setGoogleMaps(String googleMaps) { this.googleMaps = googleMaps; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SiteFooter siteFooter = (SiteFooter) o; if (siteFooter.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), siteFooter.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "SiteFooter{" + "id=" + getId() + ", address='" + getAddress() + "'" + ", contact='" + getContact() + "'" + ", links='" + getLinks() + "'" + ", moreContent='" + getMoreContent() + "'" + ", googleMaps='" + getGoogleMaps() + "'" + "}"; } } <file_sep>/.apt_generated/com/gob/scjn/domain/SiteFooter_.java package com.gob.scjn.domain; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor") @StaticMetamodel(SiteFooter.class) public abstract class SiteFooter_ { public static volatile SingularAttribute<SiteFooter, String> address; public static volatile SingularAttribute<SiteFooter, String> contact; public static volatile SingularAttribute<SiteFooter, String> links; public static volatile SingularAttribute<SiteFooter, Long> id; public static volatile SingularAttribute<SiteFooter, String> moreContent; public static volatile SingularAttribute<SiteFooter, String> googleMaps; } <file_sep>/src/main/java/com/gob/scjn/repository/SitePageLanguageRepository.java package com.gob.scjn.repository; import com.gob.scjn.domain.SitePageLanguage; import org.springframework.data.jpa.repository.*; import org.springframework.stereotype.Repository; /** * Spring Data repository for the SitePageLanguage entity. */ @SuppressWarnings("unused") @Repository public interface SitePageLanguageRepository extends JpaRepository<SitePageLanguage, Long> { } <file_sep>/src/main/java/com/gob/scjn/service/mapper/EventLanguageMapper.java package com.gob.scjn.service.mapper; import com.gob.scjn.domain.*; import com.gob.scjn.service.dto.EventLanguageDTO; import org.mapstruct.*; /** * Mapper for the entity EventLanguage and its DTO EventLanguageDTO. */ @Mapper(componentModel = "spring", uses = {EventMapper.class}) public interface EventLanguageMapper extends EntityMapper<EventLanguageDTO, EventLanguage> { //@Mapping(source = "event.id", target = "eventId") EventLanguageDTO toDto(EventLanguage eventLanguage); //@Mapping(source = "eventId", target = "event") EventLanguage toEntity(EventLanguageDTO eventLanguageDTO); default EventLanguage fromId(Long id) { if (id == null) { return null; } EventLanguage eventLanguage = new EventLanguage(); eventLanguage.setId(id); return eventLanguage; } } <file_sep>/src/main/java/com/gob/scjn/service/dto/package-info.java /** * Data Transfer Objects. */ package com.gob.scjn.service.dto; <file_sep>/src/main/java/com/gob/scjn/service/impl/SiteColorPaletteServiceImpl.java package com.gob.scjn.service.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.gob.scjn.domain.Site; import com.gob.scjn.repository.SiteRepository; import com.gob.scjn.service.SiteColorPaletteService; import com.gob.scjn.service.dto.SiteColorPaletteDTO; import com.gob.scjn.service.mapper.SiteColorPaletteMapper; /** * Service Implementation for managing SiteColorPalette. */ @Service @Transactional public class SiteColorPaletteServiceImpl implements SiteColorPaletteService { private final Logger log = LoggerFactory.getLogger(SiteColorPaletteServiceImpl.class); private final SiteColorPaletteMapper siteColorPaletteMapper; private final SiteRepository siteRepository; public SiteColorPaletteServiceImpl(SiteColorPaletteMapper siteColorPaletteMapper, SiteRepository siteRepository) { this.siteColorPaletteMapper = siteColorPaletteMapper; this.siteRepository = siteRepository; } /** * Save a siteColorPalette. * * @param siteColorPaletteDTO * the entity to save * @return the persisted entity */ @Override public SiteColorPaletteDTO save(Long id, SiteColorPaletteDTO siteColorPaletteDTO) { Site site = findByEventId(id); site.setPalette(siteColorPaletteMapper.toEntity(siteColorPaletteDTO)); site = siteRepository.save(site); return siteColorPaletteMapper.toDto(site.getPalette()); } /** * Get site color palette. * * @param site * id * @return site color palette */ @Override @Transactional(readOnly = true) public SiteColorPaletteDTO findOne(Long id) { return siteColorPaletteMapper.toDto(findByEventId(id).getPalette()); } /** * Delete the siteColorPalette by id. * * @param id * the id of the entity */ @Override public void delete(Long id) { log.debug("Request to delete SiteColorPalette : {}", id); Site site = findByEventId(id); site.setPalette(null); siteRepository.save(site); } private Site findByEventId(Long id) { return siteRepository.findById(id).get(); } } <file_sep>/src/main/java/com/gob/scjn/service/dto/SitePageDTO.java package com.gob.scjn.service.dto; import java.io.Serializable; import java.time.Instant; import java.util.HashSet; import java.util.Objects; import java.util.Set; /** * A DTO for the SitePage entity. */ public class SitePageDTO implements Serializable { private Long id; private Instant creationDate; private Instant updatedDate; private String menuEntry; private Long order; private Boolean status; private String slug; private Long siteId; private Set<SitePageLanguageDTO> languages = new HashSet<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Instant getCreationDate() { return creationDate; } public void setCreationDate(Instant creationDate) { this.creationDate = creationDate; } public Instant getUpdatedDate() { return updatedDate; } public void setUpdatedDate(Instant updatedDate) { this.updatedDate = updatedDate; } public String getMenuEntry() { return menuEntry; } public void setMenuEntry(String menuEntry) { this.menuEntry = menuEntry; } public Long getOrder() { return order; } public void setOrder(Long order) { this.order = order; } public Boolean isStatus() { return status; } public void setStatus(Boolean status) { this.status = status; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public Long getSiteId() { return siteId; } public void setSiteId(Long siteId) { this.siteId = siteId; } public Set<SitePageLanguageDTO> getLanguages() { return languages; } public void setLanguages(Set<SitePageLanguageDTO> languages) { this.languages = languages; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SitePageDTO sitePageDTO = (SitePageDTO) o; if (sitePageDTO.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), sitePageDTO.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "SitePageDTO [id=" + id + ", creationDate=" + creationDate + ", updatedDate=" + updatedDate + ", menuEntry=" + menuEntry + ", order=" + order + ", status=" + status + ", slug=" + slug + ", siteId=" + siteId + ", languages=" + languages + "]"; } } <file_sep>/.apt_generated/com/gob/scjn/domain/Menu_.java package com.gob.scjn.domain; import javax.annotation.Generated; import javax.persistence.metamodel.SetAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor") @StaticMetamodel(Menu.class) public abstract class Menu_ { public static volatile SingularAttribute<Menu, Long> id; public static volatile SetAttribute<Menu, MenuItems> items; } <file_sep>/.apt_generated/com/gob/scjn/domain/MenuItemsLanguage_.java package com.gob.scjn.domain; import com.gob.scjn.domain.enumeration.Language; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor") @StaticMetamodel(MenuItemsLanguage.class) public abstract class MenuItemsLanguage_ { public static volatile SingularAttribute<MenuItemsLanguage, String> name; public static volatile SingularAttribute<MenuItemsLanguage, MenuItems> menuItems; public static volatile SingularAttribute<MenuItemsLanguage, Language> language; public static volatile SingularAttribute<MenuItemsLanguage, Long> id; } <file_sep>/src/main/java/com/gob/scjn/service/VenueService.java package com.gob.scjn.service; import com.gob.scjn.service.dto.VenueDTO; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.Optional; /** * Service Interface for managing Venue. */ public interface VenueService { /** * Save a venue. * * @param venueDTO the entity to save * @return the persisted entity */ VenueDTO save(VenueDTO venueDTO); /** * Get all the venues. * * @param pageable the pagination information * @return the list of entities */ Page<VenueDTO> findAll(Pageable pageable); /** * Get the "id" venue. * * @param id the id of the entity * @return the entity */ Optional<VenueDTO> findOne(Long id); /** * Delete the "id" venue. * * @param id the id of the entity */ void delete(Long id); } <file_sep>/.apt_generated/com/gob/scjn/service/mapper/CMSMapperImpl.java package com.gob.scjn.service.mapper; import com.gob.scjn.domain.Activity; import com.gob.scjn.domain.CMS; import com.gob.scjn.domain.Event; import com.gob.scjn.domain.EventUser; import com.gob.scjn.domain.SitePage; import com.gob.scjn.service.dto.CMSDTO; import java.util.ArrayList; import java.util.List; import javax.annotation.Generated; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Generated( value = "org.mapstruct.ap.MappingProcessor", date = "2018-07-24T19:22:06-0500", comments = "version: 1.2.0.Final, compiler: Eclipse JDT (IDE) 3.12.3.v20170228-1205, environment: Java 1.8.0_171 (Oracle Corporation)" ) @Component public class CMSMapperImpl implements CMSMapper { @Autowired private EventUserMapper eventUserMapper; @Autowired private EventMapper eventMapper; @Autowired private ActivityMapper activityMapper; @Autowired private SitePageMapper sitePageMapper; @Override public List<CMSDTO> toDto(List<CMS> arg0) { if ( arg0 == null ) { return null; } List<CMSDTO> list = new ArrayList<CMSDTO>( arg0.size() ); for ( CMS cMS : arg0 ) { list.add( toDto( cMS ) ); } return list; } @Override public List<CMS> toEntity(List<CMSDTO> arg0) { if ( arg0 == null ) { return null; } List<CMS> list = new ArrayList<CMS>( arg0.size() ); for ( CMSDTO cMSDTO : arg0 ) { list.add( toEntity( cMSDTO ) ); } return list; } @Override public CMSDTO toDto(CMS cMS) { if ( cMS == null ) { return null; } CMSDTO cMSDTO = new CMSDTO(); Long id = cMSEventUserId( cMS ); if ( id != null ) { cMSDTO.setEventUserId( id ); } Long id1 = cMSEventId( cMS ); if ( id1 != null ) { cMSDTO.setEventId( id1 ); } Long id2 = cMSActivityId( cMS ); if ( id2 != null ) { cMSDTO.setActivityId( id2 ); } Long id3 = cMSSitePageId( cMS ); if ( id3 != null ) { cMSDTO.setSitePageId( id3 ); } cMSDTO.setFileId( cMS.getFileId() ); cMSDTO.setId( cMS.getId() ); return cMSDTO; } @Override public CMS toEntity(CMSDTO cMSDTO) { if ( cMSDTO == null ) { return null; } CMS cMS = new CMS(); cMS.setEventUser( eventUserMapper.fromId( cMSDTO.getEventUserId() ) ); cMS.setSitePage( sitePageMapper.fromId( cMSDTO.getSitePageId() ) ); cMS.setActivity( activityMapper.fromId( cMSDTO.getActivityId() ) ); cMS.setEvent( eventMapper.fromId( cMSDTO.getEventId() ) ); cMS.setId( cMSDTO.getId() ); cMS.setFileId( cMSDTO.getFileId() ); return cMS; } private Long cMSEventUserId(CMS cMS) { if ( cMS == null ) { return null; } EventUser eventUser = cMS.getEventUser(); if ( eventUser == null ) { return null; } Long id = eventUser.getId(); if ( id == null ) { return null; } return id; } private Long cMSEventId(CMS cMS) { if ( cMS == null ) { return null; } Event event = cMS.getEvent(); if ( event == null ) { return null; } Long id = event.getId(); if ( id == null ) { return null; } return id; } private Long cMSActivityId(CMS cMS) { if ( cMS == null ) { return null; } Activity activity = cMS.getActivity(); if ( activity == null ) { return null; } Long id = activity.getId(); if ( id == null ) { return null; } return id; } private Long cMSSitePageId(CMS cMS) { if ( cMS == null ) { return null; } SitePage sitePage = cMS.getSitePage(); if ( sitePage == null ) { return null; } Long id = sitePage.getId(); if ( id == null ) { return null; } return id; } } <file_sep>/src/main/java/com/gob/scjn/service/impl/EventUserServiceImpl.java package com.gob.scjn.service.impl; import com.gob.scjn.service.EventUserService; import com.gob.scjn.domain.EventUser; import com.gob.scjn.repository.EventUserRepository; import com.gob.scjn.service.dto.EventUserDTO; import com.gob.scjn.service.mapper.EventUserMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; /** * Service Implementation for managing EventUser. */ @Service @Transactional public class EventUserServiceImpl implements EventUserService { private final Logger log = LoggerFactory.getLogger(EventUserServiceImpl.class); private final EventUserRepository eventUserRepository; private final EventUserMapper eventUserMapper; public EventUserServiceImpl(EventUserRepository eventUserRepository, EventUserMapper eventUserMapper) { this.eventUserRepository = eventUserRepository; this.eventUserMapper = eventUserMapper; } /** * Save a eventUser. * * @param eventUserDTO the entity to save * @return the persisted entity */ @Override public EventUserDTO save(EventUserDTO eventUserDTO) { log.debug("Request to save EventUser : {}", eventUserDTO); EventUser eventUser = eventUserMapper.toEntity(eventUserDTO); eventUser = eventUserRepository.save(eventUser); return eventUserMapper.toDto(eventUser); } /** * Get all the eventUsers. * * @param pageable the pagination information * @return the list of entities */ @Override @Transactional(readOnly = true) public Page<EventUserDTO> findAll(Pageable pageable) { log.debug("Request to get all EventUsers"); return eventUserRepository.findAll(pageable) .map(eventUserMapper::toDto); } /** * Get one eventUser by id. * * @param id the id of the entity * @return the entity */ @Override @Transactional(readOnly = true) public Optional<EventUserDTO> findOne(Long id) { log.debug("Request to get EventUser : {}", id); return eventUserRepository.findById(id) .map(eventUserMapper::toDto); } /** * Delete the eventUser by id. * * @param id the id of the entity */ @Override public void delete(Long id) { log.debug("Request to delete EventUser : {}", id); eventUserRepository.deleteById(id); } } <file_sep>/src/test/java/com/gob/scjn/web/rest/EventUserResourceIntTest.java package com.gob.scjn.web.rest; import com.gob.scjn.EventApp; import com.gob.scjn.domain.EventUser; import com.gob.scjn.repository.EventUserRepository; import com.gob.scjn.service.EventUserService; import com.gob.scjn.service.dto.EventUserDTO; import com.gob.scjn.service.mapper.EventUserMapper; import com.gob.scjn.web.rest.errors.ExceptionTranslator; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.util.List; import static com.gob.scjn.web.rest.TestUtil.createFormattingConversionService; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import com.gob.scjn.domain.enumeration.UserType; /** * Test class for the EventUserResource REST controller. * * @see EventUserResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = EventApp.class) public class EventUserResourceIntTest { private static final String DEFAULT_NAME = "AAAAAAAAAA"; private static final String UPDATED_NAME = "BBBBBBBBBB"; private static final String DEFAULT_LAST_NAME = "AAAAAAAAAA"; private static final String UPDATED_LAST_NAME = "BBBBBBBBBB"; private static final String DEFAULT_USER_NAME = "AAAAAAAAAA"; private static final String UPDATED_USER_NAME = "BBBBBBBBBB"; private static final String DEFAULT_INSTITUTION = "AAAAAAAAAA"; private static final String UPDATED_INSTITUTION = "BBBBBBBBBB"; private static final String DEFAULT_POSITION = "AAAAAAAAAA"; private static final String UPDATED_POSITION = "BBBBBBBBBB"; private static final String DEFAULT_EMAIL = "AAAAAAAAAA"; private static final String UPDATED_EMAIL = "BBBBBBBBBB"; private static final String DEFAULT_DESCRIPTION = "AAAAAAAAAA"; private static final String UPDATED_DESCRIPTION = "BBBBBBBBBB"; private static final String DEFAULT_IMAGE_URL = "AAAAAAAAAA"; private static final String UPDATED_IMAGE_URL = "BBBBBBBBBB"; private static final UserType DEFAULT_USER_TYPE = UserType.EXPOSITOR; private static final UserType UPDATED_USER_TYPE = UserType.PARTICIPANT; @Autowired private EventUserRepository eventUserRepository; @Autowired private EventUserMapper eventUserMapper; @Autowired private EventUserService eventUserService; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; @Autowired private ExceptionTranslator exceptionTranslator; @Autowired private EntityManager em; private MockMvc restEventUserMockMvc; private EventUser eventUser; @Before public void setup() { MockitoAnnotations.initMocks(this); final EventUserResource eventUserResource = new EventUserResource(eventUserService); this.restEventUserMockMvc = MockMvcBuilders.standaloneSetup(eventUserResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setControllerAdvice(exceptionTranslator) .setConversionService(createFormattingConversionService()) .setMessageConverters(jacksonMessageConverter).build(); } /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static EventUser createEntity(EntityManager em) { EventUser eventUser = new EventUser() .name(DEFAULT_NAME) .lastName(DEFAULT_LAST_NAME) .userName(DEFAULT_USER_NAME) .institution(DEFAULT_INSTITUTION) .position(DEFAULT_POSITION) .email(DEFAULT_EMAIL) .description(DEFAULT_DESCRIPTION) .imageUrl(DEFAULT_IMAGE_URL) .userType(DEFAULT_USER_TYPE); return eventUser; } @Before public void initTest() { eventUser = createEntity(em); } @Test @Transactional public void createEventUser() throws Exception { int databaseSizeBeforeCreate = eventUserRepository.findAll().size(); // Create the EventUser EventUserDTO eventUserDTO = eventUserMapper.toDto(eventUser); restEventUserMockMvc.perform(post("/api/event-users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(eventUserDTO))) .andExpect(status().isCreated()); // Validate the EventUser in the database List<EventUser> eventUserList = eventUserRepository.findAll(); assertThat(eventUserList).hasSize(databaseSizeBeforeCreate + 1); EventUser testEventUser = eventUserList.get(eventUserList.size() - 1); assertThat(testEventUser.getName()).isEqualTo(DEFAULT_NAME); assertThat(testEventUser.getLastName()).isEqualTo(DEFAULT_LAST_NAME); assertThat(testEventUser.getUserName()).isEqualTo(DEFAULT_USER_NAME); assertThat(testEventUser.getInstitution()).isEqualTo(DEFAULT_INSTITUTION); assertThat(testEventUser.getPosition()).isEqualTo(DEFAULT_POSITION); assertThat(testEventUser.getEmail()).isEqualTo(DEFAULT_EMAIL); assertThat(testEventUser.getDescription()).isEqualTo(DEFAULT_DESCRIPTION); assertThat(testEventUser.getImageUrl()).isEqualTo(DEFAULT_IMAGE_URL); assertThat(testEventUser.getUserType()).isEqualTo(DEFAULT_USER_TYPE); } @Test @Transactional public void createEventUserWithExistingId() throws Exception { int databaseSizeBeforeCreate = eventUserRepository.findAll().size(); // Create the EventUser with an existing ID eventUser.setId(1L); EventUserDTO eventUserDTO = eventUserMapper.toDto(eventUser); // An entity with an existing ID cannot be created, so this API call must fail restEventUserMockMvc.perform(post("/api/event-users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(eventUserDTO))) .andExpect(status().isBadRequest()); // Validate the EventUser in the database List<EventUser> eventUserList = eventUserRepository.findAll(); assertThat(eventUserList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void getAllEventUsers() throws Exception { // Initialize the database eventUserRepository.saveAndFlush(eventUser); // Get all the eventUserList restEventUserMockMvc.perform(get("/api/event-users?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(eventUser.getId().intValue()))) .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString()))) .andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LAST_NAME.toString()))) .andExpect(jsonPath("$.[*].userName").value(hasItem(DEFAULT_USER_NAME.toString()))) .andExpect(jsonPath("$.[*].institution").value(hasItem(DEFAULT_INSTITUTION.toString()))) .andExpect(jsonPath("$.[*].position").value(hasItem(DEFAULT_POSITION.toString()))) .andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL.toString()))) .andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION.toString()))) .andExpect(jsonPath("$.[*].imageUrl").value(hasItem(DEFAULT_IMAGE_URL.toString()))) .andExpect(jsonPath("$.[*].userType").value(hasItem(DEFAULT_USER_TYPE.toString()))); } @Test @Transactional public void getEventUser() throws Exception { // Initialize the database eventUserRepository.saveAndFlush(eventUser); // Get the eventUser restEventUserMockMvc.perform(get("/api/event-users/{id}", eventUser.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(eventUser.getId().intValue())) .andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString())) .andExpect(jsonPath("$.lastName").value(DEFAULT_LAST_NAME.toString())) .andExpect(jsonPath("$.userName").value(DEFAULT_USER_NAME.toString())) .andExpect(jsonPath("$.institution").value(DEFAULT_INSTITUTION.toString())) .andExpect(jsonPath("$.position").value(DEFAULT_POSITION.toString())) .andExpect(jsonPath("$.email").value(DEFAULT_EMAIL.toString())) .andExpect(jsonPath("$.description").value(DEFAULT_DESCRIPTION.toString())) .andExpect(jsonPath("$.imageUrl").value(DEFAULT_IMAGE_URL.toString())) .andExpect(jsonPath("$.userType").value(DEFAULT_USER_TYPE.toString())); } @Test @Transactional public void getNonExistingEventUser() throws Exception { // Get the eventUser restEventUserMockMvc.perform(get("/api/event-users/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test @Transactional public void updateEventUser() throws Exception { // Initialize the database eventUserRepository.saveAndFlush(eventUser); int databaseSizeBeforeUpdate = eventUserRepository.findAll().size(); // Update the eventUser EventUser updatedEventUser = eventUserRepository.findById(eventUser.getId()).get(); // Disconnect from session so that the updates on updatedEventUser are not directly saved in db em.detach(updatedEventUser); updatedEventUser .name(UPDATED_NAME) .lastName(UPDATED_LAST_NAME) .userName(UPDATED_USER_NAME) .institution(UPDATED_INSTITUTION) .position(UPDATED_POSITION) .email(UPDATED_EMAIL) .description(UPDATED_DESCRIPTION) .imageUrl(UPDATED_IMAGE_URL) .userType(UPDATED_USER_TYPE); EventUserDTO eventUserDTO = eventUserMapper.toDto(updatedEventUser); restEventUserMockMvc.perform(put("/api/event-users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(eventUserDTO))) .andExpect(status().isOk()); // Validate the EventUser in the database List<EventUser> eventUserList = eventUserRepository.findAll(); assertThat(eventUserList).hasSize(databaseSizeBeforeUpdate); EventUser testEventUser = eventUserList.get(eventUserList.size() - 1); assertThat(testEventUser.getName()).isEqualTo(UPDATED_NAME); assertThat(testEventUser.getLastName()).isEqualTo(UPDATED_LAST_NAME); assertThat(testEventUser.getUserName()).isEqualTo(UPDATED_USER_NAME); assertThat(testEventUser.getInstitution()).isEqualTo(UPDATED_INSTITUTION); assertThat(testEventUser.getPosition()).isEqualTo(UPDATED_POSITION); assertThat(testEventUser.getEmail()).isEqualTo(UPDATED_EMAIL); assertThat(testEventUser.getDescription()).isEqualTo(UPDATED_DESCRIPTION); assertThat(testEventUser.getImageUrl()).isEqualTo(UPDATED_IMAGE_URL); assertThat(testEventUser.getUserType()).isEqualTo(UPDATED_USER_TYPE); } @Test @Transactional public void updateNonExistingEventUser() throws Exception { int databaseSizeBeforeUpdate = eventUserRepository.findAll().size(); // Create the EventUser EventUserDTO eventUserDTO = eventUserMapper.toDto(eventUser); // If the entity doesn't have an ID, it will be created instead of just being updated restEventUserMockMvc.perform(put("/api/event-users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(eventUserDTO))) .andExpect(status().isBadRequest()); // Validate the EventUser in the database List<EventUser> eventUserList = eventUserRepository.findAll(); assertThat(eventUserList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional public void deleteEventUser() throws Exception { // Initialize the database eventUserRepository.saveAndFlush(eventUser); int databaseSizeBeforeDelete = eventUserRepository.findAll().size(); // Get the eventUser restEventUserMockMvc.perform(delete("/api/event-users/{id}", eventUser.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate the database is empty List<EventUser> eventUserList = eventUserRepository.findAll(); assertThat(eventUserList).hasSize(databaseSizeBeforeDelete - 1); } @Test @Transactional public void equalsVerifier() throws Exception { TestUtil.equalsVerifier(EventUser.class); EventUser eventUser1 = new EventUser(); eventUser1.setId(1L); EventUser eventUser2 = new EventUser(); eventUser2.setId(eventUser1.getId()); assertThat(eventUser1).isEqualTo(eventUser2); eventUser2.setId(2L); assertThat(eventUser1).isNotEqualTo(eventUser2); eventUser1.setId(null); assertThat(eventUser1).isNotEqualTo(eventUser2); } @Test @Transactional public void dtoEqualsVerifier() throws Exception { TestUtil.equalsVerifier(EventUserDTO.class); EventUserDTO eventUserDTO1 = new EventUserDTO(); eventUserDTO1.setId(1L); EventUserDTO eventUserDTO2 = new EventUserDTO(); assertThat(eventUserDTO1).isNotEqualTo(eventUserDTO2); eventUserDTO2.setId(eventUserDTO1.getId()); assertThat(eventUserDTO1).isEqualTo(eventUserDTO2); eventUserDTO2.setId(2L); assertThat(eventUserDTO1).isNotEqualTo(eventUserDTO2); eventUserDTO1.setId(null); assertThat(eventUserDTO1).isNotEqualTo(eventUserDTO2); } @Test @Transactional public void testEntityFromId() { assertThat(eventUserMapper.fromId(42L).getId()).isEqualTo(42); assertThat(eventUserMapper.fromId(null)).isNull(); } } <file_sep>/src/main/java/com/gob/scjn/service/impl/MenuServiceImpl.java package com.gob.scjn.service.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.gob.scjn.domain.Site; import com.gob.scjn.repository.SiteRepository; import com.gob.scjn.service.MenuService; import com.gob.scjn.service.dto.MenuDTO; import com.gob.scjn.service.mapper.MenuMapper; /** * Service Implementation for managing Menu. */ @Service @Transactional public class MenuServiceImpl implements MenuService { private final Logger log = LoggerFactory.getLogger(MenuServiceImpl.class); private final MenuMapper menuMapper; private final SiteRepository siteRepository; public MenuServiceImpl(MenuMapper menuMapper, SiteRepository siteRepository) { this.menuMapper = menuMapper; this.siteRepository = siteRepository; } /** * Save a menu. * * @param menuDTO * the entity to save * @return the persisted entity */ @Override public MenuDTO save(Long id, MenuDTO menuDTO) { log.debug("Request to save Menu : {}", menuDTO); Site site = findByEventId(id); site.setMenu(menuMapper.toEntity(menuDTO)); site = siteRepository.save(site); return menuMapper.toDto(site.getMenu()); } /** * Get one menu by id. * * @param id * the id of the entity * @return the entity */ @Override @Transactional(readOnly = true) public MenuDTO findOne(Long id) { Site site = findByEventId(id); System.out.println(site); return menuMapper.toDto(site.getMenu()); } /** * Delete the menu by id. * * @param id * the id of the entity */ @Override public void delete(Long id) { Site site = findByEventId(id); site.setMenu(null); siteRepository.save(site); } private Site findByEventId(Long id) { return siteRepository.findById(id).get(); } } <file_sep>/src/main/java/com/gob/scjn/service/mapper/MenuItemsMapper.java package com.gob.scjn.service.mapper; import com.gob.scjn.domain.*; import com.gob.scjn.service.dto.MenuItemsDTO; import org.mapstruct.*; /** * Mapper for the entity MenuItems and its DTO MenuItemsDTO. */ @Mapper(componentModel = "spring", uses = {MenuItemsLanguageMapper.class}) public interface MenuItemsMapper extends EntityMapper<MenuItemsDTO, MenuItems> { MenuItems toEntity(MenuItemsDTO menuItemsDTO); default MenuItems fromId(Long id) { if (id == null) { return null; } MenuItems menuItems = new MenuItems(); menuItems.setId(id); return menuItems; } } <file_sep>/src/main/java/com/gob/scjn/repository/CMSRepository.java package com.gob.scjn.repository; import com.gob.scjn.domain.CMS; import org.springframework.data.jpa.repository.*; import org.springframework.stereotype.Repository; /** * Spring Data repository for the CMS entity. */ @SuppressWarnings("unused") @Repository public interface CMSRepository extends JpaRepository<CMS, Long> { } <file_sep>/src/main/java/com/gob/scjn/repository/EventLanguageRepository.java package com.gob.scjn.repository; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.gob.scjn.domain.EventLanguage; /** * Spring Data repository for the EventLanguage entity. */ @SuppressWarnings("unused") @Repository public interface EventLanguageRepository extends JpaRepository<EventLanguage, Long> { } <file_sep>/src/main/java/com/gob/scjn/domain/enumeration/UserType.java package com.gob.scjn.domain.enumeration; /** * The UserType enumeration. */ public enum UserType { EXPOSITOR, PARTICIPANT, ORGANIZER } <file_sep>/src/main/java/com/gob/scjn/repository/MenuItemsRepository.java package com.gob.scjn.repository; import com.gob.scjn.domain.MenuItems; import org.springframework.data.jpa.repository.*; import org.springframework.stereotype.Repository; /** * Spring Data repository for the MenuItems entity. */ @SuppressWarnings("unused") @Repository public interface MenuItemsRepository extends JpaRepository<MenuItems, Long> { } <file_sep>/src/main/java/com/gob/scjn/repository/EventUserRepository.java package com.gob.scjn.repository; import com.gob.scjn.domain.EventUser; import org.springframework.data.jpa.repository.*; import org.springframework.stereotype.Repository; /** * Spring Data repository for the EventUser entity. */ @SuppressWarnings("unused") @Repository public interface EventUserRepository extends JpaRepository<EventUser, Long> { } <file_sep>/src/test/java/com/gob/scjn/web/rest/SitePageResourceIntTest.java package com.gob.scjn.web.rest; import com.gob.scjn.EventApp; import com.gob.scjn.domain.SitePage; import com.gob.scjn.repository.SitePageRepository; import com.gob.scjn.service.SitePageService; import com.gob.scjn.service.dto.SitePageDTO; import com.gob.scjn.service.mapper.SitePageMapper; import com.gob.scjn.web.rest.errors.ExceptionTranslator; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import static com.gob.scjn.web.rest.TestUtil.createFormattingConversionService; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the SitePageResource REST controller. * * @see SitePageResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = EventApp.class) public class SitePageResourceIntTest { private static final Instant DEFAULT_CREATION_DATE = Instant.ofEpochMilli(0L); private static final Instant UPDATED_CREATION_DATE = Instant.now().truncatedTo(ChronoUnit.MILLIS); private static final Instant DEFAULT_UPDATED_DATE = Instant.ofEpochMilli(0L); private static final Instant UPDATED_UPDATED_DATE = Instant.now().truncatedTo(ChronoUnit.MILLIS); private static final String DEFAULT_MENU_ENTRY = "AAAAAAAAAA"; private static final String UPDATED_MENU_ENTRY = "BBBBBBBBBB"; private static final Long DEFAULT_ORDER = 1L; private static final Long UPDATED_ORDER = 2L; private static final Boolean DEFAULT_STATUS = false; private static final Boolean UPDATED_STATUS = true; private static final String DEFAULT_SLUG = "AAAAAAAAAA"; private static final String UPDATED_SLUG = "BBBBBBBBBB"; @Autowired private SitePageRepository sitePageRepository; @Autowired private SitePageMapper sitePageMapper; @Autowired private SitePageService sitePageService; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; @Autowired private ExceptionTranslator exceptionTranslator; @Autowired private EntityManager em; private MockMvc restSitePageMockMvc; private SitePage sitePage; @Before public void setup() { MockitoAnnotations.initMocks(this); final SitePageResource sitePageResource = new SitePageResource(sitePageService); this.restSitePageMockMvc = MockMvcBuilders.standaloneSetup(sitePageResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setControllerAdvice(exceptionTranslator) .setConversionService(createFormattingConversionService()) .setMessageConverters(jacksonMessageConverter).build(); } /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static SitePage createEntity(EntityManager em) { SitePage sitePage = new SitePage() .creationDate(DEFAULT_CREATION_DATE) .updatedDate(DEFAULT_UPDATED_DATE) .menuEntry(DEFAULT_MENU_ENTRY) .order(DEFAULT_ORDER) .status(DEFAULT_STATUS) .slug(DEFAULT_SLUG); return sitePage; } @Before public void initTest() { sitePage = createEntity(em); } @Test @Transactional public void createSitePage() throws Exception { int databaseSizeBeforeCreate = sitePageRepository.findAll().size(); // Create the SitePage SitePageDTO sitePageDTO = sitePageMapper.toDto(sitePage); restSitePageMockMvc.perform(post("/api/site-pages") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(sitePageDTO))) .andExpect(status().isCreated()); // Validate the SitePage in the database List<SitePage> sitePageList = sitePageRepository.findAll(); assertThat(sitePageList).hasSize(databaseSizeBeforeCreate + 1); SitePage testSitePage = sitePageList.get(sitePageList.size() - 1); assertThat(testSitePage.getCreationDate()).isEqualTo(DEFAULT_CREATION_DATE); assertThat(testSitePage.getUpdatedDate()).isEqualTo(DEFAULT_UPDATED_DATE); assertThat(testSitePage.getMenuEntry()).isEqualTo(DEFAULT_MENU_ENTRY); assertThat(testSitePage.getOrder()).isEqualTo(DEFAULT_ORDER); assertThat(testSitePage.isStatus()).isEqualTo(DEFAULT_STATUS); assertThat(testSitePage.getSlug()).isEqualTo(DEFAULT_SLUG); } @Test @Transactional public void createSitePageWithExistingId() throws Exception { int databaseSizeBeforeCreate = sitePageRepository.findAll().size(); // Create the SitePage with an existing ID sitePage.setId(1L); SitePageDTO sitePageDTO = sitePageMapper.toDto(sitePage); // An entity with an existing ID cannot be created, so this API call must fail restSitePageMockMvc.perform(post("/api/site-pages") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(sitePageDTO))) .andExpect(status().isBadRequest()); // Validate the SitePage in the database List<SitePage> sitePageList = sitePageRepository.findAll(); assertThat(sitePageList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void getAllSitePages() throws Exception { // Initialize the database sitePageRepository.saveAndFlush(sitePage); // Get all the sitePageList restSitePageMockMvc.perform(get("/api/site-pages?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(sitePage.getId().intValue()))) .andExpect(jsonPath("$.[*].creationDate").value(hasItem(DEFAULT_CREATION_DATE.toString()))) .andExpect(jsonPath("$.[*].updatedDate").value(hasItem(DEFAULT_UPDATED_DATE.toString()))) .andExpect(jsonPath("$.[*].menuEntry").value(hasItem(DEFAULT_MENU_ENTRY.toString()))) .andExpect(jsonPath("$.[*].order").value(hasItem(DEFAULT_ORDER.intValue()))) .andExpect(jsonPath("$.[*].status").value(hasItem(DEFAULT_STATUS.booleanValue()))) .andExpect(jsonPath("$.[*].slug").value(hasItem(DEFAULT_SLUG.toString()))); } @Test @Transactional public void getSitePage() throws Exception { // Initialize the database sitePageRepository.saveAndFlush(sitePage); // Get the sitePage restSitePageMockMvc.perform(get("/api/site-pages/{id}", sitePage.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(sitePage.getId().intValue())) .andExpect(jsonPath("$.creationDate").value(DEFAULT_CREATION_DATE.toString())) .andExpect(jsonPath("$.updatedDate").value(DEFAULT_UPDATED_DATE.toString())) .andExpect(jsonPath("$.menuEntry").value(DEFAULT_MENU_ENTRY.toString())) .andExpect(jsonPath("$.order").value(DEFAULT_ORDER.intValue())) .andExpect(jsonPath("$.status").value(DEFAULT_STATUS.booleanValue())) .andExpect(jsonPath("$.slug").value(DEFAULT_SLUG.toString())); } @Test @Transactional public void getNonExistingSitePage() throws Exception { // Get the sitePage restSitePageMockMvc.perform(get("/api/site-pages/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test @Transactional public void updateSitePage() throws Exception { // Initialize the database sitePageRepository.saveAndFlush(sitePage); int databaseSizeBeforeUpdate = sitePageRepository.findAll().size(); // Update the sitePage SitePage updatedSitePage = sitePageRepository.findById(sitePage.getId()).get(); // Disconnect from session so that the updates on updatedSitePage are not directly saved in db em.detach(updatedSitePage); updatedSitePage .creationDate(UPDATED_CREATION_DATE) .updatedDate(UPDATED_UPDATED_DATE) .menuEntry(UPDATED_MENU_ENTRY) .order(UPDATED_ORDER) .status(UPDATED_STATUS) .slug(UPDATED_SLUG); SitePageDTO sitePageDTO = sitePageMapper.toDto(updatedSitePage); restSitePageMockMvc.perform(put("/api/site-pages") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(sitePageDTO))) .andExpect(status().isOk()); // Validate the SitePage in the database List<SitePage> sitePageList = sitePageRepository.findAll(); assertThat(sitePageList).hasSize(databaseSizeBeforeUpdate); SitePage testSitePage = sitePageList.get(sitePageList.size() - 1); assertThat(testSitePage.getCreationDate()).isEqualTo(UPDATED_CREATION_DATE); assertThat(testSitePage.getUpdatedDate()).isEqualTo(UPDATED_UPDATED_DATE); assertThat(testSitePage.getMenuEntry()).isEqualTo(UPDATED_MENU_ENTRY); assertThat(testSitePage.getOrder()).isEqualTo(UPDATED_ORDER); assertThat(testSitePage.isStatus()).isEqualTo(UPDATED_STATUS); assertThat(testSitePage.getSlug()).isEqualTo(UPDATED_SLUG); } @Test @Transactional public void updateNonExistingSitePage() throws Exception { int databaseSizeBeforeUpdate = sitePageRepository.findAll().size(); // Create the SitePage SitePageDTO sitePageDTO = sitePageMapper.toDto(sitePage); // If the entity doesn't have an ID, it will be created instead of just being updated restSitePageMockMvc.perform(put("/api/site-pages") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(sitePageDTO))) .andExpect(status().isBadRequest()); // Validate the SitePage in the database List<SitePage> sitePageList = sitePageRepository.findAll(); assertThat(sitePageList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional public void deleteSitePage() throws Exception { // Initialize the database sitePageRepository.saveAndFlush(sitePage); int databaseSizeBeforeDelete = sitePageRepository.findAll().size(); // Get the sitePage restSitePageMockMvc.perform(delete("/api/site-pages/{id}", sitePage.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate the database is empty List<SitePage> sitePageList = sitePageRepository.findAll(); assertThat(sitePageList).hasSize(databaseSizeBeforeDelete - 1); } @Test @Transactional public void equalsVerifier() throws Exception { TestUtil.equalsVerifier(SitePage.class); SitePage sitePage1 = new SitePage(); sitePage1.setId(1L); SitePage sitePage2 = new SitePage(); sitePage2.setId(sitePage1.getId()); assertThat(sitePage1).isEqualTo(sitePage2); sitePage2.setId(2L); assertThat(sitePage1).isNotEqualTo(sitePage2); sitePage1.setId(null); assertThat(sitePage1).isNotEqualTo(sitePage2); } @Test @Transactional public void dtoEqualsVerifier() throws Exception { TestUtil.equalsVerifier(SitePageDTO.class); SitePageDTO sitePageDTO1 = new SitePageDTO(); sitePageDTO1.setId(1L); SitePageDTO sitePageDTO2 = new SitePageDTO(); assertThat(sitePageDTO1).isNotEqualTo(sitePageDTO2); sitePageDTO2.setId(sitePageDTO1.getId()); assertThat(sitePageDTO1).isEqualTo(sitePageDTO2); sitePageDTO2.setId(2L); assertThat(sitePageDTO1).isNotEqualTo(sitePageDTO2); sitePageDTO1.setId(null); assertThat(sitePageDTO1).isNotEqualTo(sitePageDTO2); } @Test @Transactional public void testEntityFromId() { assertThat(sitePageMapper.fromId(42L).getId()).isEqualTo(42); assertThat(sitePageMapper.fromId(null)).isNull(); } } <file_sep>/.apt_generated/com/gob/scjn/service/mapper/SitePageLanguageMapperImpl.java package com.gob.scjn.service.mapper; import com.gob.scjn.domain.SitePage; import com.gob.scjn.domain.SitePageLanguage; import com.gob.scjn.service.dto.SitePageLanguageDTO; import java.util.ArrayList; import java.util.List; import javax.annotation.Generated; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Generated( value = "org.mapstruct.ap.MappingProcessor", date = "2018-07-21T14:51:12-0500", comments = "version: 1.2.0.Final, compiler: Eclipse JDT (IDE) 3.12.3.v20170228-1205, environment: Java 1.8.0_171 (Oracle Corporation)" ) @Component public class SitePageLanguageMapperImpl implements SitePageLanguageMapper { @Autowired private SitePageMapper sitePageMapper; @Override public List<SitePageLanguage> toEntity(List<SitePageLanguageDTO> dtoList) { if ( dtoList == null ) { return null; } List<SitePageLanguage> list = new ArrayList<SitePageLanguage>( dtoList.size() ); for ( SitePageLanguageDTO sitePageLanguageDTO : dtoList ) { list.add( toEntity( sitePageLanguageDTO ) ); } return list; } @Override public List<SitePageLanguageDTO> toDto(List<SitePageLanguage> entityList) { if ( entityList == null ) { return null; } List<SitePageLanguageDTO> list = new ArrayList<SitePageLanguageDTO>( entityList.size() ); for ( SitePageLanguage sitePageLanguage : entityList ) { list.add( toDto( sitePageLanguage ) ); } return list; } @Override public SitePageLanguageDTO toDto(SitePageLanguage sitePageLanguage) { if ( sitePageLanguage == null ) { return null; } SitePageLanguageDTO sitePageLanguageDTO = new SitePageLanguageDTO(); Long id = sitePageLanguageSitePageId( sitePageLanguage ); if ( id != null ) { sitePageLanguageDTO.setSitePageId( id ); } sitePageLanguageDTO.setId( sitePageLanguage.getId() ); sitePageLanguageDTO.setExceptPage( sitePageLanguage.getExceptPage() ); sitePageLanguageDTO.setContent( sitePageLanguage.getContent() ); sitePageLanguageDTO.setTitle( sitePageLanguage.getTitle() ); sitePageLanguageDTO.setLanguage( sitePageLanguage.getLanguage() ); return sitePageLanguageDTO; } @Override public SitePageLanguage toEntity(SitePageLanguageDTO sitePageLanguageDTO) { if ( sitePageLanguageDTO == null ) { return null; } SitePageLanguage sitePageLanguage = new SitePageLanguage(); sitePageLanguage.setSitePage( sitePageMapper.fromId( sitePageLanguageDTO.getSitePageId() ) ); sitePageLanguage.setId( sitePageLanguageDTO.getId() ); sitePageLanguage.setExceptPage( sitePageLanguageDTO.getExceptPage() ); sitePageLanguage.setContent( sitePageLanguageDTO.getContent() ); sitePageLanguage.setTitle( sitePageLanguageDTO.getTitle() ); sitePageLanguage.setLanguage( sitePageLanguageDTO.getLanguage() ); return sitePageLanguage; } private Long sitePageLanguageSitePageId(SitePageLanguage sitePageLanguage) { if ( sitePageLanguage == null ) { return null; } SitePage sitePage = sitePageLanguage.getSitePage(); if ( sitePage == null ) { return null; } Long id = sitePage.getId(); if ( id == null ) { return null; } return id; } } <file_sep>/src/main/java/com/gob/scjn/web/rest/package-info.java /** * Spring MVC REST controllers. */ package com.gob.scjn.web.rest; <file_sep>/src/main/java/com/gob/scjn/service/impl/SitePageLanguageServiceImpl.java package com.gob.scjn.service.impl; import com.gob.scjn.service.SitePageLanguageService; import com.gob.scjn.domain.SitePageLanguage; import com.gob.scjn.repository.SitePageLanguageRepository; import com.gob.scjn.service.dto.SitePageLanguageDTO; import com.gob.scjn.service.mapper.SitePageLanguageMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; /** * Service Implementation for managing SitePageLanguage. */ @Service @Transactional public class SitePageLanguageServiceImpl implements SitePageLanguageService { private final Logger log = LoggerFactory.getLogger(SitePageLanguageServiceImpl.class); private final SitePageLanguageRepository sitePageLanguageRepository; private final SitePageLanguageMapper sitePageLanguageMapper; public SitePageLanguageServiceImpl(SitePageLanguageRepository sitePageLanguageRepository, SitePageLanguageMapper sitePageLanguageMapper) { this.sitePageLanguageRepository = sitePageLanguageRepository; this.sitePageLanguageMapper = sitePageLanguageMapper; } /** * Save a sitePageLanguage. * * @param sitePageLanguageDTO the entity to save * @return the persisted entity */ @Override public SitePageLanguageDTO save(SitePageLanguageDTO sitePageLanguageDTO) { log.debug("Request to save SitePageLanguage : {}", sitePageLanguageDTO); SitePageLanguage sitePageLanguage = sitePageLanguageMapper.toEntity(sitePageLanguageDTO); sitePageLanguage = sitePageLanguageRepository.save(sitePageLanguage); return sitePageLanguageMapper.toDto(sitePageLanguage); } /** * Get all the sitePageLanguages. * * @param pageable the pagination information * @return the list of entities */ @Override @Transactional(readOnly = true) public Page<SitePageLanguageDTO> findAll(Pageable pageable) { log.debug("Request to get all SitePageLanguages"); return sitePageLanguageRepository.findAll(pageable) .map(sitePageLanguageMapper::toDto); } /** * Get one sitePageLanguage by id. * * @param id the id of the entity * @return the entity */ @Override @Transactional(readOnly = true) public Optional<SitePageLanguageDTO> findOne(Long id) { log.debug("Request to get SitePageLanguage : {}", id); return sitePageLanguageRepository.findById(id) .map(sitePageLanguageMapper::toDto); } /** * Delete the sitePageLanguage by id. * * @param id the id of the entity */ @Override public void delete(Long id) { log.debug("Request to delete SitePageLanguage : {}", id); sitePageLanguageRepository.deleteById(id); } } <file_sep>/src/main/java/com/gob/scjn/web/rest/SiteColorPaletteResource.java package com.gob.scjn.web.rest; import java.net.URISyntaxException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.codahale.metrics.annotation.Timed; import com.gob.scjn.service.SiteColorPaletteService; import com.gob.scjn.service.dto.SiteColorPaletteDTO; import com.gob.scjn.web.rest.util.HeaderUtil; /** * REST controller for managing SiteColorPalette. */ @RestController @RequestMapping("/api") public class SiteColorPaletteResource { private final Logger log = LoggerFactory.getLogger(SiteColorPaletteResource.class); private static final String ENTITY_NAME = "siteColorPalette"; private final SiteColorPaletteService siteColorPaletteService; public SiteColorPaletteResource(SiteColorPaletteService siteColorPaletteService) { this.siteColorPaletteService = siteColorPaletteService; } /** * POST /site-color-palettes : Create a new siteColorPalette. * * @param siteColorPaletteDTO * the siteColorPaletteDTO to create * @return the ResponseEntity with status 201 (Created) and with body the new * siteColorPaletteDTO, or with status 400 (Bad Request) if the * siteColorPalette has already an ID * @throws URISyntaxException * if the Location URI syntax is incorrect */ @PostMapping("/site/{id}/color-palette") public ResponseEntity<SiteColorPaletteDTO> createFooterEntity(@PathVariable Long id, @RequestBody SiteColorPaletteDTO siteColorPaletteDTO) { SiteColorPaletteDTO result = siteColorPaletteService.save(id,siteColorPaletteDTO); return new ResponseEntity<>(result, HttpStatus.CREATED); } /** * PUT /site-color-palettes : Updates an existing siteColorPalette. * * @param siteColorPaletteDTO * the siteColorPaletteDTO to update * @return the ResponseEntity with status 200 (OK) and with body the updated * siteColorPaletteDTO, or with status 400 (Bad Request) if the * siteColorPaletteDTO is not valid, or with status 500 (Internal Server * Error) if the siteColorPaletteDTO couldn't be updated * @throws URISyntaxException * if the Location URI syntax is incorrect */ @PutMapping("/site/{id}/color-palette") @Timed public ResponseEntity<SiteColorPaletteDTO> updateSiteColorPalette(@PathVariable Long id, @RequestBody SiteColorPaletteDTO siteColorPaletteDTO) throws URISyntaxException { SiteColorPaletteDTO result = siteColorPaletteService.save(id, siteColorPaletteDTO); return new ResponseEntity<>(result, HttpStatus.OK); } /** * GET /site-color-palettes : get all the siteColorPalettes. * * @param pageable * the pagination information * @return the ResponseEntity with status 200 (OK) and the list of * siteColorPalettes in body */ @GetMapping("/site/{id}/color-palette") @Timed public ResponseEntity<SiteColorPaletteDTO> getAllSiteColorPalettes(@PathVariable Long id) { log.debug("REST request to get a page of SiteColorPalettes"); SiteColorPaletteDTO sitePalette = siteColorPaletteService.findOne(id); return new ResponseEntity<>(sitePalette, HttpStatus.OK); } /** * DELETE /site-color-palettes/:id : delete the "id" siteColorPalette. * * @param id * the id of the siteColorPaletteDTO to delete * @return the ResponseEntity with status 200 (OK) */ @DeleteMapping("/site/{id}/color-palette") @Timed public ResponseEntity<Void> deleteSiteColorPalette(@PathVariable Long id) { log.debug("REST request to delete SiteColorPalette : {}", id); siteColorPaletteService.delete(id); return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build(); } } <file_sep>/src/main/java/com/gob/scjn/service/impl/ActivityLanguageServiceImpl.java package com.gob.scjn.service.impl; import com.gob.scjn.service.ActivityLanguageService; import com.gob.scjn.domain.ActivityLanguage; import com.gob.scjn.repository.ActivityLanguageRepository; import com.gob.scjn.service.dto.ActivityLanguageDTO; import com.gob.scjn.service.mapper.ActivityLanguageMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; /** * Service Implementation for managing ActivityLanguage. */ @Service @Transactional public class ActivityLanguageServiceImpl implements ActivityLanguageService { private final Logger log = LoggerFactory.getLogger(ActivityLanguageServiceImpl.class); private final ActivityLanguageRepository activityLanguageRepository; private final ActivityLanguageMapper activityLanguageMapper; public ActivityLanguageServiceImpl(ActivityLanguageRepository activityLanguageRepository, ActivityLanguageMapper activityLanguageMapper) { this.activityLanguageRepository = activityLanguageRepository; this.activityLanguageMapper = activityLanguageMapper; } /** * Save a activityLanguage. * * @param activityLanguageDTO the entity to save * @return the persisted entity */ @Override public ActivityLanguageDTO save(ActivityLanguageDTO activityLanguageDTO) { log.debug("Request to save ActivityLanguage : {}", activityLanguageDTO); ActivityLanguage activityLanguage = activityLanguageMapper.toEntity(activityLanguageDTO); activityLanguage = activityLanguageRepository.save(activityLanguage); return activityLanguageMapper.toDto(activityLanguage); } /** * Get all the activityLanguages. * * @param pageable the pagination information * @return the list of entities */ @Override @Transactional(readOnly = true) public Page<ActivityLanguageDTO> findAll(Pageable pageable) { log.debug("Request to get all ActivityLanguages"); return activityLanguageRepository.findAll(pageable) .map(activityLanguageMapper::toDto); } /** * Get one activityLanguage by id. * * @param id the id of the entity * @return the entity */ @Override @Transactional(readOnly = true) public Optional<ActivityLanguageDTO> findOne(Long id) { log.debug("Request to get ActivityLanguage : {}", id); return activityLanguageRepository.findById(id) .map(activityLanguageMapper::toDto); } /** * Delete the activityLanguage by id. * * @param id the id of the entity */ @Override public void delete(Long id) { log.debug("Request to delete ActivityLanguage : {}", id); activityLanguageRepository.deleteById(id); } } <file_sep>/.apt_generated/com/gob/scjn/service/mapper/ActivityLanguageMapperImpl.java package com.gob.scjn.service.mapper; import com.gob.scjn.domain.ActivityLanguage; import com.gob.scjn.service.dto.ActivityLanguageDTO; import java.util.ArrayList; import java.util.List; import javax.annotation.Generated; import org.springframework.stereotype.Component; @Generated( value = "org.mapstruct.ap.MappingProcessor", date = "2018-07-24T19:22:04-0500", comments = "version: 1.2.0.Final, compiler: Eclipse JDT (IDE) 3.12.3.v20170228-1205, environment: Java 1.8.0_171 (Oracle Corporation)" ) @Component public class ActivityLanguageMapperImpl implements ActivityLanguageMapper { @Override public List<ActivityLanguageDTO> toDto(List<ActivityLanguage> arg0) { if ( arg0 == null ) { return null; } List<ActivityLanguageDTO> list = new ArrayList<ActivityLanguageDTO>( arg0.size() ); for ( ActivityLanguage activityLanguage : arg0 ) { list.add( toDto( activityLanguage ) ); } return list; } @Override public List<ActivityLanguage> toEntity(List<ActivityLanguageDTO> arg0) { if ( arg0 == null ) { return null; } List<ActivityLanguage> list = new ArrayList<ActivityLanguage>( arg0.size() ); for ( ActivityLanguageDTO activityLanguageDTO : arg0 ) { list.add( toEntity( activityLanguageDTO ) ); } return list; } @Override public ActivityLanguageDTO toDto(ActivityLanguage activityLanguage) { if ( activityLanguage == null ) { return null; } ActivityLanguageDTO activityLanguageDTO = new ActivityLanguageDTO(); activityLanguageDTO.setAddress( activityLanguage.getAddress() ); activityLanguageDTO.setDescription( activityLanguage.getDescription() ); activityLanguageDTO.setId( activityLanguage.getId() ); activityLanguageDTO.setLanguage( activityLanguage.getLanguage() ); activityLanguageDTO.setName( activityLanguage.getName() ); return activityLanguageDTO; } @Override public ActivityLanguage toEntity(ActivityLanguageDTO activityLanguageDTO) { if ( activityLanguageDTO == null ) { return null; } ActivityLanguage activityLanguage = new ActivityLanguage(); activityLanguage.setId( activityLanguageDTO.getId() ); activityLanguage.setName( activityLanguageDTO.getName() ); activityLanguage.setDescription( activityLanguageDTO.getDescription() ); activityLanguage.setAddress( activityLanguageDTO.getAddress() ); activityLanguage.setLanguage( activityLanguageDTO.getLanguage() ); return activityLanguage; } } <file_sep>/src/main/java/com/gob/scjn/web/rest/SitePageLanguageResource.java package com.gob.scjn.web.rest; import com.codahale.metrics.annotation.Timed; import com.gob.scjn.service.SitePageLanguageService; import com.gob.scjn.web.rest.errors.BadRequestAlertException; import com.gob.scjn.web.rest.util.HeaderUtil; import com.gob.scjn.web.rest.util.PaginationUtil; import com.gob.scjn.service.dto.SitePageLanguageDTO; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; /** * REST controller for managing SitePageLanguage. */ @RestController @RequestMapping("/api") public class SitePageLanguageResource { private final Logger log = LoggerFactory.getLogger(SitePageLanguageResource.class); private static final String ENTITY_NAME = "sitePageLanguage"; private final SitePageLanguageService sitePageLanguageService; public SitePageLanguageResource(SitePageLanguageService sitePageLanguageService) { this.sitePageLanguageService = sitePageLanguageService; } /** * POST /site-page-languages : Create a new sitePageLanguage. * * @param sitePageLanguageDTO the sitePageLanguageDTO to create * @return the ResponseEntity with status 201 (Created) and with body the new sitePageLanguageDTO, or with status 400 (Bad Request) if the sitePageLanguage has already an ID * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/site-page-languages") @Timed public ResponseEntity<SitePageLanguageDTO> createSitePageLanguage(@RequestBody SitePageLanguageDTO sitePageLanguageDTO) throws URISyntaxException { log.debug("REST request to save SitePageLanguage : {}", sitePageLanguageDTO); if (sitePageLanguageDTO.getId() != null) { throw new BadRequestAlertException("A new sitePageLanguage cannot already have an ID", ENTITY_NAME, "idexists"); } SitePageLanguageDTO result = sitePageLanguageService.save(sitePageLanguageDTO); return ResponseEntity.created(new URI("/api/site-page-languages/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) .body(result); } /** * PUT /site-page-languages : Updates an existing sitePageLanguage. * * @param sitePageLanguageDTO the sitePageLanguageDTO to update * @return the ResponseEntity with status 200 (OK) and with body the updated sitePageLanguageDTO, * or with status 400 (Bad Request) if the sitePageLanguageDTO is not valid, * or with status 500 (Internal Server Error) if the sitePageLanguageDTO couldn't be updated * @throws URISyntaxException if the Location URI syntax is incorrect */ @PutMapping("/site-page-languages") @Timed public ResponseEntity<SitePageLanguageDTO> updateSitePageLanguage(@RequestBody SitePageLanguageDTO sitePageLanguageDTO) throws URISyntaxException { log.debug("REST request to update SitePageLanguage : {}", sitePageLanguageDTO); if (sitePageLanguageDTO.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } SitePageLanguageDTO result = sitePageLanguageService.save(sitePageLanguageDTO); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, sitePageLanguageDTO.getId().toString())) .body(result); } /** * GET /site-page-languages : get all the sitePageLanguages. * * @param pageable the pagination information * @return the ResponseEntity with status 200 (OK) and the list of sitePageLanguages in body */ @GetMapping("/site-page-languages") @Timed public ResponseEntity<List<SitePageLanguageDTO>> getAllSitePageLanguages(Pageable pageable) { log.debug("REST request to get a page of SitePageLanguages"); Page<SitePageLanguageDTO> page = sitePageLanguageService.findAll(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/site-page-languages"); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } /** * GET /site-page-languages/:id : get the "id" sitePageLanguage. * * @param id the id of the sitePageLanguageDTO to retrieve * @return the ResponseEntity with status 200 (OK) and with body the sitePageLanguageDTO, or with status 404 (Not Found) */ @GetMapping("/site-page-languages/{id}") @Timed public ResponseEntity<SitePageLanguageDTO> getSitePageLanguage(@PathVariable Long id) { log.debug("REST request to get SitePageLanguage : {}", id); Optional<SitePageLanguageDTO> sitePageLanguageDTO = sitePageLanguageService.findOne(id); return ResponseUtil.wrapOrNotFound(sitePageLanguageDTO); } /** * DELETE /site-page-languages/:id : delete the "id" sitePageLanguage. * * @param id the id of the sitePageLanguageDTO to delete * @return the ResponseEntity with status 200 (OK) */ @DeleteMapping("/site-page-languages/{id}") @Timed public ResponseEntity<Void> deleteSitePageLanguage(@PathVariable Long id) { log.debug("REST request to delete SitePageLanguage : {}", id); sitePageLanguageService.delete(id); return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build(); } } <file_sep>/.apt_generated/com/gob/scjn/service/mapper/MenuItemsMapperImpl.java package com.gob.scjn.service.mapper; import com.gob.scjn.domain.MenuItems; import com.gob.scjn.service.dto.MenuItemsDTO; import java.util.ArrayList; import java.util.List; import javax.annotation.Generated; import org.springframework.stereotype.Component; @Generated( value = "org.mapstruct.ap.MappingProcessor", date = "2018-07-24T20:56:20-0500", comments = "version: 1.2.0.Final, compiler: Eclipse JDT (IDE) 3.12.3.v20170228-1205, environment: Java 1.8.0_171 (Oracle Corporation)" ) @Component public class MenuItemsMapperImpl implements MenuItemsMapper { @Override public MenuItemsDTO toDto(MenuItems arg0) { if ( arg0 == null ) { return null; } MenuItemsDTO menuItemsDTO = new MenuItemsDTO(); menuItemsDTO.setId( arg0.getId() ); menuItemsDTO.setUrl( arg0.getUrl() ); menuItemsDTO.setWeight( arg0.getWeight() ); return menuItemsDTO; } @Override public List<MenuItemsDTO> toDto(List<MenuItems> arg0) { if ( arg0 == null ) { return null; } List<MenuItemsDTO> list = new ArrayList<MenuItemsDTO>( arg0.size() ); for ( MenuItems menuItems : arg0 ) { list.add( toDto( menuItems ) ); } return list; } @Override public List<MenuItems> toEntity(List<MenuItemsDTO> arg0) { if ( arg0 == null ) { return null; } List<MenuItems> list = new ArrayList<MenuItems>( arg0.size() ); for ( MenuItemsDTO menuItemsDTO : arg0 ) { list.add( toEntity( menuItemsDTO ) ); } return list; } @Override public MenuItems toEntity(MenuItemsDTO menuItemsDTO) { if ( menuItemsDTO == null ) { return null; } MenuItems menuItems = new MenuItems(); menuItems.setId( menuItemsDTO.getId() ); menuItems.setUrl( menuItemsDTO.getUrl() ); menuItems.setWeight( menuItemsDTO.getWeight() ); return menuItems; } } <file_sep>/src/main/java/com/gob/scjn/service/mapper/ActivityLanguageMapper.java package com.gob.scjn.service.mapper; import com.gob.scjn.domain.*; import com.gob.scjn.service.dto.ActivityLanguageDTO; import org.mapstruct.*; /** * Mapper for the entity ActivityLanguage and its DTO ActivityLanguageDTO. */ @Mapper(componentModel = "spring", uses = {ActivityMapper.class}) public interface ActivityLanguageMapper extends EntityMapper<ActivityLanguageDTO, ActivityLanguage> { ActivityLanguageDTO toDto(ActivityLanguage activityLanguage); ActivityLanguage toEntity(ActivityLanguageDTO activityLanguageDTO); default ActivityLanguage fromId(Long id) { if (id == null) { return null; } ActivityLanguage activityLanguage = new ActivityLanguage(); activityLanguage.setId(id); return activityLanguage; } } <file_sep>/src/main/java/com/gob/scjn/service/SiteFooterService.java package com.gob.scjn.service; import com.gob.scjn.service.dto.SiteFooterDTO; /** * Service Interface for managing SiteFooter. */ public interface SiteFooterService { /** * Save a siteFooter. * * @param site id & siteFooterDTO the entity to save * @return the persisted entity */ SiteFooterDTO save(Long id, SiteFooterDTO siteFooterDTO); /** * Get footer related to site id. * * @param id the id of the site * @return the entity */ SiteFooterDTO findOne(Long id); /** * Delete the site footer. * * @param id the id of the site */ void delete(Long id); } <file_sep>/.apt_generated/com/gob/scjn/domain/EventUser_.java package com.gob.scjn.domain; import com.gob.scjn.domain.enumeration.UserType; import javax.annotation.Generated; import javax.persistence.metamodel.SetAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor") @StaticMetamodel(EventUser.class) public abstract class EventUser_ { public static volatile SingularAttribute<EventUser, String> lastName; public static volatile SingularAttribute<EventUser, String> institution; public static volatile SingularAttribute<EventUser, String> imageUrl; public static volatile SingularAttribute<EventUser, String> name; public static volatile SetAttribute<EventUser, CMS> cms; public static volatile SingularAttribute<EventUser, String> description; public static volatile SetAttribute<EventUser, Event> sites; public static volatile SingularAttribute<EventUser, Long> id; public static volatile SingularAttribute<EventUser, String> position; public static volatile SingularAttribute<EventUser, UserType> userType; public static volatile SingularAttribute<EventUser, String> userName; public static volatile SingularAttribute<EventUser, String> email; } <file_sep>/src/main/java/com/gob/scjn/domain/enumeration/Language.java package com.gob.scjn.domain.enumeration; /** * The Language enumeration. */ public enum Language { ENGLISH, FRENCH, SPANISH, PORTUGUESE, GERMAN, ITALIAN, RUSSIAN } <file_sep>/src/main/java/com/gob/scjn/service/dto/SitePageLanguageDTO.java package com.gob.scjn.service.dto; import java.io.Serializable; import java.util.Objects; import javax.persistence.Lob; import com.gob.scjn.domain.enumeration.Language; /** * A DTO for the SitePageLanguage entity. */ public class SitePageLanguageDTO implements Serializable { private Long id; @Lob private String exceptPage; @Lob private String content; private String title; private Language language; private Long sitePageId; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getExceptPage() { return exceptPage; } public void setExceptPage(String exceptPage) { this.exceptPage = exceptPage; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Language getLanguage() { return language; } public void setLanguage(Language language) { this.language = language; } public Long getSitePageId() { return sitePageId; } public void setSitePageId(Long sitePageId) { this.sitePageId = sitePageId; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SitePageLanguageDTO sitePageLanguageDTO = (SitePageLanguageDTO) o; if (sitePageLanguageDTO.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), sitePageLanguageDTO.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "SitePageLanguageDTO{" + "id=" + getId() + ", exceptPage='" + getExceptPage() + "'" + ", content='" + getContent() + "'" + ", title='" + getTitle() + "'" + ", language='" + getLanguage() + "'" + ", sitePage=" + getSitePageId() + "}"; } } <file_sep>/src/main/java/com/gob/scjn/web/rest/MenuItemsResource.java package com.gob.scjn.web.rest; import com.codahale.metrics.annotation.Timed; import com.gob.scjn.service.MenuItemsService; import com.gob.scjn.web.rest.errors.BadRequestAlertException; import com.gob.scjn.web.rest.util.HeaderUtil; import com.gob.scjn.service.dto.MenuItemsDTO; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; /** * REST controller for managing MenuItems. */ @RestController @RequestMapping("/api") public class MenuItemsResource { private final Logger log = LoggerFactory.getLogger(MenuItemsResource.class); private static final String ENTITY_NAME = "menuItems"; private final MenuItemsService menuItemsService; public MenuItemsResource(MenuItemsService menuItemsService) { this.menuItemsService = menuItemsService; } /** * POST /menu-items : Create a new menuItems. * * @param menuItemsDTO the menuItemsDTO to create * @return the ResponseEntity with status 201 (Created) and with body the new menuItemsDTO, or with status 400 (Bad Request) if the menuItems has already an ID * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/menu-items") @Timed public ResponseEntity<MenuItemsDTO> createMenuItems(@RequestBody MenuItemsDTO menuItemsDTO) throws URISyntaxException { log.debug("REST request to save MenuItems : {}", menuItemsDTO); if (menuItemsDTO.getId() != null) { throw new BadRequestAlertException("A new menuItems cannot already have an ID", ENTITY_NAME, "idexists"); } MenuItemsDTO result = menuItemsService.save(menuItemsDTO); return ResponseEntity.created(new URI("/api/menu-items/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) .body(result); } /** * PUT /menu-items : Updates an existing menuItems. * * @param menuItemsDTO the menuItemsDTO to update * @return the ResponseEntity with status 200 (OK) and with body the updated menuItemsDTO, * or with status 400 (Bad Request) if the menuItemsDTO is not valid, * or with status 500 (Internal Server Error) if the menuItemsDTO couldn't be updated * @throws URISyntaxException if the Location URI syntax is incorrect */ @PutMapping("/menu-items") @Timed public ResponseEntity<MenuItemsDTO> updateMenuItems(@RequestBody MenuItemsDTO menuItemsDTO) throws URISyntaxException { log.debug("REST request to update MenuItems : {}", menuItemsDTO); if (menuItemsDTO.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } MenuItemsDTO result = menuItemsService.save(menuItemsDTO); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, menuItemsDTO.getId().toString())) .body(result); } /** * GET /menu-items : get all the menuItems. * * @return the ResponseEntity with status 200 (OK) and the list of menuItems in body */ @GetMapping("/menu-items") @Timed public List<MenuItemsDTO> getAllMenuItems() { log.debug("REST request to get all MenuItems"); return menuItemsService.findAll(); } /** * GET /menu-items/:id : get the "id" menuItems. * * @param id the id of the menuItemsDTO to retrieve * @return the ResponseEntity with status 200 (OK) and with body the menuItemsDTO, or with status 404 (Not Found) */ @GetMapping("/menu-items/{id}") @Timed public ResponseEntity<MenuItemsDTO> getMenuItems(@PathVariable Long id) { log.debug("REST request to get MenuItems : {}", id); Optional<MenuItemsDTO> menuItemsDTO = menuItemsService.findOne(id); return ResponseUtil.wrapOrNotFound(menuItemsDTO); } /** * DELETE /menu-items/:id : delete the "id" menuItems. * * @param id the id of the menuItemsDTO to delete * @return the ResponseEntity with status 200 (OK) */ @DeleteMapping("/menu-items/{id}") @Timed public ResponseEntity<Void> deleteMenuItems(@PathVariable Long id) { log.debug("REST request to delete MenuItems : {}", id); menuItemsService.delete(id); return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build(); } } <file_sep>/.apt_generated/com/gob/scjn/service/mapper/SiteFooterMapperImpl.java package com.gob.scjn.service.mapper; import com.gob.scjn.domain.SiteFooter; import com.gob.scjn.service.dto.SiteFooterDTO; import java.util.ArrayList; import java.util.List; import javax.annotation.Generated; import org.springframework.stereotype.Component; @Generated( value = "org.mapstruct.ap.MappingProcessor", date = "2018-07-21T14:51:12-0500", comments = "version: 1.2.0.Final, compiler: Eclipse JDT (IDE) 3.12.3.v20170228-1205, environment: Java 1.8.0_171 (Oracle Corporation)" ) @Component public class SiteFooterMapperImpl implements SiteFooterMapper { @Override public SiteFooter toEntity(SiteFooterDTO dto) { if ( dto == null ) { return null; } SiteFooter siteFooter = new SiteFooter(); siteFooter.setId( dto.getId() ); siteFooter.setAddress( dto.getAddress() ); siteFooter.setContact( dto.getContact() ); siteFooter.setLinks( dto.getLinks() ); siteFooter.setMoreContent( dto.getMoreContent() ); siteFooter.setGoogleMaps( dto.getGoogleMaps() ); return siteFooter; } @Override public SiteFooterDTO toDto(SiteFooter entity) { if ( entity == null ) { return null; } SiteFooterDTO siteFooterDTO = new SiteFooterDTO(); siteFooterDTO.setId( entity.getId() ); siteFooterDTO.setAddress( entity.getAddress() ); siteFooterDTO.setContact( entity.getContact() ); siteFooterDTO.setLinks( entity.getLinks() ); siteFooterDTO.setMoreContent( entity.getMoreContent() ); siteFooterDTO.setGoogleMaps( entity.getGoogleMaps() ); return siteFooterDTO; } @Override public List<SiteFooter> toEntity(List<SiteFooterDTO> dtoList) { if ( dtoList == null ) { return null; } List<SiteFooter> list = new ArrayList<SiteFooter>( dtoList.size() ); for ( SiteFooterDTO siteFooterDTO : dtoList ) { list.add( toEntity( siteFooterDTO ) ); } return list; } @Override public List<SiteFooterDTO> toDto(List<SiteFooter> entityList) { if ( entityList == null ) { return null; } List<SiteFooterDTO> list = new ArrayList<SiteFooterDTO>( entityList.size() ); for ( SiteFooter siteFooter : entityList ) { list.add( toDto( siteFooter ) ); } return list; } } <file_sep>/src/main/java/com/gob/scjn/repository/ActivityRepository.java package com.gob.scjn.repository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.gob.scjn.domain.Activity; /** * Spring Data repository for the Activity entity. */ @SuppressWarnings("unused") @Repository public interface ActivityRepository extends JpaRepository<Activity, Long> { Page<Activity> findByEventId(Long id, Pageable pageable); } <file_sep>/src/main/java/com/gob/scjn/domain/enumeration/PageStatus.java package com.gob.scjn.domain.enumeration; /** * The PageStatus enumeration. */ public enum PageStatus { PUBLISHED, DELETED, NOT_PUBLISHED } <file_sep>/src/main/java/com/gob/scjn/service/CMSService.java package com.gob.scjn.service; import com.gob.scjn.service.dto.CMSDTO; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.Optional; /** * Service Interface for managing CMS. */ public interface CMSService { /** * Save a cMS. * * @param cMSDTO the entity to save * @return the persisted entity */ CMSDTO save(CMSDTO cMSDTO); /** * Get all the cMS. * * @param pageable the pagination information * @return the list of entities */ Page<CMSDTO> findAll(Pageable pageable); /** * Get the "id" cMS. * * @param id the id of the entity * @return the entity */ Optional<CMSDTO> findOne(Long id); /** * Delete the "id" cMS. * * @param id the id of the entity */ void delete(Long id); } <file_sep>/.apt_generated/com/gob/scjn/service/mapper/EventLanguageMapperImpl.java package com.gob.scjn.service.mapper; import com.gob.scjn.domain.EventLanguage; import com.gob.scjn.service.dto.EventLanguageDTO; import java.util.ArrayList; import java.util.List; import javax.annotation.Generated; import org.springframework.stereotype.Component; @Generated( value = "org.mapstruct.ap.MappingProcessor", date = "2018-07-24T19:22:06-0500", comments = "version: 1.2.0.Final, compiler: Eclipse JDT (IDE) 3.12.3.v20170228-1205, environment: Java 1.8.0_171 (Oracle Corporation)" ) @Component public class EventLanguageMapperImpl implements EventLanguageMapper { @Override public List<EventLanguageDTO> toDto(List<EventLanguage> arg0) { if ( arg0 == null ) { return null; } List<EventLanguageDTO> list = new ArrayList<EventLanguageDTO>( arg0.size() ); for ( EventLanguage eventLanguage : arg0 ) { list.add( toDto( eventLanguage ) ); } return list; } @Override public List<EventLanguage> toEntity(List<EventLanguageDTO> arg0) { if ( arg0 == null ) { return null; } List<EventLanguage> list = new ArrayList<EventLanguage>( arg0.size() ); for ( EventLanguageDTO eventLanguageDTO : arg0 ) { list.add( toEntity( eventLanguageDTO ) ); } return list; } @Override public EventLanguageDTO toDto(EventLanguage eventLanguage) { if ( eventLanguage == null ) { return null; } EventLanguageDTO eventLanguageDTO = new EventLanguageDTO(); eventLanguageDTO.setAddress( eventLanguage.getAddress() ); eventLanguageDTO.setDescription( eventLanguage.getDescription() ); eventLanguageDTO.setEvent( eventLanguage.getEvent() ); eventLanguageDTO.setId( eventLanguage.getId() ); eventLanguageDTO.setLanguage( eventLanguage.getLanguage() ); eventLanguageDTO.setName( eventLanguage.getName() ); return eventLanguageDTO; } @Override public EventLanguage toEntity(EventLanguageDTO eventLanguageDTO) { if ( eventLanguageDTO == null ) { return null; } EventLanguage eventLanguage = new EventLanguage(); eventLanguage.setAddress( eventLanguageDTO.getAddress() ); eventLanguage.setDescription( eventLanguageDTO.getDescription() ); eventLanguage.setEvent( eventLanguageDTO.getEvent() ); eventLanguage.setId( eventLanguageDTO.getId() ); eventLanguage.setLanguage( eventLanguageDTO.getLanguage() ); eventLanguage.setName( eventLanguageDTO.getName() ); return eventLanguage; } } <file_sep>/src/main/java/com/gob/scjn/repository/SitePageRepository.java package com.gob.scjn.repository; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.gob.scjn.domain.SitePage; /** * Spring Data repository for the SitePage entity. */ @SuppressWarnings("unused") @Repository public interface SitePageRepository extends JpaRepository<SitePage, Long> { Optional<SitePage> findBySiteId(Long id); } <file_sep>/.apt_generated/com/gob/scjn/domain/MenuItems_.java package com.gob.scjn.domain; import javax.annotation.Generated; import javax.persistence.metamodel.SetAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor") @StaticMetamodel(MenuItems.class) public abstract class MenuItems_ { public static volatile SetAttribute<MenuItems, MenuItemsLanguage> languages; public static volatile SingularAttribute<MenuItems, Integer> weight; public static volatile SingularAttribute<MenuItems, Long> id; public static volatile SingularAttribute<MenuItems, Menu> menu; public static volatile SingularAttribute<MenuItems, String> url; } <file_sep>/src/main/java/com/gob/scjn/service/impl/SitePageServiceImpl.java package com.gob.scjn.service.impl; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.gob.scjn.domain.SitePage; import com.gob.scjn.repository.SitePageRepository; import com.gob.scjn.service.SitePageService; import com.gob.scjn.service.dto.SitePageDTO; import com.gob.scjn.service.mapper.SitePageMapper; import com.gob.scjn.web.rest.errors.BadRequestAlertException; /** * Service Implementation for managing SitePage. */ @Service @Transactional public class SitePageServiceImpl implements SitePageService { private final Logger log = LoggerFactory.getLogger(SitePageServiceImpl.class); private final SitePageRepository sitePageRepository; private final SitePageMapper sitePageMapper; public SitePageServiceImpl(SitePageRepository sitePageRepository, SitePageMapper sitePageMapper) { this.sitePageRepository = sitePageRepository; this.sitePageMapper = sitePageMapper; } /** * Save a sitePage. * * @param sitePageDTO the entity to save * @return the persisted entity */ @Override public SitePageDTO save(Long id, SitePageDTO sitePageDTO) { log.debug("Request to save SitePage : {}", sitePageDTO); sitePageDTO.setSiteId(id); SitePage sitePage = sitePageMapper.toEntity(sitePageDTO); sitePage = sitePageRepository.save(sitePage); return sitePageMapper.toDto(sitePage); } @Override public SitePageDTO save(Long id, Long pageId, SitePageDTO sitePageDTO) { log.debug("Request to save SitePage : {}", sitePageDTO); sitePageDTO.setSiteId(id); sitePageDTO.setId(pageId); SitePage sitePage = sitePageMapper.toEntity(sitePageDTO); sitePage = sitePageRepository.save(sitePage); return sitePageMapper.toDto(sitePage); } /** * Get all the sitePages. * * @param pageable the pagination information * @return the list of entities */ @Override @Transactional(readOnly = true) public Page<SitePageDTO> findAll(Pageable pageable) { log.debug("Request to get all SitePages"); return sitePageRepository.findAll(pageable) .map(sitePageMapper::toDto); } /** * Get one sitePage by id. * * @param id the id of the entity * @return the entity */ @Override @Transactional(readOnly = true) public Optional<SitePageDTO> findOne(Long id, Long pageId) { log.debug("Request to get SitePage : {}", id); return sitePageRepository.findById(id) .map(sitePageMapper::toDto); } /** * Delete the sitePage by id. * * @param id the id of the entity */ @Override public void delete(Long id, Long pageId) { log.debug("Request to delete SitePage : {}", id); sitePageRepository.deleteById(id); } public void validateSite(Long pageId) { sitePageRepository.findBySiteId(pageId).orElseThrow(() -> new BadRequestAlertException("No site found","Site Page","404")); } } <file_sep>/src/main/java/com/gob/scjn/service/impl/EventLanguageServiceImpl.java package com.gob.scjn.service.impl; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.gob.scjn.domain.EventLanguage; import com.gob.scjn.repository.EventLanguageRepository; import com.gob.scjn.service.EventLanguageService; import com.gob.scjn.service.dto.EventLanguageDTO; import com.gob.scjn.service.mapper.EventLanguageMapper; /** * Service Implementation for managing EventLanguage. */ @Service @Transactional public class EventLanguageServiceImpl implements EventLanguageService { private final Logger log = LoggerFactory.getLogger(EventLanguageServiceImpl.class); private final EventLanguageRepository eventLanguageRepository; private final EventLanguageMapper eventLanguageMapper; public EventLanguageServiceImpl(EventLanguageRepository eventLanguageRepository, EventLanguageMapper eventLanguageMapper) { this.eventLanguageRepository = eventLanguageRepository; this.eventLanguageMapper = eventLanguageMapper; } /** * Save a eventLanguage. * * @param eventLanguageDTO * the entity to save * @return the persisted entity */ @Override public EventLanguageDTO save(EventLanguageDTO eventLanguageDTO) { log.debug("Request to save EventLanguage : {}", eventLanguageDTO); EventLanguage eventLanguage = eventLanguageMapper.toEntity(eventLanguageDTO); eventLanguage = eventLanguageRepository.save(eventLanguage); return eventLanguageMapper.toDto(eventLanguage); } /** * Get all the eventLanguages. * * @param pageable * the pagination information * @return the list of entities */ @Override @Transactional(readOnly = true) public Page<EventLanguageDTO> findAll(Pageable pageable) { log.debug("Request to get all EventLanguages"); return eventLanguageRepository.findAll(pageable).map(eventLanguageMapper::toDto); } /** * Get one eventLanguage by id. * * @param id * the id of the entity * @return the entity */ @Override @Transactional(readOnly = true) public Optional<EventLanguageDTO> findOne(Long id) { log.debug("Request to get EventLanguage : {}", id); return eventLanguageRepository.findById(id).map(eventLanguageMapper::toDto); } /** * Delete the eventLanguage by id. * * @param id * the id of the entity */ @Override public void delete(Long id) { log.debug("Request to delete EventLanguage : {}", id); eventLanguageRepository.deleteById(id); } } <file_sep>/src/main/java/com/gob/scjn/service/mapper/SiteFooterMapper.java package com.gob.scjn.service.mapper; import com.gob.scjn.domain.*; import com.gob.scjn.service.dto.SiteFooterDTO; import org.mapstruct.*; /** * Mapper for the entity SiteFooter and its DTO SiteFooterDTO. */ @Mapper(componentModel = "spring", uses = {}) public interface SiteFooterMapper extends EntityMapper<SiteFooterDTO, SiteFooter> { default SiteFooter fromId(Long id) { if (id == null) { return null; } SiteFooter siteFooter = new SiteFooter(); siteFooter.setId(id); return siteFooter; } } <file_sep>/src/main/java/com/gob/scjn/service/dto/MenuItemsDTO.java package com.gob.scjn.service.dto; import java.io.Serializable; import java.util.HashSet; import java.util.Objects; import java.util.Set; /** * A DTO for the MenuItems entity. */ public class MenuItemsDTO implements Serializable { private Long id; private Integer weight; private String url; private Set<MenuItemsLanguageDTO> languages = new HashSet<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getWeight() { return weight; } public void setWeight(Integer weight) { this.weight = weight; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Set<MenuItemsLanguageDTO> getLanguages() { return languages; } public void setLanguages(Set<MenuItemsLanguageDTO> languages) { this.languages = languages; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MenuItemsDTO menuItemsDTO = (MenuItemsDTO) o; if (menuItemsDTO.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), menuItemsDTO.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "MenuItemsDTO [id=" + id + ", weight=" + weight + ", url=" + url + ", languages=" + languages + "]"; } } <file_sep>/.apt_generated/com/gob/scjn/domain/SitePageLanguage_.java package com.gob.scjn.domain; import com.gob.scjn.domain.enumeration.Language; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor") @StaticMetamodel(SitePageLanguage.class) public abstract class SitePageLanguage_ { public static volatile SingularAttribute<SitePageLanguage, String> exceptPage; public static volatile SingularAttribute<SitePageLanguage, Language> language; public static volatile SingularAttribute<SitePageLanguage, SitePage> sitePage; public static volatile SingularAttribute<SitePageLanguage, Long> id; public static volatile SingularAttribute<SitePageLanguage, String> title; public static volatile SingularAttribute<SitePageLanguage, String> content; } <file_sep>/src/main/java/com/gob/scjn/service/impl/MenuItemsLanguageServiceImpl.java package com.gob.scjn.service.impl; import com.gob.scjn.service.MenuItemsLanguageService; import com.gob.scjn.domain.MenuItemsLanguage; import com.gob.scjn.repository.MenuItemsLanguageRepository; import com.gob.scjn.service.dto.MenuItemsLanguageDTO; import com.gob.scjn.service.mapper.MenuItemsLanguageMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * Service Implementation for managing MenuItemsLanguage. */ @Service @Transactional public class MenuItemsLanguageServiceImpl implements MenuItemsLanguageService { private final Logger log = LoggerFactory.getLogger(MenuItemsLanguageServiceImpl.class); private final MenuItemsLanguageRepository menuItemsLanguageRepository; private final MenuItemsLanguageMapper menuItemsLanguageMapper; public MenuItemsLanguageServiceImpl(MenuItemsLanguageRepository menuItemsLanguageRepository, MenuItemsLanguageMapper menuItemsLanguageMapper) { this.menuItemsLanguageRepository = menuItemsLanguageRepository; this.menuItemsLanguageMapper = menuItemsLanguageMapper; } /** * Save a menuItemsLanguage. * * @param menuItemsLanguageDTO the entity to save * @return the persisted entity */ @Override public MenuItemsLanguageDTO save(MenuItemsLanguageDTO menuItemsLanguageDTO) { log.debug("Request to save MenuItemsLanguage : {}", menuItemsLanguageDTO); MenuItemsLanguage menuItemsLanguage = menuItemsLanguageMapper.toEntity(menuItemsLanguageDTO); menuItemsLanguage = menuItemsLanguageRepository.save(menuItemsLanguage); return menuItemsLanguageMapper.toDto(menuItemsLanguage); } /** * Get all the menuItemsLanguages. * * @return the list of entities */ @Override @Transactional(readOnly = true) public List<MenuItemsLanguageDTO> findAll() { log.debug("Request to get all MenuItemsLanguages"); return menuItemsLanguageRepository.findAll().stream() .map(menuItemsLanguageMapper::toDto) .collect(Collectors.toCollection(LinkedList::new)); } /** * Get one menuItemsLanguage by id. * * @param id the id of the entity * @return the entity */ @Override @Transactional(readOnly = true) public Optional<MenuItemsLanguageDTO> findOne(Long id) { log.debug("Request to get MenuItemsLanguage : {}", id); return menuItemsLanguageRepository.findById(id) .map(menuItemsLanguageMapper::toDto); } /** * Delete the menuItemsLanguage by id. * * @param id the id of the entity */ @Override public void delete(Long id) { log.debug("Request to delete MenuItemsLanguage : {}", id); menuItemsLanguageRepository.deleteById(id); } } <file_sep>/src/main/java/com/gob/scjn/domain/SitePage.java package com.gob.scjn.domain; import java.io.Serializable; import java.time.Instant; import java.util.HashSet; import java.util.Objects; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * A SitePage. */ @Entity @Table(name = "site_page") public class SitePage implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "creation_date") private Instant creationDate; @Column(name = "updated_date") private Instant updatedDate; @Column(name = "menu_entry") private String menuEntry; @Column(name = "jhi_order") private Long order; @Column(name = "status") private Boolean status; @Column(name = "slug") private String slug; @ManyToOne @JsonIgnoreProperties("sitePages") private Site site; @OneToMany(cascade = CascadeType.ALL) @JoinColumn(name="site_page_id") private Set<SitePageLanguage> languages = new HashSet<>(); @OneToMany(mappedBy = "sitePage") private Set<CMS> cms = new HashSet<>(); // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Instant getCreationDate() { return creationDate; } public SitePage creationDate(Instant creationDate) { this.creationDate = creationDate; return this; } public void setCreationDate(Instant creationDate) { this.creationDate = creationDate; } public Instant getUpdatedDate() { return updatedDate; } public SitePage updatedDate(Instant updatedDate) { this.updatedDate = updatedDate; return this; } public void setUpdatedDate(Instant updatedDate) { this.updatedDate = updatedDate; } public String getMenuEntry() { return menuEntry; } public SitePage menuEntry(String menuEntry) { this.menuEntry = menuEntry; return this; } public void setMenuEntry(String menuEntry) { this.menuEntry = menuEntry; } public Long getOrder() { return order; } public SitePage order(Long order) { this.order = order; return this; } public void setOrder(Long order) { this.order = order; } public Boolean isStatus() { return status; } public SitePage status(Boolean status) { this.status = status; return this; } public void setStatus(Boolean status) { this.status = status; } public String getSlug() { return slug; } public SitePage slug(String slug) { this.slug = slug; return this; } public void setSlug(String slug) { this.slug = slug; } public Site getSite() { return site; } public SitePage site(Site site) { this.site = site; return this; } public void setSite(Site site) { this.site = site; } public Set<SitePageLanguage> getPages() { return languages; } public SitePage pages(Set<SitePageLanguage> sitePageLanguages) { this.languages = sitePageLanguages; return this; } public SitePage removePage(SitePageLanguage sitePageLanguage) { this.languages.remove(sitePageLanguage); sitePageLanguage.setSitePage(null); return this; } public void setPages(Set<SitePageLanguage> sitePageLanguages) { this.languages = sitePageLanguages; } public Set<CMS> getCms() { return cms; } public SitePage cms(Set<CMS> cMS) { this.cms = cMS; return this; } public SitePage addCms(CMS cMS) { this.cms.add(cMS); cMS.setSitePage(this); return this; } public SitePage removeCms(CMS cMS) { this.cms.remove(cMS); cMS.setSitePage(null); return this; } public void setCms(Set<CMS> cMS) { this.cms = cMS; } public Set<SitePageLanguage> getLanguages() { return languages; } public void setLanguages(Set<SitePageLanguage> languages) { this.languages = languages; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SitePage sitePage = (SitePage) o; if (sitePage.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), sitePage.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "SitePage [id=" + id + ", creationDate=" + creationDate + ", updatedDate=" + updatedDate + ", menuEntry=" + menuEntry + ", order=" + order + ", status=" + status + ", slug=" + slug + ", site=" + site + ", languages=" + languages + ", cms=" + cms + "]"; } }
62ba6ad98f66d3e523bbd979633e11a532b90821
[ "Java" ]
60
Java
LuisPerez0790/event
e808be4283cf9716ee9256083e177f0b36e34a32
b6434f8914b3e287b10cccde9a34cf9688d6ed6a